blob: 3ec31f83da6fe5a969097230b0223e10c80cd712 [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*/
drh60f34ae2018-10-30 13:19:49 +00001062#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 */
1066#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1067#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
drh1fa6d9f2018-01-06 21:46:01 +00001068
drh2ce15c32017-07-11 13:34:40 +00001069/*
1070** These are the allowed shellFlgs values
1071*/
drhb2a0f752017-08-28 15:51:35 +00001072#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1073#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1074#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1075#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1076#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1077#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1078#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
drh2ce15c32017-07-11 13:34:40 +00001079
1080/*
1081** Macros for testing and setting shellFlgs
1082*/
1083#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1084#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1085#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1086
1087/*
1088** These are the allowed modes.
1089*/
1090#define MODE_Line 0 /* One column per line. Blank line between records */
1091#define MODE_Column 1 /* One record per line in neat columns */
1092#define MODE_List 2 /* One record per line with a separator */
1093#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1094#define MODE_Html 4 /* Generate an XHTML table */
1095#define MODE_Insert 5 /* Generate SQL "insert" statements */
1096#define MODE_Quote 6 /* Quote values as for SQL */
1097#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1098#define MODE_Csv 8 /* Quote strings, numbers are plain */
1099#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1100#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1101#define MODE_Pretty 11 /* Pretty-print schemas */
drh4b5345c2018-04-24 13:07:40 +00001102#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
drh2ce15c32017-07-11 13:34:40 +00001103
1104static const char *modeDescr[] = {
1105 "line",
1106 "column",
1107 "list",
1108 "semi",
1109 "html",
1110 "insert",
1111 "quote",
1112 "tcl",
1113 "csv",
1114 "explain",
1115 "ascii",
1116 "prettyprint",
drh4b5345c2018-04-24 13:07:40 +00001117 "eqp"
drh2ce15c32017-07-11 13:34:40 +00001118};
1119
1120/*
1121** These are the column/row/line separators used by the various
1122** import/export modes.
1123*/
1124#define SEP_Column "|"
1125#define SEP_Row "\n"
1126#define SEP_Tab "\t"
1127#define SEP_Space " "
1128#define SEP_Comma ","
1129#define SEP_CrLf "\r\n"
1130#define SEP_Unit "\x1F"
1131#define SEP_Record "\x1E"
1132
1133/*
drh2ce15c32017-07-11 13:34:40 +00001134** A callback for the sqlite3_log() interface.
1135*/
1136static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1137 ShellState *p = (ShellState*)pArg;
1138 if( p->pLog==0 ) return;
1139 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1140 fflush(p->pLog);
1141}
1142
1143/*
drh634c70f2018-01-10 16:50:18 +00001144** SQL function: shell_putsnl(X)
1145**
1146** Write the text X to the screen (or whatever output is being directed)
1147** adding a newline at the end, and then return X.
1148*/
1149static void shellPutsFunc(
1150 sqlite3_context *pCtx,
1151 int nVal,
1152 sqlite3_value **apVal
1153){
1154 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
drhb9685182018-01-17 13:15:23 +00001155 (void)nVal;
drh634c70f2018-01-10 16:50:18 +00001156 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1157 sqlite3_result_value(pCtx, apVal[0]);
1158}
1159
1160/*
drh97913132018-01-11 00:04:00 +00001161** SQL function: edit(VALUE)
1162** edit(VALUE,EDITOR)
1163**
1164** These steps:
1165**
1166** (1) Write VALUE into a temporary file.
1167** (2) Run program EDITOR on that temporary file.
1168** (3) Read the temporary file back and return its content as the result.
1169** (4) Delete the temporary file
1170**
1171** If the EDITOR argument is omitted, use the value in the VISUAL
1172** environment variable. If still there is no EDITOR, through an error.
1173**
1174** Also throw an error if the EDITOR program returns a non-zero exit code.
1175*/
drh04a28c32018-01-31 01:38:44 +00001176#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00001177static void editFunc(
1178 sqlite3_context *context,
1179 int argc,
1180 sqlite3_value **argv
1181){
1182 const char *zEditor;
1183 char *zTempFile = 0;
1184 sqlite3 *db;
1185 char *zCmd = 0;
1186 int bBin;
1187 int rc;
drhf018fd52018-08-06 02:08:53 +00001188 int hasCRNL = 0;
drh97913132018-01-11 00:04:00 +00001189 FILE *f = 0;
1190 sqlite3_int64 sz;
1191 sqlite3_int64 x;
1192 unsigned char *p = 0;
1193
1194 if( argc==2 ){
1195 zEditor = (const char*)sqlite3_value_text(argv[1]);
1196 }else{
1197 zEditor = getenv("VISUAL");
1198 }
1199 if( zEditor==0 ){
1200 sqlite3_result_error(context, "no editor for edit()", -1);
1201 return;
1202 }
1203 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1204 sqlite3_result_error(context, "NULL input to edit()", -1);
1205 return;
1206 }
1207 db = sqlite3_context_db_handle(context);
1208 zTempFile = 0;
1209 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1210 if( zTempFile==0 ){
1211 sqlite3_uint64 r = 0;
1212 sqlite3_randomness(sizeof(r), &r);
1213 zTempFile = sqlite3_mprintf("temp%llx", r);
1214 if( zTempFile==0 ){
1215 sqlite3_result_error_nomem(context);
1216 return;
1217 }
1218 }
1219 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
drhf018fd52018-08-06 02:08:53 +00001220 /* When writing the file to be edited, do \n to \r\n conversions on systems
1221 ** that want \r\n line endings */
drh97913132018-01-11 00:04:00 +00001222 f = fopen(zTempFile, bBin ? "wb" : "w");
1223 if( f==0 ){
1224 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1225 goto edit_func_end;
1226 }
1227 sz = sqlite3_value_bytes(argv[0]);
1228 if( bBin ){
1229 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
1230 }else{
drhf018fd52018-08-06 02:08:53 +00001231 const char *z = (const char*)sqlite3_value_text(argv[0]);
1232 /* Remember whether or not the value originally contained \r\n */
1233 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
drh97913132018-01-11 00:04:00 +00001234 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
1235 }
1236 fclose(f);
1237 f = 0;
1238 if( x!=sz ){
1239 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1240 goto edit_func_end;
1241 }
1242 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1243 if( zCmd==0 ){
1244 sqlite3_result_error_nomem(context);
1245 goto edit_func_end;
1246 }
1247 rc = system(zCmd);
1248 sqlite3_free(zCmd);
1249 if( rc ){
1250 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1251 goto edit_func_end;
1252 }
drhf018fd52018-08-06 02:08:53 +00001253 f = fopen(zTempFile, "rb");
drh97913132018-01-11 00:04:00 +00001254 if( f==0 ){
1255 sqlite3_result_error(context,
1256 "edit() cannot reopen temp file after edit", -1);
1257 goto edit_func_end;
1258 }
1259 fseek(f, 0, SEEK_END);
1260 sz = ftell(f);
1261 rewind(f);
1262 p = sqlite3_malloc64( sz+(bBin==0) );
1263 if( p==0 ){
1264 sqlite3_result_error_nomem(context);
1265 goto edit_func_end;
1266 }
drhf018fd52018-08-06 02:08:53 +00001267 x = fread(p, 1, sz, f);
drh97913132018-01-11 00:04:00 +00001268 fclose(f);
1269 f = 0;
1270 if( x!=sz ){
1271 sqlite3_result_error(context, "could not read back the whole file", -1);
1272 goto edit_func_end;
1273 }
1274 if( bBin ){
mistachkinb71aa092018-01-23 00:05:18 +00001275 sqlite3_result_blob64(context, p, sz, sqlite3_free);
drh97913132018-01-11 00:04:00 +00001276 }else{
dan60bdcf52018-10-03 11:13:30 +00001277 sqlite3_int64 i, j;
drhf018fd52018-08-06 02:08:53 +00001278 if( hasCRNL ){
1279 /* If the original contains \r\n then do no conversions back to \n */
1280 j = sz;
1281 }else{
1282 /* If the file did not originally contain \r\n then convert any new
1283 ** \r\n back into \n */
1284 for(i=j=0; i<sz; i++){
1285 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1286 p[j++] = p[i];
1287 }
1288 sz = j;
1289 p[sz] = 0;
1290 }
mistachkinb71aa092018-01-23 00:05:18 +00001291 sqlite3_result_text64(context, (const char*)p, sz,
1292 sqlite3_free, SQLITE_UTF8);
drh97913132018-01-11 00:04:00 +00001293 }
1294 p = 0;
1295
1296edit_func_end:
1297 if( f ) fclose(f);
1298 unlink(zTempFile);
1299 sqlite3_free(zTempFile);
1300 sqlite3_free(p);
1301}
drh04a28c32018-01-31 01:38:44 +00001302#endif /* SQLITE_NOHAVE_SYSTEM */
drh97913132018-01-11 00:04:00 +00001303
1304/*
drh3c484e82018-01-10 22:27:21 +00001305** Save or restore the current output mode
1306*/
1307static void outputModePush(ShellState *p){
1308 p->modePrior = p->mode;
1309 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1310 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1311}
1312static void outputModePop(ShellState *p){
1313 p->mode = p->modePrior;
1314 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1315 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1316}
1317
1318/*
drh2ce15c32017-07-11 13:34:40 +00001319** Output the given string as a hex-encoded blob (eg. X'1234' )
1320*/
1321static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1322 int i;
1323 char *zBlob = (char *)pBlob;
1324 raw_printf(out,"X'");
1325 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1326 raw_printf(out,"'");
1327}
1328
1329/*
1330** Find a string that is not found anywhere in z[]. Return a pointer
1331** to that string.
1332**
1333** Try to use zA and zB first. If both of those are already found in z[]
1334** then make up some string and store it in the buffer zBuf.
1335*/
1336static const char *unused_string(
1337 const char *z, /* Result must not appear anywhere in z */
1338 const char *zA, const char *zB, /* Try these first */
1339 char *zBuf /* Space to store a generated string */
1340){
1341 unsigned i = 0;
1342 if( strstr(z, zA)==0 ) return zA;
1343 if( strstr(z, zB)==0 ) return zB;
1344 do{
1345 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1346 }while( strstr(z,zBuf)!=0 );
1347 return zBuf;
1348}
1349
1350/*
1351** Output the given string as a quoted string using SQL quoting conventions.
1352**
1353** See also: output_quoted_escaped_string()
1354*/
1355static void output_quoted_string(FILE *out, const char *z){
1356 int i;
1357 char c;
1358 setBinaryMode(out, 1);
1359 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1360 if( c==0 ){
1361 utf8_printf(out,"'%s'",z);
1362 }else{
1363 raw_printf(out, "'");
1364 while( *z ){
1365 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1366 if( c=='\'' ) i++;
1367 if( i ){
1368 utf8_printf(out, "%.*s", i, z);
1369 z += i;
1370 }
1371 if( c=='\'' ){
1372 raw_printf(out, "'");
1373 continue;
1374 }
1375 if( c==0 ){
1376 break;
1377 }
1378 z++;
1379 }
1380 raw_printf(out, "'");
1381 }
1382 setTextMode(out, 1);
1383}
1384
1385/*
1386** Output the given string as a quoted string using SQL quoting conventions.
1387** Additionallly , escape the "\n" and "\r" characters so that they do not
1388** get corrupted by end-of-line translation facilities in some operating
1389** systems.
1390**
1391** This is like output_quoted_string() but with the addition of the \r\n
1392** escape mechanism.
1393*/
1394static void output_quoted_escaped_string(FILE *out, const char *z){
1395 int i;
1396 char c;
1397 setBinaryMode(out, 1);
1398 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1399 if( c==0 ){
1400 utf8_printf(out,"'%s'",z);
1401 }else{
1402 const char *zNL = 0;
1403 const char *zCR = 0;
1404 int nNL = 0;
1405 int nCR = 0;
1406 char zBuf1[20], zBuf2[20];
1407 for(i=0; z[i]; i++){
1408 if( z[i]=='\n' ) nNL++;
1409 if( z[i]=='\r' ) nCR++;
1410 }
1411 if( nNL ){
1412 raw_printf(out, "replace(");
1413 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1414 }
1415 if( nCR ){
1416 raw_printf(out, "replace(");
1417 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1418 }
1419 raw_printf(out, "'");
1420 while( *z ){
1421 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1422 if( c=='\'' ) i++;
1423 if( i ){
1424 utf8_printf(out, "%.*s", i, z);
1425 z += i;
1426 }
1427 if( c=='\'' ){
1428 raw_printf(out, "'");
1429 continue;
1430 }
1431 if( c==0 ){
1432 break;
1433 }
1434 z++;
1435 if( c=='\n' ){
1436 raw_printf(out, "%s", zNL);
1437 continue;
1438 }
1439 raw_printf(out, "%s", zCR);
1440 }
1441 raw_printf(out, "'");
1442 if( nCR ){
1443 raw_printf(out, ",'%s',char(13))", zCR);
1444 }
1445 if( nNL ){
1446 raw_printf(out, ",'%s',char(10))", zNL);
1447 }
1448 }
1449 setTextMode(out, 1);
1450}
1451
1452/*
1453** Output the given string as a quoted according to C or TCL quoting rules.
1454*/
1455static void output_c_string(FILE *out, const char *z){
1456 unsigned int c;
1457 fputc('"', out);
1458 while( (c = *(z++))!=0 ){
1459 if( c=='\\' ){
1460 fputc(c, out);
1461 fputc(c, out);
1462 }else if( c=='"' ){
1463 fputc('\\', out);
1464 fputc('"', out);
1465 }else if( c=='\t' ){
1466 fputc('\\', out);
1467 fputc('t', out);
1468 }else if( c=='\n' ){
1469 fputc('\\', out);
1470 fputc('n', out);
1471 }else if( c=='\r' ){
1472 fputc('\\', out);
1473 fputc('r', out);
1474 }else if( !isprint(c&0xff) ){
1475 raw_printf(out, "\\%03o", c&0xff);
1476 }else{
1477 fputc(c, out);
1478 }
1479 }
1480 fputc('"', out);
1481}
1482
1483/*
1484** Output the given string with characters that are special to
1485** HTML escaped.
1486*/
1487static void output_html_string(FILE *out, const char *z){
1488 int i;
1489 if( z==0 ) z = "";
1490 while( *z ){
1491 for(i=0; z[i]
1492 && z[i]!='<'
1493 && z[i]!='&'
1494 && z[i]!='>'
1495 && z[i]!='\"'
1496 && z[i]!='\'';
1497 i++){}
1498 if( i>0 ){
1499 utf8_printf(out,"%.*s",i,z);
1500 }
1501 if( z[i]=='<' ){
1502 raw_printf(out,"&lt;");
1503 }else if( z[i]=='&' ){
1504 raw_printf(out,"&amp;");
1505 }else if( z[i]=='>' ){
1506 raw_printf(out,"&gt;");
1507 }else if( z[i]=='\"' ){
1508 raw_printf(out,"&quot;");
1509 }else if( z[i]=='\'' ){
1510 raw_printf(out,"&#39;");
1511 }else{
1512 break;
1513 }
1514 z += i + 1;
1515 }
1516}
1517
1518/*
1519** If a field contains any character identified by a 1 in the following
1520** array, then the string must be quoted for CSV.
1521*/
1522static const char needCsvQuote[] = {
1523 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1525 1, 0, 1, 0, 0, 0, 0, 1, 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, 0,
1530 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1539};
1540
1541/*
1542** Output a single term of CSV. Actually, p->colSeparator is used for
1543** the separator, which may or may not be a comma. p->nullValue is
1544** the null value. Strings are quoted if necessary. The separator
1545** is only issued if bSep is true.
1546*/
1547static void output_csv(ShellState *p, const char *z, int bSep){
1548 FILE *out = p->out;
1549 if( z==0 ){
1550 utf8_printf(out,"%s",p->nullValue);
1551 }else{
1552 int i;
1553 int nSep = strlen30(p->colSeparator);
1554 for(i=0; z[i]; i++){
1555 if( needCsvQuote[((unsigned char*)z)[i]]
1556 || (z[i]==p->colSeparator[0] &&
1557 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1558 i = 0;
1559 break;
1560 }
1561 }
1562 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001563 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1564 utf8_printf(out, "%s", zQuoted);
1565 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001566 }else{
1567 utf8_printf(out, "%s", z);
1568 }
1569 }
1570 if( bSep ){
1571 utf8_printf(p->out, "%s", p->colSeparator);
1572 }
1573}
1574
drh2ce15c32017-07-11 13:34:40 +00001575/*
1576** This routine runs when the user presses Ctrl-C
1577*/
1578static void interrupt_handler(int NotUsed){
1579 UNUSED_PARAMETER(NotUsed);
1580 seenInterrupt++;
1581 if( seenInterrupt>2 ) exit(1);
1582 if( globalDb ) sqlite3_interrupt(globalDb);
1583}
mistachkinb4bab902017-10-27 17:09:44 +00001584
1585#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1586/*
1587** This routine runs for console events (e.g. Ctrl-C) on Win32
1588*/
1589static BOOL WINAPI ConsoleCtrlHandler(
1590 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1591){
1592 if( dwCtrlType==CTRL_C_EVENT ){
1593 interrupt_handler(0);
1594 return TRUE;
1595 }
1596 return FALSE;
1597}
drh2ce15c32017-07-11 13:34:40 +00001598#endif
1599
1600#ifndef SQLITE_OMIT_AUTHORIZATION
1601/*
1602** When the ".auth ON" is set, the following authorizer callback is
1603** invoked. It always returns SQLITE_OK.
1604*/
1605static int shellAuth(
1606 void *pClientData,
1607 int op,
1608 const char *zA1,
1609 const char *zA2,
1610 const char *zA3,
1611 const char *zA4
1612){
1613 ShellState *p = (ShellState*)pClientData;
1614 static const char *azAction[] = { 0,
1615 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1616 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1617 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1618 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1619 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1620 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1621 "PRAGMA", "READ", "SELECT",
1622 "TRANSACTION", "UPDATE", "ATTACH",
1623 "DETACH", "ALTER_TABLE", "REINDEX",
1624 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1625 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1626 };
1627 int i;
1628 const char *az[4];
1629 az[0] = zA1;
1630 az[1] = zA2;
1631 az[2] = zA3;
1632 az[3] = zA4;
1633 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1634 for(i=0; i<4; i++){
1635 raw_printf(p->out, " ");
1636 if( az[i] ){
1637 output_c_string(p->out, az[i]);
1638 }else{
1639 raw_printf(p->out, "NULL");
1640 }
1641 }
1642 raw_printf(p->out, "\n");
1643 return SQLITE_OK;
1644}
1645#endif
1646
1647/*
1648** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1649**
1650** This routine converts some CREATE TABLE statements for shadow tables
1651** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1652*/
1653static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1654 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1655 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1656 }else{
1657 utf8_printf(out, "%s%s", z, zTail);
1658 }
1659}
1660static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1661 char c = z[n];
1662 z[n] = 0;
1663 printSchemaLine(out, z, zTail);
1664 z[n] = c;
1665}
1666
1667/*
drh11be81d2018-01-06 15:46:20 +00001668** Return true if string z[] has nothing but whitespace and comments to the
1669** end of the first line.
1670*/
1671static int wsToEol(const char *z){
1672 int i;
1673 for(i=0; z[i]; i++){
1674 if( z[i]=='\n' ) return 1;
1675 if( IsSpace(z[i]) ) continue;
1676 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1677 return 0;
1678 }
1679 return 1;
1680}
drh4b5345c2018-04-24 13:07:40 +00001681
1682/*
1683** Add a new entry to the EXPLAIN QUERY PLAN data
1684*/
drhe2ca99c2018-05-02 00:33:43 +00001685static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
drh4b5345c2018-04-24 13:07:40 +00001686 EQPGraphRow *pNew;
1687 int nText = strlen30(zText);
drhe2ca99c2018-05-02 00:33:43 +00001688 if( p->autoEQPtest ){
1689 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1690 }
drh4b5345c2018-04-24 13:07:40 +00001691 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1692 if( pNew==0 ) shell_out_of_memory();
drhe2ca99c2018-05-02 00:33:43 +00001693 pNew->iEqpId = iEqpId;
1694 pNew->iParentId = p2;
drh4b5345c2018-04-24 13:07:40 +00001695 memcpy(pNew->zText, zText, nText+1);
1696 pNew->pNext = 0;
1697 if( p->sGraph.pLast ){
1698 p->sGraph.pLast->pNext = pNew;
1699 }else{
1700 p->sGraph.pRow = pNew;
1701 }
1702 p->sGraph.pLast = pNew;
1703}
1704
1705/*
1706** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1707** in p->sGraph.
1708*/
1709static void eqp_reset(ShellState *p){
1710 EQPGraphRow *pRow, *pNext;
1711 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1712 pNext = pRow->pNext;
1713 sqlite3_free(pRow);
1714 }
1715 memset(&p->sGraph, 0, sizeof(p->sGraph));
1716}
1717
drhe2ca99c2018-05-02 00:33:43 +00001718/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
drh4b5345c2018-04-24 13:07:40 +00001719** pOld, or return the first such line if pOld is NULL
1720*/
drhe2ca99c2018-05-02 00:33:43 +00001721static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
drh4b5345c2018-04-24 13:07:40 +00001722 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
drhe2ca99c2018-05-02 00:33:43 +00001723 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
drh4b5345c2018-04-24 13:07:40 +00001724 return pRow;
1725}
1726
drhe2ca99c2018-05-02 00:33:43 +00001727/* Render a single level of the graph that has iEqpId as its parent. Called
drh4b5345c2018-04-24 13:07:40 +00001728** recursively to render sublevels.
1729*/
drhe2ca99c2018-05-02 00:33:43 +00001730static void eqp_render_level(ShellState *p, int iEqpId){
drh4b5345c2018-04-24 13:07:40 +00001731 EQPGraphRow *pRow, *pNext;
drh4b5345c2018-04-24 13:07:40 +00001732 int n = strlen30(p->sGraph.zPrefix);
1733 char *z;
drhe2ca99c2018-05-02 00:33:43 +00001734 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1735 pNext = eqp_next_row(p, iEqpId, pRow);
drh4b5345c2018-04-24 13:07:40 +00001736 z = pRow->zText;
1737 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
drhe2188f02018-05-07 11:37:34 +00001738 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
drh4b5345c2018-04-24 13:07:40 +00001739 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
drhe2ca99c2018-05-02 00:33:43 +00001740 eqp_render_level(p, pRow->iEqpId);
drh4b5345c2018-04-24 13:07:40 +00001741 p->sGraph.zPrefix[n] = 0;
1742 }
1743 }
1744}
1745
1746/*
1747** Display and reset the EXPLAIN QUERY PLAN data
1748*/
1749static void eqp_render(ShellState *p){
1750 EQPGraphRow *pRow = p->sGraph.pRow;
1751 if( pRow ){
1752 if( pRow->zText[0]=='-' ){
1753 if( pRow->pNext==0 ){
1754 eqp_reset(p);
1755 return;
1756 }
1757 utf8_printf(p->out, "%s\n", pRow->zText+3);
1758 p->sGraph.pRow = pRow->pNext;
1759 sqlite3_free(pRow);
1760 }else{
1761 utf8_printf(p->out, "QUERY PLAN\n");
1762 }
1763 p->sGraph.zPrefix[0] = 0;
1764 eqp_render_level(p, 0);
1765 eqp_reset(p);
1766 }
1767}
drh11be81d2018-01-06 15:46:20 +00001768
1769/*
drh2ce15c32017-07-11 13:34:40 +00001770** This is the callback routine that the shell
1771** invokes for each row of a query result.
1772*/
1773static int shell_callback(
1774 void *pArg,
1775 int nArg, /* Number of result columns */
1776 char **azArg, /* Text of each result column */
1777 char **azCol, /* Column names */
1778 int *aiType /* Column types */
1779){
1780 int i;
1781 ShellState *p = (ShellState*)pArg;
1782
drhb3c45232017-08-28 14:33:27 +00001783 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001784 switch( p->cMode ){
1785 case MODE_Line: {
1786 int w = 5;
1787 if( azArg==0 ) break;
1788 for(i=0; i<nArg; i++){
1789 int len = strlen30(azCol[i] ? azCol[i] : "");
1790 if( len>w ) w = len;
1791 }
1792 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1793 for(i=0; i<nArg; i++){
1794 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1795 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1796 }
1797 break;
1798 }
1799 case MODE_Explain:
1800 case MODE_Column: {
1801 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1802 const int *colWidth;
1803 int showHdr;
1804 char *rowSep;
1805 if( p->cMode==MODE_Column ){
1806 colWidth = p->colWidth;
1807 showHdr = p->showHeader;
1808 rowSep = p->rowSeparator;
1809 }else{
1810 colWidth = aExplainWidths;
1811 showHdr = 1;
1812 rowSep = SEP_Row;
1813 }
1814 if( p->cnt++==0 ){
1815 for(i=0; i<nArg; i++){
1816 int w, n;
1817 if( i<ArraySize(p->colWidth) ){
1818 w = colWidth[i];
1819 }else{
1820 w = 0;
1821 }
1822 if( w==0 ){
1823 w = strlenChar(azCol[i] ? azCol[i] : "");
1824 if( w<10 ) w = 10;
1825 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1826 if( w<n ) w = n;
1827 }
1828 if( i<ArraySize(p->actualWidth) ){
1829 p->actualWidth[i] = w;
1830 }
1831 if( showHdr ){
1832 utf8_width_print(p->out, w, azCol[i]);
1833 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1834 }
1835 }
1836 if( showHdr ){
1837 for(i=0; i<nArg; i++){
1838 int w;
1839 if( i<ArraySize(p->actualWidth) ){
1840 w = p->actualWidth[i];
1841 if( w<0 ) w = -w;
1842 }else{
1843 w = 10;
1844 }
1845 utf8_printf(p->out,"%-*.*s%s",w,w,
1846 "----------------------------------------------------------"
1847 "----------------------------------------------------------",
1848 i==nArg-1 ? rowSep : " ");
1849 }
1850 }
1851 }
1852 if( azArg==0 ) break;
1853 for(i=0; i<nArg; i++){
1854 int w;
1855 if( i<ArraySize(p->actualWidth) ){
1856 w = p->actualWidth[i];
1857 }else{
1858 w = 10;
1859 }
1860 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1861 w = strlenChar(azArg[i]);
1862 }
1863 if( i==1 && p->aiIndent && p->pStmt ){
1864 if( p->iIndent<p->nIndent ){
1865 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1866 }
1867 p->iIndent++;
1868 }
1869 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1870 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1871 }
1872 break;
1873 }
1874 case MODE_Semi: { /* .schema and .fullschema output */
1875 printSchemaLine(p->out, azArg[0], ";\n");
1876 break;
1877 }
1878 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1879 char *z;
1880 int j;
1881 int nParen = 0;
1882 char cEnd = 0;
1883 char c;
1884 int nLine = 0;
1885 assert( nArg==1 );
1886 if( azArg[0]==0 ) break;
1887 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1888 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1889 ){
1890 utf8_printf(p->out, "%s;\n", azArg[0]);
1891 break;
1892 }
1893 z = sqlite3_mprintf("%s", azArg[0]);
1894 j = 0;
1895 for(i=0; IsSpace(z[i]); i++){}
1896 for(; (c = z[i])!=0; i++){
1897 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001898 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001899 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1900 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1901 j--;
1902 }
1903 z[j++] = c;
1904 }
1905 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1906 z[j] = 0;
1907 if( strlen30(z)>=79 ){
drh11be81d2018-01-06 15:46:20 +00001908 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001909 if( c==cEnd ){
1910 cEnd = 0;
1911 }else if( c=='"' || c=='\'' || c=='`' ){
1912 cEnd = c;
1913 }else if( c=='[' ){
1914 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001915 }else if( c=='-' && z[i+1]=='-' ){
1916 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001917 }else if( c=='(' ){
1918 nParen++;
1919 }else if( c==')' ){
1920 nParen--;
1921 if( nLine>0 && nParen==0 && j>0 ){
1922 printSchemaLineN(p->out, z, j, "\n");
1923 j = 0;
1924 }
1925 }
1926 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001927 if( nParen==1 && cEnd==0
1928 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1929 ){
drh2ce15c32017-07-11 13:34:40 +00001930 if( c=='\n' ) j--;
1931 printSchemaLineN(p->out, z, j, "\n ");
1932 j = 0;
1933 nLine++;
1934 while( IsSpace(z[i+1]) ){ i++; }
1935 }
1936 }
1937 z[j] = 0;
1938 }
1939 printSchemaLine(p->out, z, ";\n");
1940 sqlite3_free(z);
1941 break;
1942 }
1943 case MODE_List: {
1944 if( p->cnt++==0 && p->showHeader ){
1945 for(i=0; i<nArg; i++){
1946 utf8_printf(p->out,"%s%s",azCol[i],
1947 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1948 }
1949 }
1950 if( azArg==0 ) break;
1951 for(i=0; i<nArg; i++){
1952 char *z = azArg[i];
1953 if( z==0 ) z = p->nullValue;
1954 utf8_printf(p->out, "%s", z);
1955 if( i<nArg-1 ){
1956 utf8_printf(p->out, "%s", p->colSeparator);
1957 }else{
1958 utf8_printf(p->out, "%s", p->rowSeparator);
1959 }
1960 }
1961 break;
1962 }
1963 case MODE_Html: {
1964 if( p->cnt++==0 && p->showHeader ){
1965 raw_printf(p->out,"<TR>");
1966 for(i=0; i<nArg; i++){
1967 raw_printf(p->out,"<TH>");
1968 output_html_string(p->out, azCol[i]);
1969 raw_printf(p->out,"</TH>\n");
1970 }
1971 raw_printf(p->out,"</TR>\n");
1972 }
1973 if( azArg==0 ) break;
1974 raw_printf(p->out,"<TR>");
1975 for(i=0; i<nArg; i++){
1976 raw_printf(p->out,"<TD>");
1977 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1978 raw_printf(p->out,"</TD>\n");
1979 }
1980 raw_printf(p->out,"</TR>\n");
1981 break;
1982 }
1983 case MODE_Tcl: {
1984 if( p->cnt++==0 && p->showHeader ){
1985 for(i=0; i<nArg; i++){
1986 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1987 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1988 }
1989 utf8_printf(p->out, "%s", p->rowSeparator);
1990 }
1991 if( azArg==0 ) break;
1992 for(i=0; i<nArg; i++){
1993 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1994 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1995 }
1996 utf8_printf(p->out, "%s", p->rowSeparator);
1997 break;
1998 }
1999 case MODE_Csv: {
2000 setBinaryMode(p->out, 1);
2001 if( p->cnt++==0 && p->showHeader ){
2002 for(i=0; i<nArg; i++){
2003 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2004 }
2005 utf8_printf(p->out, "%s", p->rowSeparator);
2006 }
2007 if( nArg>0 ){
2008 for(i=0; i<nArg; i++){
2009 output_csv(p, azArg[i], i<nArg-1);
2010 }
2011 utf8_printf(p->out, "%s", p->rowSeparator);
2012 }
2013 setTextMode(p->out, 1);
2014 break;
2015 }
2016 case MODE_Insert: {
2017 if( azArg==0 ) break;
2018 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2019 if( p->showHeader ){
2020 raw_printf(p->out,"(");
2021 for(i=0; i<nArg; i++){
2022 if( i>0 ) raw_printf(p->out, ",");
2023 if( quoteChar(azCol[i]) ){
2024 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2025 utf8_printf(p->out, "%s", z);
2026 sqlite3_free(z);
2027 }else{
2028 raw_printf(p->out, "%s", azCol[i]);
2029 }
2030 }
2031 raw_printf(p->out,")");
2032 }
2033 p->cnt++;
2034 for(i=0; i<nArg; i++){
2035 raw_printf(p->out, i>0 ? "," : " VALUES(");
2036 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2037 utf8_printf(p->out,"NULL");
2038 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2039 if( ShellHasFlag(p, SHFLG_Newlines) ){
2040 output_quoted_string(p->out, azArg[i]);
2041 }else{
2042 output_quoted_escaped_string(p->out, azArg[i]);
2043 }
2044 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2045 utf8_printf(p->out,"%s", azArg[i]);
2046 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2047 char z[50];
2048 double r = sqlite3_column_double(p->pStmt, i);
drh2f1f8802018-06-13 17:19:20 +00002049 sqlite3_uint64 ur;
2050 memcpy(&ur,&r,sizeof(r));
2051 if( ur==0x7ff0000000000000LL ){
2052 raw_printf(p->out, "1e999");
2053 }else if( ur==0xfff0000000000000LL ){
2054 raw_printf(p->out, "-1e999");
2055 }else{
2056 sqlite3_snprintf(50,z,"%!.20g", r);
2057 raw_printf(p->out, "%s", z);
2058 }
drh2ce15c32017-07-11 13:34:40 +00002059 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2060 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2061 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2062 output_hex_blob(p->out, pBlob, nBlob);
2063 }else if( isNumber(azArg[i], 0) ){
2064 utf8_printf(p->out,"%s", azArg[i]);
2065 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2066 output_quoted_string(p->out, azArg[i]);
2067 }else{
2068 output_quoted_escaped_string(p->out, azArg[i]);
2069 }
2070 }
2071 raw_printf(p->out,");\n");
2072 break;
2073 }
2074 case MODE_Quote: {
2075 if( azArg==0 ) break;
2076 if( p->cnt==0 && p->showHeader ){
2077 for(i=0; i<nArg; i++){
2078 if( i>0 ) raw_printf(p->out, ",");
2079 output_quoted_string(p->out, azCol[i]);
2080 }
2081 raw_printf(p->out,"\n");
2082 }
2083 p->cnt++;
2084 for(i=0; i<nArg; i++){
2085 if( i>0 ) raw_printf(p->out, ",");
2086 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2087 utf8_printf(p->out,"NULL");
2088 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2089 output_quoted_string(p->out, azArg[i]);
2090 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2091 utf8_printf(p->out,"%s", azArg[i]);
2092 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2093 char z[50];
2094 double r = sqlite3_column_double(p->pStmt, i);
2095 sqlite3_snprintf(50,z,"%!.20g", r);
2096 raw_printf(p->out, "%s", z);
2097 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2098 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2099 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2100 output_hex_blob(p->out, pBlob, nBlob);
2101 }else if( isNumber(azArg[i], 0) ){
2102 utf8_printf(p->out,"%s", azArg[i]);
2103 }else{
2104 output_quoted_string(p->out, azArg[i]);
2105 }
2106 }
2107 raw_printf(p->out,"\n");
2108 break;
2109 }
2110 case MODE_Ascii: {
2111 if( p->cnt++==0 && p->showHeader ){
2112 for(i=0; i<nArg; i++){
2113 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2114 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2115 }
2116 utf8_printf(p->out, "%s", p->rowSeparator);
2117 }
2118 if( azArg==0 ) break;
2119 for(i=0; i<nArg; i++){
2120 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2121 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2122 }
2123 utf8_printf(p->out, "%s", p->rowSeparator);
2124 break;
2125 }
drh4b5345c2018-04-24 13:07:40 +00002126 case MODE_EQP: {
drhe2ca99c2018-05-02 00:33:43 +00002127 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
drh4b5345c2018-04-24 13:07:40 +00002128 break;
2129 }
drh2ce15c32017-07-11 13:34:40 +00002130 }
2131 return 0;
2132}
2133
2134/*
2135** This is the callback routine that the SQLite library
2136** invokes for each row of a query result.
2137*/
2138static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2139 /* since we don't have type info, call the shell_callback with a NULL value */
2140 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2141}
2142
2143/*
2144** This is the callback routine from sqlite3_exec() that appends all
2145** output onto the end of a ShellText object.
2146*/
2147static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2148 ShellText *p = (ShellText*)pArg;
2149 int i;
2150 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00002151 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002152 if( p->n ) appendText(p, "|", 0);
2153 for(i=0; i<nArg; i++){
2154 if( i ) appendText(p, ",", 0);
2155 if( azArg[i] ) appendText(p, azArg[i], 0);
2156 }
2157 return 0;
2158}
2159
2160/*
2161** Generate an appropriate SELFTEST table in the main database.
2162*/
2163static void createSelftestTable(ShellState *p){
2164 char *zErrMsg = 0;
2165 sqlite3_exec(p->db,
2166 "SAVEPOINT selftest_init;\n"
2167 "CREATE TABLE IF NOT EXISTS selftest(\n"
2168 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2169 " op TEXT,\n" /* Operator: memo run */
2170 " cmd TEXT,\n" /* Command text */
2171 " ans TEXT\n" /* Desired answer */
2172 ");"
2173 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2174 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2175 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2176 " 'memo','Tests generated by --init');\n"
2177 "INSERT INTO [_shell$self]\n"
2178 " SELECT 'run',\n"
2179 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2180 "FROM sqlite_master ORDER BY 2'',224))',\n"
2181 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2182 "FROM sqlite_master ORDER BY 2',224));\n"
2183 "INSERT INTO [_shell$self]\n"
2184 " SELECT 'run',"
2185 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2186 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2187 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2188 " FROM (\n"
2189 " SELECT name FROM sqlite_master\n"
2190 " WHERE type='table'\n"
2191 " AND name<>'selftest'\n"
2192 " AND coalesce(rootpage,0)>0\n"
2193 " )\n"
2194 " ORDER BY name;\n"
2195 "INSERT INTO [_shell$self]\n"
2196 " VALUES('run','PRAGMA integrity_check','ok');\n"
2197 "INSERT INTO selftest(tno,op,cmd,ans)"
2198 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2199 "DROP TABLE [_shell$self];"
2200 ,0,0,&zErrMsg);
2201 if( zErrMsg ){
2202 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2203 sqlite3_free(zErrMsg);
2204 }
2205 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2206}
2207
2208
2209/*
2210** Set the destination table field of the ShellState structure to
2211** the name of the table given. Escape any quote characters in the
2212** table name.
2213*/
2214static void set_table_name(ShellState *p, const char *zName){
2215 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00002216 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00002217 char *z;
2218
2219 if( p->zDestTable ){
2220 free(p->zDestTable);
2221 p->zDestTable = 0;
2222 }
2223 if( zName==0 ) return;
2224 cQuote = quoteChar(zName);
2225 n = strlen30(zName);
2226 if( cQuote ) n += n+2;
2227 z = p->zDestTable = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00002228 if( z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002229 n = 0;
2230 if( cQuote ) z[n++] = cQuote;
2231 for(i=0; zName[i]; i++){
2232 z[n++] = zName[i];
2233 if( zName[i]==cQuote ) z[n++] = cQuote;
2234 }
2235 if( cQuote ) z[n++] = cQuote;
2236 z[n] = 0;
2237}
2238
2239
2240/*
2241** Execute a query statement that will generate SQL output. Print
2242** the result columns, comma-separated, on a line and then add a
2243** semicolon terminator to the end of that line.
2244**
2245** If the number of columns is 1 and that column contains text "--"
2246** then write the semicolon on a separate line. That way, if a
2247** "--" comment occurs at the end of the statement, the comment
2248** won't consume the semicolon terminator.
2249*/
2250static int run_table_dump_query(
2251 ShellState *p, /* Query context */
2252 const char *zSelect, /* SELECT statement to extract content */
2253 const char *zFirstRow /* Print before first row, if not NULL */
2254){
2255 sqlite3_stmt *pSelect;
2256 int rc;
2257 int nResult;
2258 int i;
2259 const char *z;
2260 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2261 if( rc!=SQLITE_OK || !pSelect ){
2262 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2263 sqlite3_errmsg(p->db));
2264 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2265 return rc;
2266 }
2267 rc = sqlite3_step(pSelect);
2268 nResult = sqlite3_column_count(pSelect);
2269 while( rc==SQLITE_ROW ){
2270 if( zFirstRow ){
2271 utf8_printf(p->out, "%s", zFirstRow);
2272 zFirstRow = 0;
2273 }
2274 z = (const char*)sqlite3_column_text(pSelect, 0);
2275 utf8_printf(p->out, "%s", z);
2276 for(i=1; i<nResult; i++){
2277 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2278 }
2279 if( z==0 ) z = "";
2280 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2281 if( z[0] ){
2282 raw_printf(p->out, "\n;\n");
2283 }else{
2284 raw_printf(p->out, ";\n");
2285 }
2286 rc = sqlite3_step(pSelect);
2287 }
2288 rc = sqlite3_finalize(pSelect);
2289 if( rc!=SQLITE_OK ){
2290 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2291 sqlite3_errmsg(p->db));
2292 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2293 }
2294 return rc;
2295}
2296
2297/*
2298** Allocate space and save off current error string.
2299*/
2300static char *save_err_msg(
2301 sqlite3 *db /* Database to query */
2302){
2303 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2304 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2305 if( zErrMsg ){
2306 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2307 }
2308 return zErrMsg;
2309}
2310
2311#ifdef __linux__
2312/*
2313** Attempt to display I/O stats on Linux using /proc/PID/io
2314*/
2315static void displayLinuxIoStats(FILE *out){
2316 FILE *in;
2317 char z[200];
2318 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2319 in = fopen(z, "rb");
2320 if( in==0 ) return;
2321 while( fgets(z, sizeof(z), in)!=0 ){
2322 static const struct {
2323 const char *zPattern;
2324 const char *zDesc;
2325 } aTrans[] = {
2326 { "rchar: ", "Bytes received by read():" },
2327 { "wchar: ", "Bytes sent to write():" },
2328 { "syscr: ", "Read() system calls:" },
2329 { "syscw: ", "Write() system calls:" },
2330 { "read_bytes: ", "Bytes read from storage:" },
2331 { "write_bytes: ", "Bytes written to storage:" },
2332 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2333 };
2334 int i;
2335 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00002336 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00002337 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2338 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2339 break;
2340 }
2341 }
2342 }
2343 fclose(in);
2344}
2345#endif
2346
2347/*
2348** Display a single line of status using 64-bit values.
2349*/
2350static void displayStatLine(
2351 ShellState *p, /* The shell context */
2352 char *zLabel, /* Label for this one line */
2353 char *zFormat, /* Format for the result */
2354 int iStatusCtrl, /* Which status to display */
2355 int bReset /* True to reset the stats */
2356){
2357 sqlite3_int64 iCur = -1;
2358 sqlite3_int64 iHiwtr = -1;
2359 int i, nPercent;
2360 char zLine[200];
2361 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2362 for(i=0, nPercent=0; zFormat[i]; i++){
2363 if( zFormat[i]=='%' ) nPercent++;
2364 }
2365 if( nPercent>1 ){
2366 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2367 }else{
2368 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2369 }
2370 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2371}
2372
2373/*
2374** Display memory stats.
2375*/
2376static int display_stats(
2377 sqlite3 *db, /* Database to query */
2378 ShellState *pArg, /* Pointer to ShellState */
2379 int bReset /* True to reset the stats */
2380){
2381 int iCur;
2382 int iHiwtr;
drh393344f2018-03-09 16:37:05 +00002383 FILE *out;
2384 if( pArg==0 || pArg->out==0 ) return 0;
2385 out = pArg->out;
drh2ce15c32017-07-11 13:34:40 +00002386
drh393344f2018-03-09 16:37:05 +00002387 if( pArg->pStmt && (pArg->statsOn & 2) ){
2388 int nCol, i, x;
2389 sqlite3_stmt *pStmt = pArg->pStmt;
2390 char z[100];
2391 nCol = sqlite3_column_count(pStmt);
2392 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2393 for(i=0; i<nCol; i++){
2394 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2395 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002396#ifndef SQLITE_OMIT_DECLTYPE
drh393344f2018-03-09 16:37:05 +00002397 sqlite3_snprintf(30, z+x, "declared type:");
2398 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
drh929cce82018-03-17 16:26:36 +00002399#endif
2400#ifdef SQLITE_ENABLE_COLUMN_METADATA
drh393344f2018-03-09 16:37:05 +00002401 sqlite3_snprintf(30, z+x, "database name:");
2402 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2403 sqlite3_snprintf(30, z+x, "table name:");
2404 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2405 sqlite3_snprintf(30, z+x, "origin name:");
2406 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002407#endif
drh2ce15c32017-07-11 13:34:40 +00002408 }
drh929cce82018-03-17 16:26:36 +00002409 }
drh2ce15c32017-07-11 13:34:40 +00002410
drh393344f2018-03-09 16:37:05 +00002411 displayStatLine(pArg, "Memory Used:",
2412 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2413 displayStatLine(pArg, "Number of Outstanding Allocations:",
2414 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2415 if( pArg->shellFlgs & SHFLG_Pagecache ){
2416 displayStatLine(pArg, "Number of Pcache Pages Used:",
2417 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2418 }
2419 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2420 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2421 displayStatLine(pArg, "Largest Allocation:",
2422 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2423 displayStatLine(pArg, "Largest Pcache Allocation:",
2424 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2425#ifdef YYTRACKMAXSTACKDEPTH
2426 displayStatLine(pArg, "Deepest Parser Stack:",
2427 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2428#endif
2429
2430 if( db ){
drh2ce15c32017-07-11 13:34:40 +00002431 if( pArg->shellFlgs & SHFLG_Lookaside ){
2432 iHiwtr = iCur = -1;
2433 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2434 &iCur, &iHiwtr, bReset);
2435 raw_printf(pArg->out,
2436 "Lookaside Slots Used: %d (max %d)\n",
2437 iCur, iHiwtr);
2438 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2439 &iCur, &iHiwtr, bReset);
2440 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2441 iHiwtr);
2442 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2443 &iCur, &iHiwtr, bReset);
2444 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2445 iHiwtr);
2446 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2447 &iCur, &iHiwtr, bReset);
2448 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2449 iHiwtr);
2450 }
2451 iHiwtr = iCur = -1;
2452 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2453 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2454 iCur);
2455 iHiwtr = iCur = -1;
2456 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2457 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2458 iHiwtr = iCur = -1;
2459 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2460 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2461 iHiwtr = iCur = -1;
2462 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2463 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2464 iHiwtr = iCur = -1;
drhffc78a42018-03-14 14:53:50 +00002465 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2466 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2467 iHiwtr = iCur = -1;
drh2ce15c32017-07-11 13:34:40 +00002468 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2469 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2470 iCur);
2471 iHiwtr = iCur = -1;
2472 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2473 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2474 iCur);
2475 }
2476
drh393344f2018-03-09 16:37:05 +00002477 if( pArg->pStmt ){
drh2ce15c32017-07-11 13:34:40 +00002478 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2479 bReset);
2480 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2481 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2482 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2483 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2484 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2485 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2486 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
drh393344f2018-03-09 16:37:05 +00002487 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
2488 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2489 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2490 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2491 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2492 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
drh2ce15c32017-07-11 13:34:40 +00002493 }
2494
2495#ifdef __linux__
2496 displayLinuxIoStats(pArg->out);
2497#endif
2498
2499 /* Do not remove this machine readable comment: extra-stats-output-here */
2500
2501 return 0;
2502}
2503
2504/*
2505** Display scan stats.
2506*/
2507static void display_scanstats(
2508 sqlite3 *db, /* Database to query */
2509 ShellState *pArg /* Pointer to ShellState */
2510){
2511#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2512 UNUSED_PARAMETER(db);
2513 UNUSED_PARAMETER(pArg);
2514#else
2515 int i, k, n, mx;
2516 raw_printf(pArg->out, "-------- scanstats --------\n");
2517 mx = 0;
2518 for(k=0; k<=mx; k++){
2519 double rEstLoop = 1.0;
2520 for(i=n=0; 1; i++){
2521 sqlite3_stmt *p = pArg->pStmt;
2522 sqlite3_int64 nLoop, nVisit;
2523 double rEst;
2524 int iSid;
2525 const char *zExplain;
2526 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2527 break;
2528 }
2529 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2530 if( iSid>mx ) mx = iSid;
2531 if( iSid!=k ) continue;
2532 if( n==0 ){
2533 rEstLoop = (double)nLoop;
2534 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2535 }
2536 n++;
2537 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2538 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2539 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2540 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2541 rEstLoop *= rEst;
2542 raw_printf(pArg->out,
2543 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2544 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2545 );
2546 }
2547 }
2548 raw_printf(pArg->out, "---------------------------\n");
2549#endif
2550}
2551
2552/*
2553** Parameter azArray points to a zero-terminated array of strings. zStr
2554** points to a single nul-terminated string. Return non-zero if zStr
2555** is equal, according to strcmp(), to any of the strings in the array.
2556** Otherwise, return zero.
2557*/
2558static int str_in_array(const char *zStr, const char **azArray){
2559 int i;
2560 for(i=0; azArray[i]; i++){
2561 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2562 }
2563 return 0;
2564}
2565
2566/*
2567** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2568** and populate the ShellState.aiIndent[] array with the number of
2569** spaces each opcode should be indented before it is output.
2570**
2571** The indenting rules are:
2572**
2573** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2574** all opcodes that occur between the p2 jump destination and the opcode
2575** itself by 2 spaces.
2576**
2577** * For each "Goto", if the jump destination is earlier in the program
2578** and ends on one of:
2579** Yield SeekGt SeekLt RowSetRead Rewind
2580** or if the P1 parameter is one instead of zero,
2581** then indent all opcodes between the earlier instruction
2582** and "Goto" by 2 spaces.
2583*/
2584static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2585 const char *zSql; /* The text of the SQL statement */
2586 const char *z; /* Used to check if this is an EXPLAIN */
2587 int *abYield = 0; /* True if op is an OP_Yield */
2588 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2589 int iOp; /* Index of operation in p->aiIndent[] */
2590
drhf1949b62018-06-07 17:32:59 +00002591 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
drh2ce15c32017-07-11 13:34:40 +00002592 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2593 "Rewind", 0 };
2594 const char *azGoto[] = { "Goto", 0 };
2595
2596 /* Try to figure out if this is really an EXPLAIN statement. If this
2597 ** cannot be verified, return early. */
2598 if( sqlite3_column_count(pSql)!=8 ){
2599 p->cMode = p->mode;
2600 return;
2601 }
2602 zSql = sqlite3_sql(pSql);
2603 if( zSql==0 ) return;
2604 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2605 if( sqlite3_strnicmp(z, "explain", 7) ){
2606 p->cMode = p->mode;
2607 return;
2608 }
2609
2610 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2611 int i;
2612 int iAddr = sqlite3_column_int(pSql, 0);
2613 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2614
2615 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2616 ** p2 is an instruction address, set variable p2op to the index of that
2617 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2618 ** the current instruction is part of a sub-program generated by an
2619 ** SQL trigger or foreign key. */
2620 int p2 = sqlite3_column_int(pSql, 3);
2621 int p2op = (p2 + (iOp-iAddr));
2622
2623 /* Grow the p->aiIndent array as required */
2624 if( iOp>=nAlloc ){
2625 if( iOp==0 ){
2626 /* Do further verfication that this is explain output. Abort if
2627 ** it is not */
2628 static const char *explainCols[] = {
2629 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2630 int jj;
2631 for(jj=0; jj<ArraySize(explainCols); jj++){
2632 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2633 p->cMode = p->mode;
2634 sqlite3_reset(pSql);
2635 return;
2636 }
2637 }
2638 }
2639 nAlloc += 100;
2640 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002641 if( p->aiIndent==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002642 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002643 if( abYield==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002644 }
2645 abYield[iOp] = str_in_array(zOp, azYield);
2646 p->aiIndent[iOp] = 0;
2647 p->nIndent = iOp+1;
2648
2649 if( str_in_array(zOp, azNext) ){
2650 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2651 }
2652 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2653 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2654 ){
2655 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2656 }
2657 }
2658
2659 p->iIndent = 0;
2660 sqlite3_free(abYield);
2661 sqlite3_reset(pSql);
2662}
2663
2664/*
2665** Free the array allocated by explain_data_prepare().
2666*/
2667static void explain_data_delete(ShellState *p){
2668 sqlite3_free(p->aiIndent);
2669 p->aiIndent = 0;
2670 p->nIndent = 0;
2671 p->iIndent = 0;
2672}
2673
2674/*
2675** Disable and restore .wheretrace and .selecttrace settings.
2676*/
2677#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2678extern int sqlite3SelectTrace;
2679static int savedSelectTrace;
2680#endif
2681#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2682extern int sqlite3WhereTrace;
2683static int savedWhereTrace;
2684#endif
2685static void disable_debug_trace_modes(void){
2686#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2687 savedSelectTrace = sqlite3SelectTrace;
2688 sqlite3SelectTrace = 0;
2689#endif
2690#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2691 savedWhereTrace = sqlite3WhereTrace;
2692 sqlite3WhereTrace = 0;
2693#endif
2694}
2695static void restore_debug_trace_modes(void){
2696#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2697 sqlite3SelectTrace = savedSelectTrace;
2698#endif
2699#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2700 sqlite3WhereTrace = savedWhereTrace;
2701#endif
2702}
2703
2704/*
2705** Run a prepared statement
2706*/
2707static void exec_prepared_stmt(
2708 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002709 sqlite3_stmt *pStmt /* Statment to run */
drh2ce15c32017-07-11 13:34:40 +00002710){
2711 int rc;
2712
2713 /* perform the first step. this will tell us if we
2714 ** have a result set or not and how wide it is.
2715 */
2716 rc = sqlite3_step(pStmt);
2717 /* if we have a result set... */
2718 if( SQLITE_ROW == rc ){
drha10b9992018-03-09 15:24:33 +00002719 /* allocate space for col name ptr, value ptr, and type */
2720 int nCol = sqlite3_column_count(pStmt);
2721 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2722 if( !pData ){
2723 rc = SQLITE_NOMEM;
drh2ce15c32017-07-11 13:34:40 +00002724 }else{
drha10b9992018-03-09 15:24:33 +00002725 char **azCols = (char **)pData; /* Names of result columns */
2726 char **azVals = &azCols[nCol]; /* Results */
2727 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2728 int i, x;
2729 assert(sizeof(int) <= sizeof(char *));
2730 /* save off ptrs to column names */
2731 for(i=0; i<nCol; i++){
2732 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2733 }
drh2ce15c32017-07-11 13:34:40 +00002734 do{
drha10b9992018-03-09 15:24:33 +00002735 /* extract the data and data types */
2736 for(i=0; i<nCol; i++){
2737 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2738 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2739 azVals[i] = "";
2740 }else{
2741 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2742 }
2743 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2744 rc = SQLITE_NOMEM;
2745 break; /* from for */
2746 }
2747 } /* end for */
2748
2749 /* if data and types extracted successfully... */
2750 if( SQLITE_ROW == rc ){
2751 /* call the supplied callback with the result row data */
2752 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2753 rc = SQLITE_ABORT;
2754 }else{
2755 rc = sqlite3_step(pStmt);
2756 }
2757 }
2758 } while( SQLITE_ROW == rc );
2759 sqlite3_free(pData);
drh2ce15c32017-07-11 13:34:40 +00002760 }
2761 }
2762}
2763
dan6b046be2018-01-09 15:25:55 +00002764#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002765/*
dan43efc182017-12-19 17:42:13 +00002766** This function is called to process SQL if the previous shell command
2767** was ".expert". It passes the SQL in the second argument directly to
2768** the sqlite3expert object.
2769**
2770** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2771** code. In this case, (*pzErr) may be set to point to a buffer containing
2772** an English language error message. It is the responsibility of the
2773** caller to eventually free this buffer using sqlite3_free().
2774*/
2775static int expertHandleSQL(
2776 ShellState *pState,
2777 const char *zSql,
2778 char **pzErr
2779){
2780 assert( pState->expert.pExpert );
2781 assert( pzErr==0 || *pzErr==0 );
2782 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2783}
2784
2785/*
2786** This function is called either to silently clean up the object
2787** created by the ".expert" command (if bCancel==1), or to generate a
2788** report from it and then clean it up (if bCancel==0).
2789**
2790** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2791** code. In this case, (*pzErr) may be set to point to a buffer containing
2792** an English language error message. It is the responsibility of the
2793** caller to eventually free this buffer using sqlite3_free().
2794*/
2795static int expertFinish(
2796 ShellState *pState,
2797 int bCancel,
2798 char **pzErr
2799){
2800 int rc = SQLITE_OK;
2801 sqlite3expert *p = pState->expert.pExpert;
2802 assert( p );
2803 assert( bCancel || pzErr==0 || *pzErr==0 );
2804 if( bCancel==0 ){
2805 FILE *out = pState->out;
2806 int bVerbose = pState->expert.bVerbose;
2807
2808 rc = sqlite3_expert_analyze(p, pzErr);
2809 if( rc==SQLITE_OK ){
2810 int nQuery = sqlite3_expert_count(p);
2811 int i;
2812
2813 if( bVerbose ){
2814 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2815 raw_printf(out, "-- Candidates -----------------------------\n");
2816 raw_printf(out, "%s\n", zCand);
2817 }
2818 for(i=0; i<nQuery; i++){
2819 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2820 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2821 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2822 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2823 if( bVerbose ){
2824 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2825 raw_printf(out, "%s\n\n", zSql);
2826 }
2827 raw_printf(out, "%s\n", zIdx);
2828 raw_printf(out, "%s\n", zEQP);
2829 }
2830 }
2831 }
2832 sqlite3_expert_destroy(p);
2833 pState->expert.pExpert = 0;
2834 return rc;
2835}
2836
dan6b046be2018-01-09 15:25:55 +00002837/*
2838** Implementation of ".expert" dot command.
2839*/
2840static int expertDotCommand(
2841 ShellState *pState, /* Current shell tool state */
2842 char **azArg, /* Array of arguments passed to dot command */
2843 int nArg /* Number of entries in azArg[] */
2844){
2845 int rc = SQLITE_OK;
2846 char *zErr = 0;
2847 int i;
2848 int iSample = 0;
2849
2850 assert( pState->expert.pExpert==0 );
2851 memset(&pState->expert, 0, sizeof(ExpertInfo));
2852
2853 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2854 char *z = azArg[i];
2855 int n;
2856 if( z[0]=='-' && z[1]=='-' ) z++;
2857 n = strlen30(z);
2858 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2859 pState->expert.bVerbose = 1;
2860 }
2861 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2862 if( i==(nArg-1) ){
2863 raw_printf(stderr, "option requires an argument: %s\n", z);
2864 rc = SQLITE_ERROR;
2865 }else{
2866 iSample = (int)integerValue(azArg[++i]);
2867 if( iSample<0 || iSample>100 ){
2868 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2869 rc = SQLITE_ERROR;
2870 }
2871 }
2872 }
2873 else{
2874 raw_printf(stderr, "unknown option: %s\n", z);
2875 rc = SQLITE_ERROR;
2876 }
2877 }
2878
2879 if( rc==SQLITE_OK ){
2880 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2881 if( pState->expert.pExpert==0 ){
2882 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2883 rc = SQLITE_ERROR;
2884 }else{
2885 sqlite3_expert_config(
2886 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2887 );
2888 }
2889 }
2890
2891 return rc;
2892}
2893#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00002894
2895/*
drh2ce15c32017-07-11 13:34:40 +00002896** Execute a statement or set of statements. Print
2897** any result rows/columns depending on the current mode
2898** set via the supplied callback.
2899**
2900** This is very similar to SQLite's built-in sqlite3_exec()
2901** function except it takes a slightly different callback
2902** and callback data argument.
2903*/
2904static int shell_exec(
drh2ce15c32017-07-11 13:34:40 +00002905 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002906 const char *zSql, /* SQL to be evaluated */
drh2ce15c32017-07-11 13:34:40 +00002907 char **pzErrMsg /* Error msg written here */
2908){
2909 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2910 int rc = SQLITE_OK; /* Return Code */
2911 int rc2;
2912 const char *zLeftover; /* Tail of unprocessed SQL */
drha10b9992018-03-09 15:24:33 +00002913 sqlite3 *db = pArg->db;
drh2ce15c32017-07-11 13:34:40 +00002914
2915 if( pzErrMsg ){
2916 *pzErrMsg = NULL;
2917 }
2918
dan6b046be2018-01-09 15:25:55 +00002919#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00002920 if( pArg->expert.pExpert ){
2921 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2922 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2923 }
dan6b046be2018-01-09 15:25:55 +00002924#endif
dan43efc182017-12-19 17:42:13 +00002925
drh2ce15c32017-07-11 13:34:40 +00002926 while( zSql[0] && (SQLITE_OK == rc) ){
2927 static const char *zStmtSql;
2928 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2929 if( SQLITE_OK != rc ){
2930 if( pzErrMsg ){
2931 *pzErrMsg = save_err_msg(db);
2932 }
2933 }else{
2934 if( !pStmt ){
2935 /* this happens for a comment or white-space */
2936 zSql = zLeftover;
2937 while( IsSpace(zSql[0]) ) zSql++;
2938 continue;
2939 }
2940 zStmtSql = sqlite3_sql(pStmt);
2941 if( zStmtSql==0 ) zStmtSql = "";
2942 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2943
2944 /* save off the prepared statment handle and reset row count */
2945 if( pArg ){
2946 pArg->pStmt = pStmt;
2947 pArg->cnt = 0;
2948 }
2949
2950 /* echo the sql statement if echo on */
2951 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2952 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2953 }
2954
2955 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2956 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2957 sqlite3_stmt *pExplain;
2958 char *zEQP;
drhada70452017-12-21 21:02:27 +00002959 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00002960 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00002961 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2962 if( pArg->autoEQP>=AUTOEQP_trigger ){
2963 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2964 }
drh2ce15c32017-07-11 13:34:40 +00002965 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2966 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2967 if( rc==SQLITE_OK ){
2968 while( sqlite3_step(pExplain)==SQLITE_ROW ){
drh4b5345c2018-04-24 13:07:40 +00002969 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
drhe2ca99c2018-05-02 00:33:43 +00002970 int iEqpId = sqlite3_column_int(pExplain, 0);
2971 int iParentId = sqlite3_column_int(pExplain, 1);
drh4b5345c2018-04-24 13:07:40 +00002972 if( zEQPLine[0]=='-' ) eqp_render(pArg);
drhe2ca99c2018-05-02 00:33:43 +00002973 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
drh2ce15c32017-07-11 13:34:40 +00002974 }
drh4b5345c2018-04-24 13:07:40 +00002975 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00002976 }
2977 sqlite3_finalize(pExplain);
2978 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00002979 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00002980 /* Also do an EXPLAIN for ".eqp full" mode */
2981 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2982 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2983 if( rc==SQLITE_OK ){
2984 pArg->cMode = MODE_Explain;
2985 explain_data_prepare(pArg, pExplain);
drha10b9992018-03-09 15:24:33 +00002986 exec_prepared_stmt(pArg, pExplain);
drh2ce15c32017-07-11 13:34:40 +00002987 explain_data_delete(pArg);
2988 }
2989 sqlite3_finalize(pExplain);
2990 sqlite3_free(zEQP);
2991 }
drh51efe092018-03-20 12:04:38 +00002992 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
2993 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
2994 /* Reprepare pStmt before reactiving trace modes */
2995 sqlite3_finalize(pStmt);
2996 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
drh3c49eaf2018-06-07 15:23:43 +00002997 if( pArg ) pArg->pStmt = pStmt;
drh51efe092018-03-20 12:04:38 +00002998 }
drh2ce15c32017-07-11 13:34:40 +00002999 restore_debug_trace_modes();
3000 }
3001
3002 if( pArg ){
3003 pArg->cMode = pArg->mode;
drh4b5345c2018-04-24 13:07:40 +00003004 if( pArg->autoExplain ){
3005 if( sqlite3_column_count(pStmt)==8
3006 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
3007 ){
3008 pArg->cMode = MODE_Explain;
3009 }
3010 if( sqlite3_column_count(pStmt)==4
3011 && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql,0)==0 ){
3012 pArg->cMode = MODE_EQP;
3013 }
drh2ce15c32017-07-11 13:34:40 +00003014 }
3015
3016 /* If the shell is currently in ".explain" mode, gather the extra
3017 ** data required to add indents to the output.*/
3018 if( pArg->cMode==MODE_Explain ){
3019 explain_data_prepare(pArg, pStmt);
3020 }
3021 }
3022
drha10b9992018-03-09 15:24:33 +00003023 exec_prepared_stmt(pArg, pStmt);
drh2ce15c32017-07-11 13:34:40 +00003024 explain_data_delete(pArg);
drh4b5345c2018-04-24 13:07:40 +00003025 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003026
3027 /* print usage stats if stats on */
3028 if( pArg && pArg->statsOn ){
3029 display_stats(db, pArg, 0);
3030 }
3031
3032 /* print loop-counters if required */
3033 if( pArg && pArg->scanstatsOn ){
3034 display_scanstats(db, pArg);
3035 }
3036
3037 /* Finalize the statement just executed. If this fails, save a
3038 ** copy of the error message. Otherwise, set zSql to point to the
3039 ** next statement to execute. */
3040 rc2 = sqlite3_finalize(pStmt);
3041 if( rc!=SQLITE_NOMEM ) rc = rc2;
3042 if( rc==SQLITE_OK ){
3043 zSql = zLeftover;
3044 while( IsSpace(zSql[0]) ) zSql++;
3045 }else if( pzErrMsg ){
3046 *pzErrMsg = save_err_msg(db);
3047 }
3048
3049 /* clear saved stmt handle */
3050 if( pArg ){
3051 pArg->pStmt = NULL;
3052 }
3053 }
3054 } /* end while */
3055
3056 return rc;
3057}
3058
3059/*
3060** Release memory previously allocated by tableColumnList().
3061*/
3062static void freeColumnList(char **azCol){
3063 int i;
3064 for(i=1; azCol[i]; i++){
3065 sqlite3_free(azCol[i]);
3066 }
3067 /* azCol[0] is a static string */
3068 sqlite3_free(azCol);
3069}
3070
3071/*
3072** Return a list of pointers to strings which are the names of all
3073** columns in table zTab. The memory to hold the names is dynamically
3074** allocated and must be released by the caller using a subsequent call
3075** to freeColumnList().
3076**
3077** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3078** value that needs to be preserved, then azCol[0] is filled in with the
3079** name of the rowid column.
3080**
3081** The first regular column in the table is azCol[1]. The list is terminated
3082** by an entry with azCol[i]==0.
3083*/
3084static char **tableColumnList(ShellState *p, const char *zTab){
3085 char **azCol = 0;
3086 sqlite3_stmt *pStmt;
3087 char *zSql;
3088 int nCol = 0;
3089 int nAlloc = 0;
3090 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3091 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3092 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3093 int rc;
3094
3095 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3096 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3097 sqlite3_free(zSql);
3098 if( rc ) return 0;
3099 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3100 if( nCol>=nAlloc-2 ){
3101 nAlloc = nAlloc*2 + nCol + 10;
3102 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
drh4b5345c2018-04-24 13:07:40 +00003103 if( azCol==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00003104 }
3105 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3106 if( sqlite3_column_int(pStmt, 5) ){
3107 nPK++;
3108 if( nPK==1
3109 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3110 "INTEGER")==0
3111 ){
3112 isIPK = 1;
3113 }else{
3114 isIPK = 0;
3115 }
3116 }
3117 }
3118 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00003119 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003120 azCol[0] = 0;
3121 azCol[nCol+1] = 0;
3122
3123 /* The decision of whether or not a rowid really needs to be preserved
3124 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3125 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3126 ** rowids on tables where the rowid is inaccessible because there are other
3127 ** columns in the table named "rowid", "_rowid_", and "oid".
3128 */
3129 if( preserveRowid && isIPK ){
3130 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3131 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3132 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3133 ** ROWID aliases. To distinguish these cases, check to see if
3134 ** there is a "pk" entry in "PRAGMA index_list". There will be
3135 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3136 */
3137 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3138 " WHERE origin='pk'", zTab);
3139 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3140 sqlite3_free(zSql);
3141 if( rc ){
3142 freeColumnList(azCol);
3143 return 0;
3144 }
3145 rc = sqlite3_step(pStmt);
3146 sqlite3_finalize(pStmt);
3147 preserveRowid = rc==SQLITE_ROW;
3148 }
3149 if( preserveRowid ){
3150 /* Only preserve the rowid if we can find a name to use for the
3151 ** rowid */
3152 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3153 int i, j;
3154 for(j=0; j<3; j++){
3155 for(i=1; i<=nCol; i++){
3156 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3157 }
3158 if( i>nCol ){
3159 /* At this point, we know that azRowid[j] is not the name of any
3160 ** ordinary column in the table. Verify that azRowid[j] is a valid
3161 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3162 ** tables will fail this last check */
3163 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3164 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3165 break;
3166 }
3167 }
3168 }
3169 return azCol;
3170}
3171
3172/*
3173** Toggle the reverse_unordered_selects setting.
3174*/
3175static void toggleSelectOrder(sqlite3 *db){
3176 sqlite3_stmt *pStmt = 0;
3177 int iSetting = 0;
3178 char zStmt[100];
3179 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3180 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3181 iSetting = sqlite3_column_int(pStmt, 0);
3182 }
3183 sqlite3_finalize(pStmt);
3184 sqlite3_snprintf(sizeof(zStmt), zStmt,
3185 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3186 sqlite3_exec(db, zStmt, 0, 0, 0);
3187}
3188
3189/*
3190** This is a different callback routine used for dumping the database.
3191** Each row received by this callback consists of a table name,
3192** the table type ("index" or "table") and SQL to create the table.
3193** This routine should print text sufficient to recreate the table.
3194*/
3195static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3196 int rc;
3197 const char *zTable;
3198 const char *zType;
3199 const char *zSql;
3200 ShellState *p = (ShellState *)pArg;
3201
3202 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00003203 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003204 zTable = azArg[0];
3205 zType = azArg[1];
3206 zSql = azArg[2];
3207
3208 if( strcmp(zTable, "sqlite_sequence")==0 ){
3209 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3210 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3211 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3212 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3213 return 0;
3214 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3215 char *zIns;
3216 if( !p->writableSchema ){
3217 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3218 p->writableSchema = 1;
3219 }
3220 zIns = sqlite3_mprintf(
3221 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3222 "VALUES('table','%q','%q',0,'%q');",
3223 zTable, zTable, zSql);
3224 utf8_printf(p->out, "%s\n", zIns);
3225 sqlite3_free(zIns);
3226 return 0;
3227 }else{
3228 printSchemaLine(p->out, zSql, ";\n");
3229 }
3230
3231 if( strcmp(zType, "table")==0 ){
3232 ShellText sSelect;
3233 ShellText sTable;
3234 char **azCol;
3235 int i;
3236 char *savedDestTable;
3237 int savedMode;
3238
3239 azCol = tableColumnList(p, zTable);
3240 if( azCol==0 ){
3241 p->nErr++;
3242 return 0;
3243 }
3244
3245 /* Always quote the table name, even if it appears to be pure ascii,
3246 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3247 initText(&sTable);
3248 appendText(&sTable, zTable, quoteChar(zTable));
3249 /* If preserving the rowid, add a column list after the table name.
3250 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3251 ** instead of the usual "INSERT INTO tab VALUES(...)".
3252 */
3253 if( azCol[0] ){
3254 appendText(&sTable, "(", 0);
3255 appendText(&sTable, azCol[0], 0);
3256 for(i=1; azCol[i]; i++){
3257 appendText(&sTable, ",", 0);
3258 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3259 }
3260 appendText(&sTable, ")", 0);
3261 }
3262
3263 /* Build an appropriate SELECT statement */
3264 initText(&sSelect);
3265 appendText(&sSelect, "SELECT ", 0);
3266 if( azCol[0] ){
3267 appendText(&sSelect, azCol[0], 0);
3268 appendText(&sSelect, ",", 0);
3269 }
3270 for(i=1; azCol[i]; i++){
3271 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3272 if( azCol[i+1] ){
3273 appendText(&sSelect, ",", 0);
3274 }
3275 }
3276 freeColumnList(azCol);
3277 appendText(&sSelect, " FROM ", 0);
3278 appendText(&sSelect, zTable, quoteChar(zTable));
3279
3280 savedDestTable = p->zDestTable;
3281 savedMode = p->mode;
3282 p->zDestTable = sTable.z;
3283 p->mode = p->cMode = MODE_Insert;
drha10b9992018-03-09 15:24:33 +00003284 rc = shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003285 if( (rc&0xff)==SQLITE_CORRUPT ){
3286 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3287 toggleSelectOrder(p->db);
drha10b9992018-03-09 15:24:33 +00003288 shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003289 toggleSelectOrder(p->db);
3290 }
3291 p->zDestTable = savedDestTable;
3292 p->mode = savedMode;
3293 freeText(&sTable);
3294 freeText(&sSelect);
3295 if( rc ) p->nErr++;
3296 }
3297 return 0;
3298}
3299
3300/*
3301** Run zQuery. Use dump_callback() as the callback routine so that
3302** the contents of the query are output as SQL statements.
3303**
3304** If we get a SQLITE_CORRUPT error, rerun the query after appending
3305** "ORDER BY rowid DESC" to the end.
3306*/
3307static int run_schema_dump_query(
3308 ShellState *p,
3309 const char *zQuery
3310){
3311 int rc;
3312 char *zErr = 0;
3313 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3314 if( rc==SQLITE_CORRUPT ){
3315 char *zQ2;
3316 int len = strlen30(zQuery);
3317 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3318 if( zErr ){
3319 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3320 sqlite3_free(zErr);
3321 zErr = 0;
3322 }
3323 zQ2 = malloc( len+100 );
3324 if( zQ2==0 ) return rc;
3325 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3326 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3327 if( rc ){
3328 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3329 }else{
3330 rc = SQLITE_CORRUPT;
3331 }
3332 sqlite3_free(zErr);
3333 free(zQ2);
3334 }
3335 return rc;
3336}
3337
3338/*
drh98aa2ab2018-09-26 16:53:51 +00003339** Text of help messages.
3340**
3341** The help text for each individual command begins with a line that starts
3342** with ".". Subsequent lines are supplimental information.
3343**
3344** There must be two or more spaces between the end of the command and the
3345** start of the description of what that command does.
drh2ce15c32017-07-11 13:34:40 +00003346*/
drh98aa2ab2018-09-26 16:53:51 +00003347static const char *(azHelp[]) = {
drhe37c0e12018-01-06 19:19:50 +00003348#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drh98aa2ab2018-09-26 16:53:51 +00003349 ".archive ... Manage SQL archives",
3350 " Each command must have exactly one of the following options:",
3351 " -c, --create Create a new archive",
3352 " -u, --update Update or add files to an existing archive",
3353 " -t, --list List contents of archive",
3354 " -x, --extract Extract files from archive",
3355 " Optional arguments:",
3356 " -v, --verbose Print each filename as it is processed",
3357 " -f FILE, --file FILE Operate on archive FILE (default is current db)",
3358 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS",
3359 " -C DIR, --directory DIR Change to directory DIR to read/extract files",
3360 " -n, --dryrun Show the SQL that would have occurred",
3361 " Examples:",
3362 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar",
3363 " .ar -tf archive.sar # List members of archive.sar",
3364 " .ar -xvf archive.sar # Verbosely extract files from archive.sar",
3365 " See also:",
3366 " http://sqlite.org/cli.html#sqlar_archive_support",
drhe37c0e12018-01-06 19:19:50 +00003367#endif
drh2ce15c32017-07-11 13:34:40 +00003368#ifndef SQLITE_OMIT_AUTHORIZATION
drh98aa2ab2018-09-26 16:53:51 +00003369 ".auth ON|OFF Show authorizer callbacks",
drh2ce15c32017-07-11 13:34:40 +00003370#endif
drh98aa2ab2018-09-26 16:53:51 +00003371 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3372 " --append Use the appendvfs",
3373 ".bail on|off Stop after hitting an error. Default OFF",
3374 ".binary on|off Turn binary output on or off. Default OFF",
3375 ".cd DIRECTORY Change the working directory to DIRECTORY",
3376 ".changes on|off Show number of rows changed by SQL",
3377 ".check GLOB Fail if output since .testcase does not match",
3378 ".clone NEWDB Clone data into NEWDB from the existing database",
3379 ".databases List names and files of attached databases",
3380 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3381 ".dbinfo ?DB? Show status information about the database",
drheb7f2a02018-09-26 18:02:32 +00003382 ".dump ?TABLE? ... Render all database content as SQL",
3383 " Options:",
3384 " --preserve-rowids Include ROWID values in the output",
3385 " --newlines Allow unescaped newline characters in output",
3386 " TABLE is LIKE pattern for the tables to dump",
drh98aa2ab2018-09-26 16:53:51 +00003387 ".echo on|off Turn command echo on or off",
3388 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN",
3389 ".excel Display the output of next command in a spreadsheet",
drheb7f2a02018-09-26 18:02:32 +00003390 ".exit ?CODE? Exit this program with return-code CODE",
drh98aa2ab2018-09-26 16:53:51 +00003391 ".expert EXPERIMENTAL. Suggest indexes for specified queries",
drh2ce15c32017-07-11 13:34:40 +00003392/* Because explain mode comes on automatically now, the ".explain" mode
3393** is removed from the help screen. It is still supported for legacy, however */
drh98aa2ab2018-09-26 16:53:51 +00003394/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/
3395 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3396 ".headers on|off Turn display of headers on or off",
3397 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3398 ".import FILE TABLE Import data from FILE into TABLE",
drh2ce15c32017-07-11 13:34:40 +00003399#ifndef SQLITE_OMIT_TEST_CONTROL
drh98aa2ab2018-09-26 16:53:51 +00003400 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
drh2ce15c32017-07-11 13:34:40 +00003401#endif
drh98aa2ab2018-09-26 16:53:51 +00003402 ".indexes ?TABLE? Show names of indexes",
3403 " If TABLE is specified, only show indexes for",
3404 " tables matching TABLE using the LIKE operator.",
drh2ce15c32017-07-11 13:34:40 +00003405#ifdef SQLITE_ENABLE_IOTRACE
drh98aa2ab2018-09-26 16:53:51 +00003406 ".iotrace FILE Enable I/O diagnostic logging to FILE",
drh2ce15c32017-07-11 13:34:40 +00003407#endif
drh98aa2ab2018-09-26 16:53:51 +00003408 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3409 ".lint OPTIONS Report potential schema issues.",
3410 " Options:",
3411 " fkey-indexes Find missing foreign key indexes",
drh2ce15c32017-07-11 13:34:40 +00003412#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh98aa2ab2018-09-26 16:53:51 +00003413 ".load FILE ?ENTRY? Load an extension library",
drh2ce15c32017-07-11 13:34:40 +00003414#endif
drh98aa2ab2018-09-26 16:53:51 +00003415 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3416 ".mode MODE ?TABLE? Set output mode",
3417 " MODE is one of:",
3418 " ascii Columns/rows delimited by 0x1F and 0x1E",
3419 " csv Comma-separated values",
3420 " column Left-aligned columns. (See .width)",
3421 " html HTML <table> code",
3422 " insert SQL insert statements for TABLE",
3423 " line One value per line",
3424 " list Values delimited by \"|\"",
3425 " quote Escape answers as for SQL",
3426 " tabs Tab-separated values",
3427 " tcl TCL list elements",
3428 ".nullvalue STRING Use STRING in place of NULL values",
3429 ".once (-e|-x|FILE) Output for the next SQL command only to FILE",
3430 " If FILE begins with '|' then open as a pipe",
3431 " Other options:",
3432 " -e Invoke system text editor",
3433 " -x Open in a spreadsheet",
3434 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3435 " Options:",
drh60f34ae2018-10-30 13:19:49 +00003436 " --append Use appendvfs to append database to the end of FILE",
3437 " --deserialize Load into memory useing sqlite3_deserialize()",
3438 " --new Initialize FILE to an empty database",
3439 " --readonly Open FILE readonly",
3440 " --zip FILE is a ZIP archive",
drh98aa2ab2018-09-26 16:53:51 +00003441 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
3442 " If FILE begins with '|' then open it as a pipe.",
3443 ".print STRING... Print literal STRING",
3444 ".prompt MAIN CONTINUE Replace the standard prompts",
3445 ".quit Exit this program",
3446 ".read FILE Read input from FILE",
3447 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
3448 ".save FILE Write in-memory database into FILE",
3449 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
3450 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
3451 " Options:",
3452 " --indent Try to pretty-print the schema",
drheb7f2a02018-09-26 18:02:32 +00003453 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
3454 " Options:",
3455 " --init Create a new SELFTEST table",
3456 " -v Verbose output",
drh98aa2ab2018-09-26 16:53:51 +00003457 ".separator COL ?ROW? Change the column and row separators",
drh2ce15c32017-07-11 13:34:40 +00003458#if defined(SQLITE_ENABLE_SESSION)
drheb7f2a02018-09-26 18:02:32 +00003459 ".session ?NAME? CMD ... Create or control sessions",
3460 " Subcommands:",
3461 " attach TABLE Attach TABLE",
3462 " changeset FILE Write a changeset into FILE",
3463 " close Close one session",
3464 " enable ?BOOLEAN? Set or query the enable bit",
3465 " filter GLOB... Reject tables matching GLOBs",
3466 " indirect ?BOOLEAN? Mark or query the indirect status",
3467 " isempty Query whether the session is empty",
3468 " list List currently open session names",
3469 " open DB NAME Open a new session on DB",
3470 " patchset FILE Write a patchset into FILE",
3471 " If ?NAME? is omitted, the first defined session is used.",
drh2ce15c32017-07-11 13:34:40 +00003472#endif
drheb7f2a02018-09-26 18:02:32 +00003473 ".sha3sum ... Compute a SHA3 hash of database content",
3474 " Options:",
3475 " --schema Also hash the sqlite_master table",
3476 " --sha3-224 Use the sha3-224 algorithm",
3477 " --sha3-256 Use the sha3-256 algorithm. This is the default.",
3478 " --sha3-384 Use the sha3-384 algorithm",
3479 " --sha3-512 Use the sha3-512 algorithm",
3480 " Any other argument is a LIKE pattern for tables to hash",
drh04a28c32018-01-31 01:38:44 +00003481#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003482 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003483#endif
drh98aa2ab2018-09-26 16:53:51 +00003484 ".show Show the current values for various settings",
3485 ".stats ?on|off? Show stats or turn stats on or off",
drh04a28c32018-01-31 01:38:44 +00003486#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003487 ".system CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003488#endif
drh98aa2ab2018-09-26 16:53:51 +00003489 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
3490 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
3491 ".timeout MS Try opening locked tables for MS milliseconds",
3492 ".timer on|off Turn SQL timer on or off",
3493 ".trace FILE|off Output each SQL statement as it is run",
3494 ".vfsinfo ?AUX? Information about the top-level VFS",
3495 ".vfslist List all available VFSes",
3496 ".vfsname ?AUX? Print the name of the VFS stack",
3497 ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
3498 " Negative values right-justify",
3499};
3500
3501/*
3502** Output help text.
3503**
3504** zPattern describes the set of commands for which help text is provided.
3505** If zPattern is NULL, then show all commands, but only give a one-line
3506** description of each.
3507**
3508** Return the number of matches.
3509*/
3510static int showHelp(FILE *out, const char *zPattern){
drhe93f8262018-10-11 16:53:37 +00003511 int i = 0;
3512 int j = 0;
drh98aa2ab2018-09-26 16:53:51 +00003513 int n = 0;
3514 char *zPat;
drh488cddf2018-10-06 14:38:17 +00003515 if( zPattern==0
3516 || zPattern[0]=='0'
3517 || strcmp(zPattern,"-a")==0
3518 || strcmp(zPattern,"-all")==0
3519 ){
drh98aa2ab2018-09-26 16:53:51 +00003520 /* Show all commands, but only one line per command */
drh488cddf2018-10-06 14:38:17 +00003521 if( zPattern==0 ) zPattern = "";
drh98aa2ab2018-09-26 16:53:51 +00003522 for(i=0; i<ArraySize(azHelp); i++){
drh488cddf2018-10-06 14:38:17 +00003523 if( azHelp[i][0]=='.' || zPattern[0] ){
drh98aa2ab2018-09-26 16:53:51 +00003524 utf8_printf(out, "%s\n", azHelp[i]);
3525 n++;
3526 }
3527 }
3528 }else{
3529 /* Look for commands that for which zPattern is an exact prefix */
3530 zPat = sqlite3_mprintf(".%s*", zPattern);
3531 for(i=0; i<ArraySize(azHelp); i++){
3532 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3533 utf8_printf(out, "%s\n", azHelp[i]);
drheb7f2a02018-09-26 18:02:32 +00003534 j = i+1;
drh98aa2ab2018-09-26 16:53:51 +00003535 n++;
3536 }
3537 }
3538 sqlite3_free(zPat);
drheb7f2a02018-09-26 18:02:32 +00003539 if( n ){
3540 if( n==1 ){
3541 /* when zPattern is a prefix of exactly one command, then include the
3542 ** details of that command, which should begin at offset j */
3543 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3544 utf8_printf(out, "%s\n", azHelp[j]);
3545 j++;
3546 }
3547 }
3548 return n;
3549 }
3550 /* Look for commands that contain zPattern anywhere. Show the complete
3551 ** text of all commands that match. */
drh98aa2ab2018-09-26 16:53:51 +00003552 zPat = sqlite3_mprintf("%%%s%%", zPattern);
3553 for(i=0; i<ArraySize(azHelp); i++){
3554 if( azHelp[i][0]=='.' ) j = i;
3555 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3556 utf8_printf(out, "%s\n", azHelp[j]);
3557 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3558 j++;
3559 utf8_printf(out, "%s\n", azHelp[j]);
3560 }
3561 i = j;
3562 n++;
3563 }
3564 }
3565 sqlite3_free(zPat);
3566 }
3567 return n;
3568}
drh2ce15c32017-07-11 13:34:40 +00003569
drh2ce15c32017-07-11 13:34:40 +00003570/* Forward reference */
3571static int process_input(ShellState *p, FILE *in);
3572
3573/*
3574** Read the content of file zName into memory obtained from sqlite3_malloc64()
3575** and return a pointer to the buffer. The caller is responsible for freeing
3576** the memory.
3577**
3578** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3579** read.
3580**
3581** For convenience, a nul-terminator byte is always appended to the data read
3582** from the file before the buffer is returned. This byte is not included in
3583** the final value of (*pnByte), if applicable.
3584**
3585** NULL is returned if any error is encountered. The final value of *pnByte
3586** is undefined in this case.
3587*/
3588static char *readFile(const char *zName, int *pnByte){
3589 FILE *in = fopen(zName, "rb");
3590 long nIn;
3591 size_t nRead;
3592 char *pBuf;
3593 if( in==0 ) return 0;
3594 fseek(in, 0, SEEK_END);
3595 nIn = ftell(in);
3596 rewind(in);
3597 pBuf = sqlite3_malloc64( nIn+1 );
drh1dbb1472018-10-11 10:37:24 +00003598 if( pBuf==0 ){ fclose(in); return 0; }
drh2ce15c32017-07-11 13:34:40 +00003599 nRead = fread(pBuf, nIn, 1, in);
3600 fclose(in);
3601 if( nRead!=1 ){
3602 sqlite3_free(pBuf);
3603 return 0;
3604 }
3605 pBuf[nIn] = 0;
3606 if( pnByte ) *pnByte = nIn;
3607 return pBuf;
3608}
3609
3610#if defined(SQLITE_ENABLE_SESSION)
3611/*
3612** Close a single OpenSession object and release all of its associated
3613** resources.
3614*/
3615static void session_close(OpenSession *pSession){
3616 int i;
3617 sqlite3session_delete(pSession->p);
3618 sqlite3_free(pSession->zName);
3619 for(i=0; i<pSession->nFilter; i++){
3620 sqlite3_free(pSession->azFilter[i]);
3621 }
3622 sqlite3_free(pSession->azFilter);
3623 memset(pSession, 0, sizeof(OpenSession));
3624}
3625#endif
3626
3627/*
3628** Close all OpenSession objects and release all associated resources.
3629*/
3630#if defined(SQLITE_ENABLE_SESSION)
3631static void session_close_all(ShellState *p){
3632 int i;
3633 for(i=0; i<p->nSession; i++){
3634 session_close(&p->aSession[i]);
3635 }
3636 p->nSession = 0;
3637}
3638#else
3639# define session_close_all(X)
3640#endif
3641
3642/*
3643** Implementation of the xFilter function for an open session. Omit
3644** any tables named by ".session filter" but let all other table through.
3645*/
3646#if defined(SQLITE_ENABLE_SESSION)
3647static int session_filter(void *pCtx, const char *zTab){
3648 OpenSession *pSession = (OpenSession*)pCtx;
3649 int i;
3650 for(i=0; i<pSession->nFilter; i++){
3651 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3652 }
3653 return 1;
3654}
3655#endif
3656
3657/*
drh1fa6d9f2018-01-06 21:46:01 +00003658** Try to deduce the type of file for zName based on its content. Return
3659** one of the SHELL_OPEN_* constants.
drh1bf208c2018-03-09 21:54:01 +00003660**
3661** If the file does not exist or is empty but its name looks like a ZIP
3662** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3663** Otherwise, assume an ordinary database regardless of the filename if
3664** the type cannot be determined from content.
drh1fa6d9f2018-01-06 21:46:01 +00003665*/
drhfc97c1c2018-05-14 00:41:12 +00003666int deduceDatabaseType(const char *zName, int dfltZip){
drh1fa6d9f2018-01-06 21:46:01 +00003667 FILE *f = fopen(zName, "rb");
3668 size_t n;
3669 int rc = SHELL_OPEN_UNSPEC;
3670 char zBuf[100];
drh1bf208c2018-03-09 21:54:01 +00003671 if( f==0 ){
drhbe4ccb22018-05-17 20:04:24 +00003672 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3673 return SHELL_OPEN_ZIPFILE;
3674 }else{
3675 return SHELL_OPEN_NORMAL;
3676 }
drh1bf208c2018-03-09 21:54:01 +00003677 }
drh2b3c4af2018-10-30 14:36:21 +00003678 n = fread(zBuf, 16, 1, f);
3679 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
3680 fclose(f);
3681 return SHELL_OPEN_NORMAL;
3682 }
drh1fa6d9f2018-01-06 21:46:01 +00003683 fseek(f, -25, SEEK_END);
3684 n = fread(zBuf, 25, 1, f);
3685 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3686 rc = SHELL_OPEN_APPENDVFS;
3687 }else{
3688 fseek(f, -22, SEEK_END);
3689 n = fread(zBuf, 22, 1, f);
3690 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3691 && zBuf[3]==0x06 ){
3692 rc = SHELL_OPEN_ZIPFILE;
drh1bf208c2018-03-09 21:54:01 +00003693 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
mistachkina3926f42018-05-14 12:23:04 +00003694 rc = SHELL_OPEN_ZIPFILE;
drh1fa6d9f2018-01-06 21:46:01 +00003695 }
3696 }
3697 fclose(f);
3698 return rc;
3699}
3700
drhbe4ccb22018-05-17 20:04:24 +00003701/* Flags for open_db().
3702**
3703** The default behavior of open_db() is to exit(1) if the database fails to
3704** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
3705** but still returns without calling exit.
3706**
3707** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
3708** ZIP archive if the file does not exist or is empty and its name matches
3709** the *.zip pattern.
3710*/
3711#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
3712#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
3713
drh1fa6d9f2018-01-06 21:46:01 +00003714/*
drh2ce15c32017-07-11 13:34:40 +00003715** Make sure the database is open. If it is not, then open it. If
3716** the database fails to open, print an error message and exit.
3717*/
drhbe4ccb22018-05-17 20:04:24 +00003718static void open_db(ShellState *p, int openFlags){
drh2ce15c32017-07-11 13:34:40 +00003719 if( p->db==0 ){
drhf2072d12018-05-11 15:10:11 +00003720 if( p->openMode==SHELL_OPEN_UNSPEC ){
3721 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
3722 p->openMode = SHELL_OPEN_NORMAL;
drhbe4ccb22018-05-17 20:04:24 +00003723 }else{
3724 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
3725 (openFlags & OPEN_DB_ZIPFILE)!=0);
drhf2072d12018-05-11 15:10:11 +00003726 }
drh1fa6d9f2018-01-06 21:46:01 +00003727 }
3728 switch( p->openMode ){
3729 case SHELL_OPEN_APPENDVFS: {
3730 sqlite3_open_v2(p->zDbFilename, &p->db,
3731 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
3732 break;
3733 }
drh60f34ae2018-10-30 13:19:49 +00003734 case SHELL_OPEN_DESERIALIZE: {
3735 sqlite3_open(0, &p->db);
3736 break;
3737 }
drh1fa6d9f2018-01-06 21:46:01 +00003738 case SHELL_OPEN_ZIPFILE: {
3739 sqlite3_open(":memory:", &p->db);
3740 break;
3741 }
drhee269a62018-02-14 23:27:43 +00003742 case SHELL_OPEN_READONLY: {
3743 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
3744 break;
3745 }
drh1fa6d9f2018-01-06 21:46:01 +00003746 case SHELL_OPEN_UNSPEC:
3747 case SHELL_OPEN_NORMAL: {
3748 sqlite3_open(p->zDbFilename, &p->db);
3749 break;
3750 }
3751 }
drh2ce15c32017-07-11 13:34:40 +00003752 globalDb = p->db;
3753 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3754 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3755 p->zDbFilename, sqlite3_errmsg(p->db));
drhbe4ccb22018-05-17 20:04:24 +00003756 if( openFlags & OPEN_DB_KEEPALIVE ) return;
drh2ce15c32017-07-11 13:34:40 +00003757 exit(1);
3758 }
3759#ifndef SQLITE_OMIT_LOAD_EXTENSION
3760 sqlite3_enable_load_extension(p->db, 1);
3761#endif
3762 sqlite3_fileio_init(p->db, 0, 0);
3763 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00003764 sqlite3_completion_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003765#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00003766 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00003767 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003768#endif
drhceba7922018-01-01 21:28:25 +00003769 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00003770 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00003771 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3772 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00003773 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
3774 shellPutsFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00003775#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00003776 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
3777 editFunc, 0, 0);
3778 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
3779 editFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00003780#endif
drh1fa6d9f2018-01-06 21:46:01 +00003781 if( p->openMode==SHELL_OPEN_ZIPFILE ){
3782 char *zSql = sqlite3_mprintf(
3783 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
3784 sqlite3_exec(p->db, zSql, 0, 0, 0);
3785 sqlite3_free(zSql);
drh60f34ae2018-10-30 13:19:49 +00003786 }else if( p->openMode==SHELL_OPEN_DESERIALIZE ){
3787 int nData = 0;
3788 unsigned char *aData = (unsigned char*)readFile(p->zDbFilename, &nData);
3789 int rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
3790 SQLITE_DESERIALIZE_RESIZEABLE |
3791 SQLITE_DESERIALIZE_FREEONCLOSE);
3792 if( rc ){
3793 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
3794 }
drh1fa6d9f2018-01-06 21:46:01 +00003795 }
drh2ce15c32017-07-11 13:34:40 +00003796 }
3797}
3798
drh9e804032018-05-18 17:11:50 +00003799/*
3800** Attempt to close the databaes connection. Report errors.
3801*/
3802void close_db(sqlite3 *db){
3803 int rc = sqlite3_close(db);
3804 if( rc ){
3805 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
3806 rc, sqlite3_errmsg(db));
3807 }
3808}
3809
drh56eb09b2017-07-11 13:59:07 +00003810#if HAVE_READLINE || HAVE_EDITLINE
3811/*
3812** Readline completion callbacks
3813*/
3814static char *readline_completion_generator(const char *text, int state){
3815 static sqlite3_stmt *pStmt = 0;
3816 char *zRet;
3817 if( state==0 ){
3818 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00003819 sqlite3_finalize(pStmt);
3820 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3821 " FROM completion(%Q) ORDER BY 1", text);
3822 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3823 sqlite3_free(zSql);
3824 }
3825 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00003826 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00003827 }else{
3828 sqlite3_finalize(pStmt);
3829 pStmt = 0;
3830 zRet = 0;
3831 }
3832 return zRet;
3833}
3834static char **readline_completion(const char *zText, int iStart, int iEnd){
3835 rl_attempted_completion_over = 1;
3836 return rl_completion_matches(zText, readline_completion_generator);
3837}
3838
3839#elif HAVE_LINENOISE
3840/*
3841** Linenoise completion callback
3842*/
3843static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00003844 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00003845 int i, iStart;
3846 sqlite3_stmt *pStmt = 0;
3847 char *zSql;
3848 char zBuf[1000];
3849
3850 if( nLine>sizeof(zBuf)-30 ) return;
drh1615c372018-05-12 23:56:22 +00003851 if( zLine[0]=='.' || zLine[0]=='#') return;
drh56eb09b2017-07-11 13:59:07 +00003852 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
3853 if( i==nLine-1 ) return;
3854 iStart = i+1;
3855 memcpy(zBuf, zLine, iStart);
3856 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3857 " FROM completion(%Q,%Q) ORDER BY 1",
3858 &zLine[iStart], zLine);
3859 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3860 sqlite3_free(zSql);
3861 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3862 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3863 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
3864 int nCompletion = sqlite3_column_bytes(pStmt, 0);
3865 if( iStart+nCompletion < sizeof(zBuf)-1 ){
3866 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
3867 linenoiseAddCompletion(lc, zBuf);
3868 }
3869 }
3870 sqlite3_finalize(pStmt);
3871}
3872#endif
3873
drh2ce15c32017-07-11 13:34:40 +00003874/*
3875** Do C-language style dequoting.
3876**
3877** \a -> alarm
3878** \b -> backspace
3879** \t -> tab
3880** \n -> newline
3881** \v -> vertical tab
3882** \f -> form feed
3883** \r -> carriage return
3884** \s -> space
3885** \" -> "
3886** \' -> '
3887** \\ -> backslash
3888** \NNN -> ascii character NNN in octal
3889*/
3890static void resolve_backslashes(char *z){
3891 int i, j;
3892 char c;
3893 while( *z && *z!='\\' ) z++;
3894 for(i=j=0; (c = z[i])!=0; i++, j++){
3895 if( c=='\\' && z[i+1]!=0 ){
3896 c = z[++i];
3897 if( c=='a' ){
3898 c = '\a';
3899 }else if( c=='b' ){
3900 c = '\b';
3901 }else if( c=='t' ){
3902 c = '\t';
3903 }else if( c=='n' ){
3904 c = '\n';
3905 }else if( c=='v' ){
3906 c = '\v';
3907 }else if( c=='f' ){
3908 c = '\f';
3909 }else if( c=='r' ){
3910 c = '\r';
3911 }else if( c=='"' ){
3912 c = '"';
3913 }else if( c=='\'' ){
3914 c = '\'';
3915 }else if( c=='\\' ){
3916 c = '\\';
3917 }else if( c>='0' && c<='7' ){
3918 c -= '0';
3919 if( z[i+1]>='0' && z[i+1]<='7' ){
3920 i++;
3921 c = (c<<3) + z[i] - '0';
3922 if( z[i+1]>='0' && z[i+1]<='7' ){
3923 i++;
3924 c = (c<<3) + z[i] - '0';
3925 }
3926 }
3927 }
3928 }
3929 z[j] = c;
3930 }
3931 if( j<i ) z[j] = 0;
3932}
3933
3934/*
drh2ce15c32017-07-11 13:34:40 +00003935** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3936** for TRUE and FALSE. Return the integer value if appropriate.
3937*/
3938static int booleanValue(const char *zArg){
3939 int i;
3940 if( zArg[0]=='0' && zArg[1]=='x' ){
3941 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3942 }else{
3943 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3944 }
3945 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3946 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3947 return 1;
3948 }
3949 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3950 return 0;
3951 }
3952 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3953 zArg);
3954 return 0;
3955}
3956
3957/*
3958** Set or clear a shell flag according to a boolean value.
3959*/
3960static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3961 if( booleanValue(zArg) ){
3962 ShellSetFlag(p, mFlag);
3963 }else{
3964 ShellClearFlag(p, mFlag);
3965 }
3966}
3967
3968/*
3969** Close an output file, assuming it is not stderr or stdout
3970*/
3971static void output_file_close(FILE *f){
3972 if( f && f!=stdout && f!=stderr ) fclose(f);
3973}
3974
3975/*
3976** Try to open an output file. The names "stdout" and "stderr" are
3977** recognized and do the right thing. NULL is returned if the output
3978** filename is "off".
3979*/
drha92a01a2018-01-10 22:15:37 +00003980static FILE *output_file_open(const char *zFile, int bTextMode){
drh2ce15c32017-07-11 13:34:40 +00003981 FILE *f;
3982 if( strcmp(zFile,"stdout")==0 ){
3983 f = stdout;
3984 }else if( strcmp(zFile, "stderr")==0 ){
3985 f = stderr;
3986 }else if( strcmp(zFile, "off")==0 ){
3987 f = 0;
3988 }else{
drha92a01a2018-01-10 22:15:37 +00003989 f = fopen(zFile, bTextMode ? "w" : "wb");
drh2ce15c32017-07-11 13:34:40 +00003990 if( f==0 ){
3991 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3992 }
3993 }
3994 return f;
3995}
3996
drh2ce15c32017-07-11 13:34:40 +00003997#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3998/*
3999** A routine for handling output from sqlite3_trace().
4000*/
4001static int sql_trace_callback(
4002 unsigned mType,
4003 void *pArg,
4004 void *pP,
4005 void *pX
4006){
4007 FILE *f = (FILE*)pArg;
4008 UNUSED_PARAMETER(mType);
4009 UNUSED_PARAMETER(pP);
4010 if( f ){
4011 const char *z = (const char*)pX;
drhaf2770f2018-01-05 14:55:43 +00004012 int i = strlen30(z);
drh2ce15c32017-07-11 13:34:40 +00004013 while( i>0 && z[i-1]==';' ){ i--; }
4014 utf8_printf(f, "%.*s;\n", i, z);
4015 }
4016 return 0;
4017}
4018#endif
drh2ce15c32017-07-11 13:34:40 +00004019
4020/*
4021** A no-op routine that runs with the ".breakpoint" doc-command. This is
4022** a useful spot to set a debugger breakpoint.
4023*/
4024static void test_breakpoint(void){
4025 static int nCall = 0;
4026 nCall++;
4027}
4028
4029/*
4030** An object used to read a CSV and other files for import.
4031*/
4032typedef struct ImportCtx ImportCtx;
4033struct ImportCtx {
4034 const char *zFile; /* Name of the input file */
4035 FILE *in; /* Read the CSV text from this input stream */
4036 char *z; /* Accumulated text for a field */
4037 int n; /* Number of bytes in z */
4038 int nAlloc; /* Space allocated for z[] */
4039 int nLine; /* Current line number */
4040 int bNotFirst; /* True if one or more bytes already read */
4041 int cTerm; /* Character that terminated the most recent field */
4042 int cColSep; /* The column separator character. (Usually ",") */
4043 int cRowSep; /* The row separator character. (Usually "\n") */
4044};
4045
4046/* Append a single byte to z[] */
4047static void import_append_char(ImportCtx *p, int c){
4048 if( p->n+1>=p->nAlloc ){
4049 p->nAlloc += p->nAlloc + 100;
4050 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drh4b5345c2018-04-24 13:07:40 +00004051 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004052 }
4053 p->z[p->n++] = (char)c;
4054}
4055
4056/* Read a single field of CSV text. Compatible with rfc4180 and extended
4057** with the option of having a separator other than ",".
4058**
4059** + Input comes from p->in.
4060** + Store results in p->z of length p->n. Space to hold p->z comes
4061** from sqlite3_malloc64().
4062** + Use p->cSep as the column separator. The default is ",".
4063** + Use p->rSep as the row separator. The default is "\n".
4064** + Keep track of the line number in p->nLine.
4065** + Store the character that terminates the field in p->cTerm. Store
4066** EOF on end-of-file.
4067** + Report syntax errors on stderr
4068*/
4069static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4070 int c;
4071 int cSep = p->cColSep;
4072 int rSep = p->cRowSep;
4073 p->n = 0;
4074 c = fgetc(p->in);
4075 if( c==EOF || seenInterrupt ){
4076 p->cTerm = EOF;
4077 return 0;
4078 }
4079 if( c=='"' ){
4080 int pc, ppc;
4081 int startLine = p->nLine;
4082 int cQuote = c;
4083 pc = ppc = 0;
4084 while( 1 ){
4085 c = fgetc(p->in);
4086 if( c==rSep ) p->nLine++;
4087 if( c==cQuote ){
4088 if( pc==cQuote ){
4089 pc = 0;
4090 continue;
4091 }
4092 }
4093 if( (c==cSep && pc==cQuote)
4094 || (c==rSep && pc==cQuote)
4095 || (c==rSep && pc=='\r' && ppc==cQuote)
4096 || (c==EOF && pc==cQuote)
4097 ){
4098 do{ p->n--; }while( p->z[p->n]!=cQuote );
4099 p->cTerm = c;
4100 break;
4101 }
4102 if( pc==cQuote && c!='\r' ){
4103 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4104 p->zFile, p->nLine, cQuote);
4105 }
4106 if( c==EOF ){
4107 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4108 p->zFile, startLine, cQuote);
4109 p->cTerm = c;
4110 break;
4111 }
4112 import_append_char(p, c);
4113 ppc = pc;
4114 pc = c;
4115 }
4116 }else{
4117 /* If this is the first field being parsed and it begins with the
4118 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4119 if( (c&0xff)==0xef && p->bNotFirst==0 ){
4120 import_append_char(p, c);
4121 c = fgetc(p->in);
4122 if( (c&0xff)==0xbb ){
4123 import_append_char(p, c);
4124 c = fgetc(p->in);
4125 if( (c&0xff)==0xbf ){
4126 p->bNotFirst = 1;
4127 p->n = 0;
4128 return csv_read_one_field(p);
4129 }
4130 }
4131 }
4132 while( c!=EOF && c!=cSep && c!=rSep ){
4133 import_append_char(p, c);
4134 c = fgetc(p->in);
4135 }
4136 if( c==rSep ){
4137 p->nLine++;
4138 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4139 }
4140 p->cTerm = c;
4141 }
4142 if( p->z ) p->z[p->n] = 0;
4143 p->bNotFirst = 1;
4144 return p->z;
4145}
4146
4147/* Read a single field of ASCII delimited text.
4148**
4149** + Input comes from p->in.
4150** + Store results in p->z of length p->n. Space to hold p->z comes
4151** from sqlite3_malloc64().
4152** + Use p->cSep as the column separator. The default is "\x1F".
4153** + Use p->rSep as the row separator. The default is "\x1E".
4154** + Keep track of the row number in p->nLine.
4155** + Store the character that terminates the field in p->cTerm. Store
4156** EOF on end-of-file.
4157** + Report syntax errors on stderr
4158*/
4159static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4160 int c;
4161 int cSep = p->cColSep;
4162 int rSep = p->cRowSep;
4163 p->n = 0;
4164 c = fgetc(p->in);
4165 if( c==EOF || seenInterrupt ){
4166 p->cTerm = EOF;
4167 return 0;
4168 }
4169 while( c!=EOF && c!=cSep && c!=rSep ){
4170 import_append_char(p, c);
4171 c = fgetc(p->in);
4172 }
4173 if( c==rSep ){
4174 p->nLine++;
4175 }
4176 p->cTerm = c;
4177 if( p->z ) p->z[p->n] = 0;
4178 return p->z;
4179}
4180
4181/*
4182** Try to transfer data for table zTable. If an error is seen while
4183** moving forward, try to go backwards. The backwards movement won't
4184** work for WITHOUT ROWID tables.
4185*/
4186static void tryToCloneData(
4187 ShellState *p,
4188 sqlite3 *newDb,
4189 const char *zTable
4190){
4191 sqlite3_stmt *pQuery = 0;
4192 sqlite3_stmt *pInsert = 0;
4193 char *zQuery = 0;
4194 char *zInsert = 0;
4195 int rc;
4196 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00004197 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00004198 int k = 0;
4199 int cnt = 0;
4200 const int spinRate = 10000;
4201
4202 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4203 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4204 if( rc ){
4205 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4206 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4207 zQuery);
4208 goto end_data_xfer;
4209 }
4210 n = sqlite3_column_count(pQuery);
4211 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh4b5345c2018-04-24 13:07:40 +00004212 if( zInsert==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004213 sqlite3_snprintf(200+nTable,zInsert,
4214 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00004215 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00004216 for(j=1; j<n; j++){
4217 memcpy(zInsert+i, ",?", 2);
4218 i += 2;
4219 }
4220 memcpy(zInsert+i, ");", 3);
4221 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4222 if( rc ){
4223 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4224 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4225 zQuery);
4226 goto end_data_xfer;
4227 }
4228 for(k=0; k<2; k++){
4229 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4230 for(i=0; i<n; i++){
4231 switch( sqlite3_column_type(pQuery, i) ){
4232 case SQLITE_NULL: {
4233 sqlite3_bind_null(pInsert, i+1);
4234 break;
4235 }
4236 case SQLITE_INTEGER: {
4237 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4238 break;
4239 }
4240 case SQLITE_FLOAT: {
4241 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4242 break;
4243 }
4244 case SQLITE_TEXT: {
4245 sqlite3_bind_text(pInsert, i+1,
4246 (const char*)sqlite3_column_text(pQuery,i),
4247 -1, SQLITE_STATIC);
4248 break;
4249 }
4250 case SQLITE_BLOB: {
4251 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4252 sqlite3_column_bytes(pQuery,i),
4253 SQLITE_STATIC);
4254 break;
4255 }
4256 }
4257 } /* End for */
4258 rc = sqlite3_step(pInsert);
4259 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4260 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4261 sqlite3_errmsg(newDb));
4262 }
4263 sqlite3_reset(pInsert);
4264 cnt++;
4265 if( (cnt%spinRate)==0 ){
4266 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4267 fflush(stdout);
4268 }
4269 } /* End while */
4270 if( rc==SQLITE_DONE ) break;
4271 sqlite3_finalize(pQuery);
4272 sqlite3_free(zQuery);
4273 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4274 zTable);
4275 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4276 if( rc ){
4277 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4278 break;
4279 }
4280 } /* End for(k=0...) */
4281
4282end_data_xfer:
4283 sqlite3_finalize(pQuery);
4284 sqlite3_finalize(pInsert);
4285 sqlite3_free(zQuery);
4286 sqlite3_free(zInsert);
4287}
4288
4289
4290/*
4291** Try to transfer all rows of the schema that match zWhere. For
4292** each row, invoke xForEach() on the object defined by that row.
4293** If an error is encountered while moving forward through the
4294** sqlite_master table, try again moving backwards.
4295*/
4296static void tryToCloneSchema(
4297 ShellState *p,
4298 sqlite3 *newDb,
4299 const char *zWhere,
4300 void (*xForEach)(ShellState*,sqlite3*,const char*)
4301){
4302 sqlite3_stmt *pQuery = 0;
4303 char *zQuery = 0;
4304 int rc;
4305 const unsigned char *zName;
4306 const unsigned char *zSql;
4307 char *zErrMsg = 0;
4308
4309 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4310 " WHERE %s", zWhere);
4311 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4312 if( rc ){
4313 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4314 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4315 zQuery);
4316 goto end_schema_xfer;
4317 }
4318 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4319 zName = sqlite3_column_text(pQuery, 0);
4320 zSql = sqlite3_column_text(pQuery, 1);
4321 printf("%s... ", zName); fflush(stdout);
4322 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4323 if( zErrMsg ){
4324 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4325 sqlite3_free(zErrMsg);
4326 zErrMsg = 0;
4327 }
4328 if( xForEach ){
4329 xForEach(p, newDb, (const char*)zName);
4330 }
4331 printf("done\n");
4332 }
4333 if( rc!=SQLITE_DONE ){
4334 sqlite3_finalize(pQuery);
4335 sqlite3_free(zQuery);
4336 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4337 " WHERE %s ORDER BY rowid DESC", zWhere);
4338 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4339 if( rc ){
4340 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4341 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4342 zQuery);
4343 goto end_schema_xfer;
4344 }
4345 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4346 zName = sqlite3_column_text(pQuery, 0);
4347 zSql = sqlite3_column_text(pQuery, 1);
4348 printf("%s... ", zName); fflush(stdout);
4349 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4350 if( zErrMsg ){
4351 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4352 sqlite3_free(zErrMsg);
4353 zErrMsg = 0;
4354 }
4355 if( xForEach ){
4356 xForEach(p, newDb, (const char*)zName);
4357 }
4358 printf("done\n");
4359 }
4360 }
4361end_schema_xfer:
4362 sqlite3_finalize(pQuery);
4363 sqlite3_free(zQuery);
4364}
4365
4366/*
4367** Open a new database file named "zNewDb". Try to recover as much information
4368** as possible out of the main database (which might be corrupt) and write it
4369** into zNewDb.
4370*/
4371static void tryToClone(ShellState *p, const char *zNewDb){
4372 int rc;
4373 sqlite3 *newDb = 0;
4374 if( access(zNewDb,0)==0 ){
4375 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4376 return;
4377 }
4378 rc = sqlite3_open(zNewDb, &newDb);
4379 if( rc ){
4380 utf8_printf(stderr, "Cannot create output database: %s\n",
4381 sqlite3_errmsg(newDb));
4382 }else{
4383 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4384 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4385 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4386 tryToCloneSchema(p, newDb, "type!='table'", 0);
4387 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4388 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4389 }
drh9e804032018-05-18 17:11:50 +00004390 close_db(newDb);
drh2ce15c32017-07-11 13:34:40 +00004391}
4392
4393/*
drh13c20932018-01-10 21:41:55 +00004394** Change the output file back to stdout.
4395**
4396** If the p->doXdgOpen flag is set, that means the output was being
4397** redirected to a temporary file named by p->zTempFile. In that case,
4398** launch start/open/xdg-open on that temporary file.
drh2ce15c32017-07-11 13:34:40 +00004399*/
4400static void output_reset(ShellState *p){
4401 if( p->outfile[0]=='|' ){
4402#ifndef SQLITE_OMIT_POPEN
4403 pclose(p->out);
4404#endif
4405 }else{
4406 output_file_close(p->out);
drh04a28c32018-01-31 01:38:44 +00004407#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00004408 if( p->doXdgOpen ){
4409 const char *zXdgOpenCmd =
4410#if defined(_WIN32)
4411 "start";
4412#elif defined(__APPLE__)
4413 "open";
4414#else
4415 "xdg-open";
4416#endif
4417 char *zCmd;
4418 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
drha92a01a2018-01-10 22:15:37 +00004419 if( system(zCmd) ){
4420 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4421 }
drh13c20932018-01-10 21:41:55 +00004422 sqlite3_free(zCmd);
drh3c484e82018-01-10 22:27:21 +00004423 outputModePop(p);
drh13c20932018-01-10 21:41:55 +00004424 p->doXdgOpen = 0;
4425 }
drh04a28c32018-01-31 01:38:44 +00004426#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00004427 }
4428 p->outfile[0] = 0;
4429 p->out = stdout;
4430}
4431
4432/*
4433** Run an SQL command and return the single integer result.
4434*/
4435static int db_int(ShellState *p, const char *zSql){
4436 sqlite3_stmt *pStmt;
4437 int res = 0;
4438 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4439 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4440 res = sqlite3_column_int(pStmt,0);
4441 }
4442 sqlite3_finalize(pStmt);
4443 return res;
4444}
4445
4446/*
4447** Convert a 2-byte or 4-byte big-endian integer into a native integer
4448*/
4449static unsigned int get2byteInt(unsigned char *a){
4450 return (a[0]<<8) + a[1];
4451}
4452static unsigned int get4byteInt(unsigned char *a){
4453 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4454}
4455
4456/*
4457** Implementation of the ".info" command.
4458**
4459** Return 1 on error, 2 to exit, and 0 otherwise.
4460*/
4461static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4462 static const struct { const char *zName; int ofst; } aField[] = {
4463 { "file change counter:", 24 },
4464 { "database page count:", 28 },
4465 { "freelist page count:", 36 },
4466 { "schema cookie:", 40 },
4467 { "schema format:", 44 },
4468 { "default cache size:", 48 },
4469 { "autovacuum top root:", 52 },
4470 { "incremental vacuum:", 64 },
4471 { "text encoding:", 56 },
4472 { "user version:", 60 },
4473 { "application id:", 68 },
4474 { "software version:", 96 },
4475 };
4476 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4477 { "number of tables:",
4478 "SELECT count(*) FROM %s WHERE type='table'" },
4479 { "number of indexes:",
4480 "SELECT count(*) FROM %s WHERE type='index'" },
4481 { "number of triggers:",
4482 "SELECT count(*) FROM %s WHERE type='trigger'" },
4483 { "number of views:",
4484 "SELECT count(*) FROM %s WHERE type='view'" },
4485 { "schema size:",
4486 "SELECT total(length(sql)) FROM %s" },
4487 };
drh2ce15c32017-07-11 13:34:40 +00004488 int i;
drhea99a312018-07-18 19:09:07 +00004489 unsigned iDataVersion;
drh2ce15c32017-07-11 13:34:40 +00004490 char *zSchemaTab;
4491 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004492 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004493 unsigned char aHdr[100];
4494 open_db(p, 0);
4495 if( p->db==0 ) return 1;
drh512e6c32017-10-11 17:51:08 +00004496 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4497 -1, &pStmt, 0);
4498 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4499 if( sqlite3_step(pStmt)==SQLITE_ROW
4500 && sqlite3_column_bytes(pStmt,0)>100
4501 ){
4502 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4503 sqlite3_finalize(pStmt);
4504 }else{
drh2ce15c32017-07-11 13:34:40 +00004505 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004506 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004507 return 1;
4508 }
4509 i = get2byteInt(aHdr+16);
4510 if( i==1 ) i = 65536;
4511 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4512 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4513 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4514 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4515 for(i=0; i<ArraySize(aField); i++){
4516 int ofst = aField[i].ofst;
4517 unsigned int val = get4byteInt(aHdr + ofst);
4518 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4519 switch( ofst ){
4520 case 56: {
4521 if( val==1 ) raw_printf(p->out, " (utf8)");
4522 if( val==2 ) raw_printf(p->out, " (utf16le)");
4523 if( val==3 ) raw_printf(p->out, " (utf16be)");
4524 }
4525 }
4526 raw_printf(p->out, "\n");
4527 }
4528 if( zDb==0 ){
4529 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4530 }else if( strcmp(zDb,"temp")==0 ){
4531 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4532 }else{
4533 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4534 }
4535 for(i=0; i<ArraySize(aQuery); i++){
4536 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4537 int val = db_int(p, zSql);
4538 sqlite3_free(zSql);
4539 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4540 }
4541 sqlite3_free(zSchemaTab);
drhea99a312018-07-18 19:09:07 +00004542 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
4543 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
drh2ce15c32017-07-11 13:34:40 +00004544 return 0;
4545}
4546
4547/*
4548** Print the current sqlite3_errmsg() value to stderr and return 1.
4549*/
4550static int shellDatabaseError(sqlite3 *db){
4551 const char *zErr = sqlite3_errmsg(db);
4552 utf8_printf(stderr, "Error: %s\n", zErr);
4553 return 1;
4554}
4555
4556/*
drh2ce15c32017-07-11 13:34:40 +00004557** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4558** if they match and FALSE (0) if they do not match.
4559**
4560** Globbing rules:
4561**
4562** '*' Matches any sequence of zero or more characters.
4563**
4564** '?' Matches exactly one character.
4565**
4566** [...] Matches one character from the enclosed list of
4567** characters.
4568**
4569** [^...] Matches one character not in the enclosed list.
4570**
4571** '#' Matches any sequence of one or more digits with an
4572** optional + or - sign in front
4573**
4574** ' ' Any span of whitespace matches any other span of
4575** whitespace.
4576**
4577** Extra whitespace at the end of z[] is ignored.
4578*/
4579static int testcase_glob(const char *zGlob, const char *z){
4580 int c, c2;
4581 int invert;
4582 int seen;
4583
4584 while( (c = (*(zGlob++)))!=0 ){
4585 if( IsSpace(c) ){
4586 if( !IsSpace(*z) ) return 0;
4587 while( IsSpace(*zGlob) ) zGlob++;
4588 while( IsSpace(*z) ) z++;
4589 }else if( c=='*' ){
4590 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4591 if( c=='?' && (*(z++))==0 ) return 0;
4592 }
4593 if( c==0 ){
4594 return 1;
4595 }else if( c=='[' ){
4596 while( *z && testcase_glob(zGlob-1,z)==0 ){
4597 z++;
4598 }
4599 return (*z)!=0;
4600 }
4601 while( (c2 = (*(z++)))!=0 ){
4602 while( c2!=c ){
4603 c2 = *(z++);
4604 if( c2==0 ) return 0;
4605 }
4606 if( testcase_glob(zGlob,z) ) return 1;
4607 }
4608 return 0;
4609 }else if( c=='?' ){
4610 if( (*(z++))==0 ) return 0;
4611 }else if( c=='[' ){
4612 int prior_c = 0;
4613 seen = 0;
4614 invert = 0;
4615 c = *(z++);
4616 if( c==0 ) return 0;
4617 c2 = *(zGlob++);
4618 if( c2=='^' ){
4619 invert = 1;
4620 c2 = *(zGlob++);
4621 }
4622 if( c2==']' ){
4623 if( c==']' ) seen = 1;
4624 c2 = *(zGlob++);
4625 }
4626 while( c2 && c2!=']' ){
4627 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4628 c2 = *(zGlob++);
4629 if( c>=prior_c && c<=c2 ) seen = 1;
4630 prior_c = 0;
4631 }else{
4632 if( c==c2 ){
4633 seen = 1;
4634 }
4635 prior_c = c2;
4636 }
4637 c2 = *(zGlob++);
4638 }
4639 if( c2==0 || (seen ^ invert)==0 ) return 0;
4640 }else if( c=='#' ){
4641 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4642 if( !IsDigit(z[0]) ) return 0;
4643 z++;
4644 while( IsDigit(z[0]) ){ z++; }
4645 }else{
4646 if( c!=(*(z++)) ) return 0;
4647 }
4648 }
4649 while( IsSpace(*z) ){ z++; }
4650 return *z==0;
4651}
4652
4653
4654/*
4655** Compare the string as a command-line option with either one or two
4656** initial "-" characters.
4657*/
4658static int optionMatch(const char *zStr, const char *zOpt){
4659 if( zStr[0]!='-' ) return 0;
4660 zStr++;
4661 if( zStr[0]=='-' ) zStr++;
4662 return strcmp(zStr, zOpt)==0;
4663}
4664
4665/*
4666** Delete a file.
4667*/
4668int shellDeleteFile(const char *zFilename){
4669 int rc;
4670#ifdef _WIN32
4671 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4672 rc = _wunlink(z);
4673 sqlite3_free(z);
4674#else
4675 rc = unlink(zFilename);
4676#endif
4677 return rc;
4678}
4679
drh13c20932018-01-10 21:41:55 +00004680/*
4681** Try to delete the temporary file (if there is one) and free the
4682** memory used to hold the name of the temp file.
4683*/
4684static void clearTempFile(ShellState *p){
4685 if( p->zTempFile==0 ) return;
drh536c3452018-01-11 00:38:39 +00004686 if( p->doXdgOpen ) return;
drh13c20932018-01-10 21:41:55 +00004687 if( shellDeleteFile(p->zTempFile) ) return;
4688 sqlite3_free(p->zTempFile);
4689 p->zTempFile = 0;
4690}
4691
4692/*
4693** Create a new temp file name with the given suffix.
4694*/
4695static void newTempFile(ShellState *p, const char *zSuffix){
4696 clearTempFile(p);
4697 sqlite3_free(p->zTempFile);
4698 p->zTempFile = 0;
drh7f3bf8a2018-01-10 21:50:08 +00004699 if( p->db ){
4700 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
4701 }
drh13c20932018-01-10 21:41:55 +00004702 if( p->zTempFile==0 ){
4703 sqlite3_uint64 r;
4704 sqlite3_randomness(sizeof(r), &r);
4705 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
4706 }else{
4707 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
4708 }
4709 if( p->zTempFile==0 ){
4710 raw_printf(stderr, "out of memory\n");
4711 exit(1);
4712 }
4713}
4714
drh2ce15c32017-07-11 13:34:40 +00004715
4716/*
4717** The implementation of SQL scalar function fkey_collate_clause(), used
4718** by the ".lint fkey-indexes" command. This scalar function is always
4719** called with four arguments - the parent table name, the parent column name,
4720** the child table name and the child column name.
4721**
4722** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4723**
4724** If either of the named tables or columns do not exist, this function
4725** returns an empty string. An empty string is also returned if both tables
4726** and columns exist but have the same default collation sequence. Or,
4727** if both exist but the default collation sequences are different, this
4728** function returns the string " COLLATE <parent-collation>", where
4729** <parent-collation> is the default collation sequence of the parent column.
4730*/
4731static void shellFkeyCollateClause(
4732 sqlite3_context *pCtx,
4733 int nVal,
4734 sqlite3_value **apVal
4735){
4736 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4737 const char *zParent;
4738 const char *zParentCol;
4739 const char *zParentSeq;
4740 const char *zChild;
4741 const char *zChildCol;
4742 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4743 int rc;
4744
4745 assert( nVal==4 );
4746 zParent = (const char*)sqlite3_value_text(apVal[0]);
4747 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4748 zChild = (const char*)sqlite3_value_text(apVal[2]);
4749 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4750
4751 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4752 rc = sqlite3_table_column_metadata(
4753 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4754 );
4755 if( rc==SQLITE_OK ){
4756 rc = sqlite3_table_column_metadata(
4757 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4758 );
4759 }
4760
4761 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4762 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4763 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4764 sqlite3_free(z);
4765 }
4766}
4767
4768
4769/*
4770** The implementation of dot-command ".lint fkey-indexes".
4771*/
4772static int lintFkeyIndexes(
4773 ShellState *pState, /* Current shell tool state */
4774 char **azArg, /* Array of arguments passed to dot command */
4775 int nArg /* Number of entries in azArg[] */
4776){
4777 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4778 FILE *out = pState->out; /* Stream to write non-error output to */
4779 int bVerbose = 0; /* If -verbose is present */
4780 int bGroupByParent = 0; /* If -groupbyparent is present */
4781 int i; /* To iterate through azArg[] */
4782 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4783 int rc; /* Return code */
4784 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4785
4786 /*
4787 ** This SELECT statement returns one row for each foreign key constraint
4788 ** in the schema of the main database. The column values are:
4789 **
4790 ** 0. The text of an SQL statement similar to:
4791 **
danf9679312017-12-01 18:40:18 +00004792 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00004793 **
danf9679312017-12-01 18:40:18 +00004794 ** This SELECT is similar to the one that the foreign keys implementation
4795 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00004796 ** be used to optimize this query, then it can also be used by the FK
4797 ** implementation to optimize DELETE or UPDATE statements on the parent
4798 ** table.
4799 **
4800 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4801 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4802 ** contains an index that can be used to optimize the query.
4803 **
4804 ** 2. Human readable text that describes the child table and columns. e.g.
4805 **
4806 ** "child_table(child_key1, child_key2)"
4807 **
4808 ** 3. Human readable text that describes the parent table and columns. e.g.
4809 **
4810 ** "parent_table(parent_key1, parent_key2)"
4811 **
4812 ** 4. A full CREATE INDEX statement for an index that could be used to
4813 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4814 **
4815 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4816 **
4817 ** 5. The name of the parent table.
4818 **
4819 ** These six values are used by the C logic below to generate the report.
4820 */
4821 const char *zSql =
4822 "SELECT "
danf9679312017-12-01 18:40:18 +00004823 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00004824 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4825 " || fkey_collate_clause("
4826 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4827 ", "
4828 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4829 " || group_concat('*=?', ' AND ') || ')'"
4830 ", "
4831 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4832 ", "
4833 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4834 ", "
4835 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4836 " || ' ON ' || quote(s.name) || '('"
4837 " || group_concat(quote(f.[from]) ||"
4838 " fkey_collate_clause("
4839 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4840 " || ');'"
4841 ", "
4842 " f.[table] "
4843 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4844 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4845 "GROUP BY s.name, f.id "
4846 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4847 ;
4848 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4849
4850 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00004851 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00004852 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4853 bVerbose = 1;
4854 }
4855 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4856 bGroupByParent = 1;
4857 zIndent = " ";
4858 }
4859 else{
4860 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4861 azArg[0], azArg[1]
4862 );
4863 return SQLITE_ERROR;
4864 }
4865 }
4866
4867 /* Register the fkey_collate_clause() SQL function */
4868 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4869 0, shellFkeyCollateClause, 0, 0
4870 );
4871
4872
4873 if( rc==SQLITE_OK ){
4874 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4875 }
4876 if( rc==SQLITE_OK ){
4877 sqlite3_bind_int(pSql, 1, bGroupByParent);
4878 }
4879
4880 if( rc==SQLITE_OK ){
4881 int rc2;
4882 char *zPrev = 0;
4883 while( SQLITE_ROW==sqlite3_step(pSql) ){
4884 int res = -1;
4885 sqlite3_stmt *pExplain = 0;
4886 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4887 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4888 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4889 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4890 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4891 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4892
4893 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4894 if( rc!=SQLITE_OK ) break;
4895 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4896 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4897 res = (
4898 0==sqlite3_strglob(zGlob, zPlan)
4899 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4900 );
4901 }
4902 rc = sqlite3_finalize(pExplain);
4903 if( rc!=SQLITE_OK ) break;
4904
4905 if( res<0 ){
4906 raw_printf(stderr, "Error: internal error");
4907 break;
4908 }else{
4909 if( bGroupByParent
4910 && (bVerbose || res==0)
4911 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4912 ){
4913 raw_printf(out, "-- Parent table %s\n", zParent);
4914 sqlite3_free(zPrev);
4915 zPrev = sqlite3_mprintf("%s", zParent);
4916 }
4917
4918 if( res==0 ){
4919 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4920 }else if( bVerbose ){
4921 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4922 zIndent, zFrom, zTarget
4923 );
4924 }
4925 }
4926 }
4927 sqlite3_free(zPrev);
4928
4929 if( rc!=SQLITE_OK ){
4930 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4931 }
4932
4933 rc2 = sqlite3_finalize(pSql);
4934 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4935 rc = rc2;
4936 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4937 }
4938 }else{
4939 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4940 }
4941
4942 return rc;
4943}
4944
4945/*
4946** Implementation of ".lint" dot command.
4947*/
4948static int lintDotCommand(
4949 ShellState *pState, /* Current shell tool state */
4950 char **azArg, /* Array of arguments passed to dot command */
4951 int nArg /* Number of entries in azArg[] */
4952){
4953 int n;
drhaf2770f2018-01-05 14:55:43 +00004954 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00004955 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4956 return lintFkeyIndexes(pState, azArg, nArg);
4957
4958 usage:
4959 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4960 raw_printf(stderr, "Where sub-commands are:\n");
4961 raw_printf(stderr, " fkey-indexes\n");
4962 return SQLITE_ERROR;
4963}
4964
drhe37c0e12018-01-06 19:19:50 +00004965#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4966/*********************************************************************************
4967** The ".archive" or ".ar" command.
4968*/
danfd0245d2017-12-07 15:44:29 +00004969static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00004970 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00004971 int *pRc,
4972 const char *zSql,
4973 sqlite3_stmt **ppStmt
4974){
4975 *ppStmt = 0;
4976 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004977 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00004978 if( rc!=SQLITE_OK ){
4979 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00004980 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00004981 );
4982 *pRc = rc;
4983 }
4984 }
4985}
4986
danac15e2d2017-12-14 19:15:07 +00004987static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00004988 sqlite3 *db,
4989 int *pRc,
danac15e2d2017-12-14 19:15:07 +00004990 sqlite3_stmt **ppStmt,
4991 const char *zFmt,
4992 ...
dan3f67ddf2017-12-13 20:04:53 +00004993){
danac15e2d2017-12-14 19:15:07 +00004994 *ppStmt = 0;
4995 if( *pRc==SQLITE_OK ){
4996 va_list ap;
4997 char *z;
4998 va_start(ap, zFmt);
4999 z = sqlite3_vmprintf(zFmt, ap);
drh1dbb1472018-10-11 10:37:24 +00005000 va_end(ap);
dan3f67ddf2017-12-13 20:04:53 +00005001 if( z==0 ){
5002 *pRc = SQLITE_NOMEM;
5003 }else{
5004 shellPrepare(db, pRc, z, ppStmt);
5005 sqlite3_free(z);
5006 }
dan3f67ddf2017-12-13 20:04:53 +00005007 }
5008}
5009
danfd0245d2017-12-07 15:44:29 +00005010static void shellFinalize(
5011 int *pRc,
5012 sqlite3_stmt *pStmt
5013){
dan25c12182017-12-07 21:03:33 +00005014 if( pStmt ){
5015 sqlite3 *db = sqlite3_db_handle(pStmt);
5016 int rc = sqlite3_finalize(pStmt);
5017 if( *pRc==SQLITE_OK ){
5018 if( rc!=SQLITE_OK ){
5019 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5020 }
5021 *pRc = rc;
5022 }
5023 }
danfd0245d2017-12-07 15:44:29 +00005024}
5025
5026static void shellReset(
5027 int *pRc,
5028 sqlite3_stmt *pStmt
5029){
5030 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00005031 if( *pRc==SQLITE_OK ){
5032 if( rc!=SQLITE_OK ){
5033 sqlite3 *db = sqlite3_db_handle(pStmt);
5034 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5035 }
5036 *pRc = rc;
5037 }
danfd0245d2017-12-07 15:44:29 +00005038}
drhe37c0e12018-01-06 19:19:50 +00005039/*
dan88be0202017-12-09 17:58:02 +00005040** Structure representing a single ".ar" command.
5041*/
5042typedef struct ArCommand ArCommand;
5043struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00005044 u8 eCmd; /* An AR_CMD_* value */
5045 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00005046 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00005047 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00005048 u8 bAppend; /* True if --append */
drhd0f9cdc2018-05-17 14:09:06 +00005049 u8 fromCmdLine; /* Run from -A instead of .archive */
drhb376b3d2018-01-10 13:11:51 +00005050 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00005051 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00005052 const char *zFile; /* --file argument, or NULL */
5053 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00005054 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00005055 ShellState *p; /* Shell state */
5056 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00005057};
5058
5059/*
5060** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5061*/
dan0d0547f2017-12-14 15:40:42 +00005062static int arUsage(FILE *f){
drh98aa2ab2018-09-26 16:53:51 +00005063 showHelp(f,"archive");
dan0d0547f2017-12-14 15:40:42 +00005064 return SQLITE_ERROR;
5065}
5066
5067/*
5068** Print an error message for the .ar command to stderr and return
5069** SQLITE_ERROR.
5070*/
drhd0f9cdc2018-05-17 14:09:06 +00005071static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
dan0d0547f2017-12-14 15:40:42 +00005072 va_list ap;
5073 char *z;
5074 va_start(ap, zFmt);
5075 z = sqlite3_vmprintf(zFmt, ap);
5076 va_end(ap);
drhd0f9cdc2018-05-17 14:09:06 +00005077 utf8_printf(stderr, "Error: %s\n", z);
5078 if( pAr->fromCmdLine ){
5079 utf8_printf(stderr, "Use \"-A\" for more help\n");
5080 }else{
5081 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5082 }
dan0d0547f2017-12-14 15:40:42 +00005083 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00005084 return SQLITE_ERROR;
5085}
5086
5087/*
5088** Values for ArCommand.eCmd.
5089*/
dand4b56e52017-12-12 20:04:59 +00005090#define AR_CMD_CREATE 1
5091#define AR_CMD_EXTRACT 2
5092#define AR_CMD_LIST 3
5093#define AR_CMD_UPDATE 4
dan0d0547f2017-12-14 15:40:42 +00005094#define AR_CMD_HELP 5
dand4b56e52017-12-12 20:04:59 +00005095
5096/*
5097** Other (non-command) switches.
5098*/
drhb376b3d2018-01-10 13:11:51 +00005099#define AR_SWITCH_VERBOSE 6
5100#define AR_SWITCH_FILE 7
5101#define AR_SWITCH_DIRECTORY 8
drha5676c42018-01-10 15:17:34 +00005102#define AR_SWITCH_APPEND 9
drhb376b3d2018-01-10 13:11:51 +00005103#define AR_SWITCH_DRYRUN 10
dand4b56e52017-12-12 20:04:59 +00005104
5105static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5106 switch( eSwitch ){
5107 case AR_CMD_CREATE:
5108 case AR_CMD_EXTRACT:
5109 case AR_CMD_LIST:
5110 case AR_CMD_UPDATE:
dan0d0547f2017-12-14 15:40:42 +00005111 case AR_CMD_HELP:
5112 if( pAr->eCmd ){
drhd0f9cdc2018-05-17 14:09:06 +00005113 return arErrorMsg(pAr, "multiple command options");
dan0d0547f2017-12-14 15:40:42 +00005114 }
dand4b56e52017-12-12 20:04:59 +00005115 pAr->eCmd = eSwitch;
5116 break;
5117
drhb376b3d2018-01-10 13:11:51 +00005118 case AR_SWITCH_DRYRUN:
5119 pAr->bDryRun = 1;
5120 break;
dand4b56e52017-12-12 20:04:59 +00005121 case AR_SWITCH_VERBOSE:
5122 pAr->bVerbose = 1;
5123 break;
drha5676c42018-01-10 15:17:34 +00005124 case AR_SWITCH_APPEND:
5125 pAr->bAppend = 1;
drhca7733b2018-01-10 18:09:20 +00005126 /* Fall thru into --file */
dand4b56e52017-12-12 20:04:59 +00005127 case AR_SWITCH_FILE:
5128 pAr->zFile = zArg;
5129 break;
5130 case AR_SWITCH_DIRECTORY:
5131 pAr->zDir = zArg;
5132 break;
5133 }
5134
5135 return SQLITE_OK;
5136}
dan88be0202017-12-09 17:58:02 +00005137
5138/*
5139** Parse the command line for an ".ar" command. The results are written into
5140** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5141** successfully, otherwise an error message is written to stderr and
5142** SQLITE_ERROR returned.
5143*/
5144static int arParseCommand(
5145 char **azArg, /* Array of arguments passed to dot command */
5146 int nArg, /* Number of entries in azArg[] */
5147 ArCommand *pAr /* Populate this object */
5148){
dand4b56e52017-12-12 20:04:59 +00005149 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00005150 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00005151 char cShort;
5152 u8 eSwitch;
5153 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00005154 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00005155 { "create", 'c', AR_CMD_CREATE, 0 },
5156 { "extract", 'x', AR_CMD_EXTRACT, 0 },
5157 { "list", 't', AR_CMD_LIST, 0 },
5158 { "update", 'u', AR_CMD_UPDATE, 0 },
5159 { "help", 'h', AR_CMD_HELP, 0 },
5160 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
5161 { "file", 'f', AR_SWITCH_FILE, 1 },
drhca7733b2018-01-10 18:09:20 +00005162 { "append", 'a', AR_SWITCH_APPEND, 1 },
drhb376b3d2018-01-10 13:11:51 +00005163 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drhb376b3d2018-01-10 13:11:51 +00005164 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00005165 };
5166 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5167 struct ArSwitch *pEnd = &aSwitch[nSwitch];
5168
dan88be0202017-12-09 17:58:02 +00005169 if( nArg<=1 ){
drh98aa2ab2018-09-26 16:53:51 +00005170 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
dan0d0547f2017-12-14 15:40:42 +00005171 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00005172 }else{
5173 char *z = azArg[1];
dan88be0202017-12-09 17:58:02 +00005174 if( z[0]!='-' ){
5175 /* Traditional style [tar] invocation */
5176 int i;
5177 int iArg = 2;
5178 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00005179 const char *zArg = 0;
5180 struct ArSwitch *pOpt;
5181 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5182 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00005183 }
dan0d0547f2017-12-14 15:40:42 +00005184 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005185 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005186 }
dand4b56e52017-12-12 20:04:59 +00005187 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005188 if( iArg>=nArg ){
drhd0f9cdc2018-05-17 14:09:06 +00005189 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005190 }
dand4b56e52017-12-12 20:04:59 +00005191 zArg = azArg[iArg++];
5192 }
5193 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00005194 }
dan88be0202017-12-09 17:58:02 +00005195 pAr->nArg = nArg-iArg;
5196 if( pAr->nArg>0 ){
5197 pAr->azArg = &azArg[iArg];
5198 }
dand4b56e52017-12-12 20:04:59 +00005199 }else{
5200 /* Non-traditional invocation */
5201 int iArg;
5202 for(iArg=1; iArg<nArg; iArg++){
5203 int n;
5204 z = azArg[iArg];
5205 if( z[0]!='-' ){
5206 /* All remaining command line words are command arguments. */
5207 pAr->azArg = &azArg[iArg];
5208 pAr->nArg = nArg-iArg;
5209 break;
5210 }
drhaf2770f2018-01-05 14:55:43 +00005211 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00005212
5213 if( z[1]!='-' ){
5214 int i;
5215 /* One or more short options */
5216 for(i=1; i<n; i++){
5217 const char *zArg = 0;
5218 struct ArSwitch *pOpt;
5219 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5220 if( z[i]==pOpt->cShort ) break;
5221 }
dan0d0547f2017-12-14 15:40:42 +00005222 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005223 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005224 }
dand4b56e52017-12-12 20:04:59 +00005225 if( pOpt->bArg ){
5226 if( i<(n-1) ){
5227 zArg = &z[i+1];
5228 i = n;
5229 }else{
dan0d0547f2017-12-14 15:40:42 +00005230 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005231 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005232 }
dand4b56e52017-12-12 20:04:59 +00005233 zArg = azArg[++iArg];
5234 }
5235 }
5236 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5237 }
5238 }else if( z[2]=='\0' ){
5239 /* A -- option, indicating that all remaining command line words
5240 ** are command arguments. */
5241 pAr->azArg = &azArg[iArg+1];
5242 pAr->nArg = nArg-iArg-1;
5243 break;
5244 }else{
5245 /* A long option */
5246 const char *zArg = 0; /* Argument for option, if any */
5247 struct ArSwitch *pMatch = 0; /* Matching option */
5248 struct ArSwitch *pOpt; /* Iterator */
5249 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5250 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00005251 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00005252 if( pMatch ){
drhd0f9cdc2018-05-17 14:09:06 +00005253 return arErrorMsg(pAr, "ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00005254 }else{
5255 pMatch = pOpt;
5256 }
5257 }
5258 }
5259
5260 if( pMatch==0 ){
drhd0f9cdc2018-05-17 14:09:06 +00005261 return arErrorMsg(pAr, "unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00005262 }
5263 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005264 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005265 return arErrorMsg(pAr, "option requires an argument: %s", z);
dan0d0547f2017-12-14 15:40:42 +00005266 }
dand4b56e52017-12-12 20:04:59 +00005267 zArg = azArg[++iArg];
5268 }
5269 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5270 }
5271 }
dan88be0202017-12-09 17:58:02 +00005272 }
5273 }
5274
5275 return SQLITE_OK;
5276}
5277
5278/*
dan3f67ddf2017-12-13 20:04:53 +00005279** This function assumes that all arguments within the ArCommand.azArg[]
5280** array refer to archive members, as for the --extract or --list commands.
5281** It checks that each of them are present. If any specified file is not
5282** present in the archive, an error is printed to stderr and an error
5283** code returned. Otherwise, if all specified arguments are present in
5284** the archive, SQLITE_OK is returned.
5285**
5286** This function strips any trailing '/' characters from each argument.
5287** This is consistent with the way the [tar] command seems to work on
5288** Linux.
5289*/
drhb376b3d2018-01-10 13:11:51 +00005290static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00005291 int rc = SQLITE_OK;
5292 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00005293 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00005294 sqlite3_stmt *pTest = 0;
5295
drhb376b3d2018-01-10 13:11:51 +00005296 shellPreparePrintf(pAr->db, &rc, &pTest,
5297 "SELECT name FROM %s WHERE name=$name",
5298 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00005299 );
drhb376b3d2018-01-10 13:11:51 +00005300 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00005301 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5302 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00005303 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00005304 int bOk = 0;
5305 while( n>0 && z[n-1]=='/' ) n--;
5306 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00005307 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00005308 if( SQLITE_ROW==sqlite3_step(pTest) ){
5309 bOk = 1;
5310 }
5311 shellReset(&rc, pTest);
5312 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00005313 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00005314 rc = SQLITE_ERROR;
5315 }
5316 }
5317 shellFinalize(&rc, pTest);
5318 }
dan3f67ddf2017-12-13 20:04:53 +00005319 return rc;
5320}
5321
5322/*
5323** Format a WHERE clause that can be used against the "sqlar" table to
5324** identify all archive members that match the command arguments held
5325** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5326** The caller is responsible for eventually calling sqlite3_free() on
5327** any non-NULL (*pzWhere) value.
5328*/
5329static void arWhereClause(
5330 int *pRc,
5331 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00005332 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00005333){
5334 char *zWhere = 0;
5335 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00005336 if( pAr->nArg==0 ){
5337 zWhere = sqlite3_mprintf("1");
5338 }else{
5339 int i;
5340 const char *zSep = "";
5341 for(i=0; i<pAr->nArg; i++){
5342 const char *z = pAr->azArg[i];
5343 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00005344 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5345 zWhere, zSep, z, strlen30(z)+1, z
5346 );
danac15e2d2017-12-14 19:15:07 +00005347 if( zWhere==0 ){
5348 *pRc = SQLITE_NOMEM;
5349 break;
5350 }
5351 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00005352 }
dan3f67ddf2017-12-13 20:04:53 +00005353 }
5354 }
5355 *pzWhere = zWhere;
5356}
5357
5358/*
dan88be0202017-12-09 17:58:02 +00005359** Implementation of .ar "lisT" command.
5360*/
drhb376b3d2018-01-10 13:11:51 +00005361static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00005362 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00005363 const char *azCols[] = {
5364 "name",
drh410cad92018-01-10 17:19:16 +00005365 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00005366 };
dan5a78b812017-12-27 18:54:11 +00005367
dan3f67ddf2017-12-13 20:04:53 +00005368 char *zWhere = 0;
5369 sqlite3_stmt *pSql = 0;
5370 int rc;
5371
drhb376b3d2018-01-10 13:11:51 +00005372 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005373 arWhereClause(&rc, pAr, &zWhere);
5374
drhb376b3d2018-01-10 13:11:51 +00005375 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5376 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00005377 if( pAr->bDryRun ){
5378 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5379 }else{
5380 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5381 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00005382 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5383 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00005384 sqlite3_column_int(pSql, 1),
5385 sqlite3_column_text(pSql, 2),
5386 sqlite3_column_text(pSql, 3)
5387 );
5388 }else{
5389 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5390 }
danb5090e42017-12-27 21:13:21 +00005391 }
dan3f67ddf2017-12-13 20:04:53 +00005392 }
dan5a78b812017-12-27 18:54:11 +00005393 shellFinalize(&rc, pSql);
drhd0f9cdc2018-05-17 14:09:06 +00005394 sqlite3_free(zWhere);
dan3f67ddf2017-12-13 20:04:53 +00005395 return rc;
dan88be0202017-12-09 17:58:02 +00005396}
5397
5398
danfd0245d2017-12-07 15:44:29 +00005399/*
5400** Implementation of .ar "eXtract" command.
5401*/
drhb376b3d2018-01-10 13:11:51 +00005402static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00005403 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00005404 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00005405 " ($dir || name),"
5406 " writefile(($dir || name), %s, mode, mtime) "
drh0cfd46a2018-06-06 01:18:01 +00005407 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5408 " AND name NOT GLOB '*..[/\\]*'";
dan5a78b812017-12-27 18:54:11 +00005409
5410 const char *azExtraArg[] = {
5411 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00005412 "data"
dan5a78b812017-12-27 18:54:11 +00005413 };
dan5a78b812017-12-27 18:54:11 +00005414
danfd0245d2017-12-07 15:44:29 +00005415 sqlite3_stmt *pSql = 0;
5416 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00005417 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00005418 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00005419 int i, j;
dan2ad09492017-12-09 18:28:22 +00005420
dan3f67ddf2017-12-13 20:04:53 +00005421 /* If arguments are specified, check that they actually exist within
5422 ** the archive before proceeding. And formulate a WHERE clause to
5423 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00005424 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005425 arWhereClause(&rc, pAr, &zWhere);
5426
5427 if( rc==SQLITE_OK ){
5428 if( pAr->zDir ){
5429 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5430 }else{
5431 zDir = sqlite3_mprintf("");
5432 }
5433 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00005434 }
danfd0245d2017-12-07 15:44:29 +00005435
drhb376b3d2018-01-10 13:11:51 +00005436 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5437 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00005438 );
5439
dan2ad09492017-12-09 18:28:22 +00005440 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005441 j = sqlite3_bind_parameter_index(pSql, "$dir");
5442 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00005443
danac15e2d2017-12-14 19:15:07 +00005444 /* Run the SELECT statement twice. The first time, writefile() is called
5445 ** for all archive members that should be extracted. The second time,
5446 ** only for the directories. This is because the timestamps for
5447 ** extracted directories must be reset after they are populated (as
5448 ** populating them changes the timestamp). */
5449 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00005450 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5451 sqlite3_bind_int(pSql, j, i);
5452 if( pAr->bDryRun ){
5453 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5454 }else{
5455 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5456 if( i==0 && pAr->bVerbose ){
5457 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5458 }
danac15e2d2017-12-14 19:15:07 +00005459 }
5460 }
5461 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005462 }
danac15e2d2017-12-14 19:15:07 +00005463 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005464 }
dan25c12182017-12-07 21:03:33 +00005465
dan2ad09492017-12-09 18:28:22 +00005466 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00005467 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00005468 return rc;
5469}
5470
drhb376b3d2018-01-10 13:11:51 +00005471/*
5472** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5473*/
5474static int arExecSql(ArCommand *pAr, const char *zSql){
5475 int rc;
5476 if( pAr->bDryRun ){
5477 utf8_printf(pAr->p->out, "%s\n", zSql);
5478 rc = SQLITE_OK;
5479 }else{
drh410cad92018-01-10 17:19:16 +00005480 char *zErr = 0;
5481 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5482 if( zErr ){
5483 utf8_printf(stdout, "ERROR: %s\n", zErr);
5484 sqlite3_free(zErr);
5485 }
drhb376b3d2018-01-10 13:11:51 +00005486 }
5487 return rc;
5488}
5489
dan1ad3f612017-12-11 20:22:02 +00005490
danfd0245d2017-12-07 15:44:29 +00005491/*
dan06741a32017-12-13 20:17:18 +00005492** Implementation of .ar "create" and "update" commands.
danfd0245d2017-12-07 15:44:29 +00005493**
5494** Create the "sqlar" table in the database if it does not already exist.
5495** Then add each file in the azFile[] array to the archive. Directories
5496** are added recursively. If argument bVerbose is non-zero, a message is
5497** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00005498**
5499** The create command is the same as update, except that it drops
5500** any existing "sqlar" table before beginning.
danfd0245d2017-12-07 15:44:29 +00005501*/
drhb376b3d2018-01-10 13:11:51 +00005502static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00005503 ArCommand *pAr, /* Command arguments and options */
drhb376b3d2018-01-10 13:11:51 +00005504 int bUpdate /* true for a --create. false for --update */
danfd0245d2017-12-07 15:44:29 +00005505){
dand4b56e52017-12-12 20:04:59 +00005506 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00005507 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5508 " name TEXT PRIMARY KEY, -- name of the file\n"
5509 " mode INT, -- access permissions\n"
5510 " mtime INT, -- last modification time\n"
5511 " sz INT, -- original file size\n"
5512 " data BLOB -- compressed content\n"
5513 ")";
dand4b56e52017-12-12 20:04:59 +00005514 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh1bf208c2018-03-09 21:54:01 +00005515 const char *zInsertFmt[2] = {
5516 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
drh634c70f2018-01-10 16:50:18 +00005517 " SELECT\n"
5518 " %s,\n"
5519 " mode,\n"
5520 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00005521 " CASE substr(lsmode(mode),1,1)\n"
5522 " WHEN '-' THEN length(data)\n"
5523 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00005524 " ELSE -1 END,\n"
drh69d2d352018-03-09 22:18:53 +00005525 " sqlar_compress(data)\n"
drh634c70f2018-01-10 16:50:18 +00005526 " FROM fsdir(%Q,%Q)\n"
drh1bf208c2018-03-09 21:54:01 +00005527 " WHERE lsmode(mode) NOT LIKE '?%%';",
5528 "REPLACE INTO %s(name,mode,mtime,data)\n"
5529 " SELECT\n"
5530 " %s,\n"
5531 " mode,\n"
5532 " mtime,\n"
5533 " data\n"
5534 " FROM fsdir(%Q,%Q)\n"
5535 " WHERE lsmode(mode) NOT LIKE '?%%';"
5536 };
danfd0245d2017-12-07 15:44:29 +00005537 int i; /* For iterating through azFile[] */
5538 int rc; /* Return code */
drh1bf208c2018-03-09 21:54:01 +00005539 const char *zTab = 0; /* SQL table into which to insert */
5540 char *zSql;
5541 char zTemp[50];
danfd0245d2017-12-07 15:44:29 +00005542
drh1bf208c2018-03-09 21:54:01 +00005543 arExecSql(pAr, "PRAGMA page_size=512");
drhb376b3d2018-01-10 13:11:51 +00005544 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00005545 if( rc!=SQLITE_OK ) return rc;
drh1bf208c2018-03-09 21:54:01 +00005546 zTemp[0] = 0;
5547 if( pAr->bZip ){
5548 /* Initialize the zipfile virtual table, if necessary */
5549 if( pAr->zFile ){
5550 sqlite3_uint64 r;
5551 sqlite3_randomness(sizeof(r),&r);
5552 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5553 zTab = zTemp;
5554 zSql = sqlite3_mprintf(
5555 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5556 zTab, pAr->zFile
5557 );
5558 rc = arExecSql(pAr, zSql);
5559 sqlite3_free(zSql);
5560 }else{
5561 zTab = "zip";
5562 }
5563 }else{
5564 /* Initialize the table for an SQLAR */
5565 zTab = "sqlar";
5566 if( bUpdate==0 ){
5567 rc = arExecSql(pAr, zDrop);
5568 if( rc!=SQLITE_OK ) goto end_ar_transaction;
5569 }
5570 rc = arExecSql(pAr, zCreate);
dan06741a32017-12-13 20:17:18 +00005571 }
dan88be0202017-12-09 17:58:02 +00005572 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
mistachkince2052b2018-03-23 00:31:53 +00005573 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
drh634c70f2018-01-10 16:50:18 +00005574 pAr->bVerbose ? "shell_putsnl(name)" : "name",
5575 pAr->azArg[i], pAr->zDir);
mistachkince2052b2018-03-23 00:31:53 +00005576 rc = arExecSql(pAr, zSql2);
5577 sqlite3_free(zSql2);
danfd0245d2017-12-07 15:44:29 +00005578 }
drh1bf208c2018-03-09 21:54:01 +00005579end_ar_transaction:
danfd0245d2017-12-07 15:44:29 +00005580 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005581 arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
danfd0245d2017-12-07 15:44:29 +00005582 }else{
drhb376b3d2018-01-10 13:11:51 +00005583 rc = arExecSql(pAr, "RELEASE ar;");
drh1bf208c2018-03-09 21:54:01 +00005584 if( pAr->bZip && pAr->zFile ){
5585 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
5586 arExecSql(pAr, zSql);
5587 sqlite3_free(zSql);
5588 }
danfd0245d2017-12-07 15:44:29 +00005589 }
danfd0245d2017-12-07 15:44:29 +00005590 return rc;
5591}
5592
5593/*
5594** Implementation of ".ar" dot command.
5595*/
5596static int arDotCommand(
5597 ShellState *pState, /* Current shell tool state */
drhd0f9cdc2018-05-17 14:09:06 +00005598 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
danfd0245d2017-12-07 15:44:29 +00005599 char **azArg, /* Array of arguments passed to dot command */
5600 int nArg /* Number of entries in azArg[] */
5601){
dan88be0202017-12-09 17:58:02 +00005602 ArCommand cmd;
5603 int rc;
drh34660642018-01-10 17:39:54 +00005604 memset(&cmd, 0, sizeof(cmd));
drhd0f9cdc2018-05-17 14:09:06 +00005605 cmd.fromCmdLine = fromCmdLine;
dan88be0202017-12-09 17:58:02 +00005606 rc = arParseCommand(azArg, nArg, &cmd);
5607 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00005608 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00005609 cmd.p = pState;
5610 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00005611 if( cmd.zFile ){
drh1bf208c2018-03-09 21:54:01 +00005612 eDbType = deduceDatabaseType(cmd.zFile, 1);
drha5676c42018-01-10 15:17:34 +00005613 }else{
5614 eDbType = pState->openMode;
5615 }
5616 if( eDbType==SHELL_OPEN_ZIPFILE ){
drh1bf208c2018-03-09 21:54:01 +00005617 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
5618 if( cmd.zFile==0 ){
5619 cmd.zSrcTable = sqlite3_mprintf("zip");
5620 }else{
5621 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
5622 }
dan5a78b812017-12-27 18:54:11 +00005623 }
drha5676c42018-01-10 15:17:34 +00005624 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00005625 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00005626 int flags;
drha5676c42018-01-10 15:17:34 +00005627 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
dand4b56e52017-12-12 20:04:59 +00005628 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
5629 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
5630 }else{
5631 flags = SQLITE_OPEN_READONLY;
5632 }
drha82c95b2018-01-10 14:00:00 +00005633 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00005634 if( cmd.bDryRun ){
5635 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
5636 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
5637 }
5638 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
5639 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00005640 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005641 utf8_printf(stderr, "cannot open file: %s (%s)\n",
5642 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00005643 );
drha5676c42018-01-10 15:17:34 +00005644 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00005645 }
drhb376b3d2018-01-10 13:11:51 +00005646 sqlite3_fileio_init(cmd.db, 0, 0);
drhb376b3d2018-01-10 13:11:51 +00005647 sqlite3_sqlar_init(cmd.db, 0, 0);
drh34660642018-01-10 17:39:54 +00005648 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
5649 shellPutsFunc, 0, 0);
5650
dand4b56e52017-12-12 20:04:59 +00005651 }
drhd0f9cdc2018-05-17 14:09:06 +00005652 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
drh634c70f2018-01-10 16:50:18 +00005653 if( cmd.eCmd!=AR_CMD_CREATE
5654 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
5655 ){
drha5676c42018-01-10 15:17:34 +00005656 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
5657 rc = SQLITE_ERROR;
5658 goto end_ar_command;
5659 }
5660 cmd.zSrcTable = sqlite3_mprintf("sqlar");
5661 }
dand4b56e52017-12-12 20:04:59 +00005662
dan88be0202017-12-09 17:58:02 +00005663 switch( cmd.eCmd ){
5664 case AR_CMD_CREATE:
drhb376b3d2018-01-10 13:11:51 +00005665 rc = arCreateOrUpdateCommand(&cmd, 0);
dan88be0202017-12-09 17:58:02 +00005666 break;
danfd0245d2017-12-07 15:44:29 +00005667
dan88be0202017-12-09 17:58:02 +00005668 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00005669 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005670 break;
5671
5672 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00005673 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005674 break;
5675
dan0d0547f2017-12-14 15:40:42 +00005676 case AR_CMD_HELP:
5677 arUsage(pState->out);
5678 break;
5679
dan88be0202017-12-09 17:58:02 +00005680 default:
5681 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb376b3d2018-01-10 13:11:51 +00005682 rc = arCreateOrUpdateCommand(&cmd, 1);
dan88be0202017-12-09 17:58:02 +00005683 break;
danfd0245d2017-12-07 15:44:29 +00005684 }
5685 }
drha5676c42018-01-10 15:17:34 +00005686end_ar_command:
5687 if( cmd.db!=pState->db ){
drh9e804032018-05-18 17:11:50 +00005688 close_db(cmd.db);
drha5676c42018-01-10 15:17:34 +00005689 }
5690 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00005691
dan88be0202017-12-09 17:58:02 +00005692 return rc;
danfd0245d2017-12-07 15:44:29 +00005693}
drhe37c0e12018-01-06 19:19:50 +00005694/* End of the ".archive" or ".ar" command logic
5695**********************************************************************************/
5696#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00005697
drh2ce15c32017-07-11 13:34:40 +00005698
5699/*
5700** If an input line begins with "." then invoke this routine to
5701** process that line.
5702**
5703** Return 1 on error, 2 to exit, and 0 otherwise.
5704*/
5705static int do_meta_command(char *zLine, ShellState *p){
5706 int h = 1;
5707 int nArg = 0;
5708 int n, c;
5709 int rc = 0;
5710 char *azArg[50];
5711
dan6b046be2018-01-09 15:25:55 +00005712#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00005713 if( p->expert.pExpert ){
5714 expertFinish(p, 1, 0);
5715 }
dan6b046be2018-01-09 15:25:55 +00005716#endif
dan43efc182017-12-19 17:42:13 +00005717
drh2ce15c32017-07-11 13:34:40 +00005718 /* Parse the input line into tokens.
5719 */
5720 while( zLine[h] && nArg<ArraySize(azArg) ){
5721 while( IsSpace(zLine[h]) ){ h++; }
5722 if( zLine[h]==0 ) break;
5723 if( zLine[h]=='\'' || zLine[h]=='"' ){
5724 int delim = zLine[h++];
5725 azArg[nArg++] = &zLine[h];
5726 while( zLine[h] && zLine[h]!=delim ){
5727 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5728 h++;
5729 }
5730 if( zLine[h]==delim ){
5731 zLine[h++] = 0;
5732 }
5733 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5734 }else{
5735 azArg[nArg++] = &zLine[h];
5736 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5737 if( zLine[h] ) zLine[h++] = 0;
5738 resolve_backslashes(azArg[nArg-1]);
5739 }
5740 }
5741
5742 /* Process the input line.
5743 */
5744 if( nArg==0 ) return 0; /* no tokens, no error */
5745 n = strlen30(azArg[0]);
5746 c = azArg[0][0];
drh13c20932018-01-10 21:41:55 +00005747 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00005748
5749#ifndef SQLITE_OMIT_AUTHORIZATION
5750 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5751 if( nArg!=2 ){
5752 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5753 rc = 1;
5754 goto meta_command_exit;
5755 }
5756 open_db(p, 0);
5757 if( booleanValue(azArg[1]) ){
5758 sqlite3_set_authorizer(p->db, shellAuth, p);
5759 }else{
5760 sqlite3_set_authorizer(p->db, 0, 0);
5761 }
5762 }else
5763#endif
5764
drhe37c0e12018-01-06 19:19:50 +00005765#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5766 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00005767 open_db(p, 0);
drhd0f9cdc2018-05-17 14:09:06 +00005768 rc = arDotCommand(p, 0, azArg, nArg);
danfd0245d2017-12-07 15:44:29 +00005769 }else
5770#endif
5771
drh2ce15c32017-07-11 13:34:40 +00005772 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5773 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5774 ){
5775 const char *zDestFile = 0;
5776 const char *zDb = 0;
5777 sqlite3 *pDest;
5778 sqlite3_backup *pBackup;
5779 int j;
drh69ed38a2018-05-14 00:23:08 +00005780 const char *zVfs = 0;
drh2ce15c32017-07-11 13:34:40 +00005781 for(j=1; j<nArg; j++){
5782 const char *z = azArg[j];
5783 if( z[0]=='-' ){
drh69ed38a2018-05-14 00:23:08 +00005784 if( z[1]=='-' ) z++;
5785 if( strcmp(z, "-append")==0 ){
5786 zVfs = "apndvfs";
5787 }else
drh2ce15c32017-07-11 13:34:40 +00005788 {
5789 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
5790 return 1;
5791 }
5792 }else if( zDestFile==0 ){
5793 zDestFile = azArg[j];
5794 }else if( zDb==0 ){
5795 zDb = zDestFile;
5796 zDestFile = azArg[j];
5797 }else{
drh69ed38a2018-05-14 00:23:08 +00005798 raw_printf(stderr, "Usage: .backup ?DB? ?--append? FILENAME\n");
drh2ce15c32017-07-11 13:34:40 +00005799 return 1;
5800 }
5801 }
5802 if( zDestFile==0 ){
5803 raw_printf(stderr, "missing FILENAME argument on .backup\n");
5804 return 1;
5805 }
5806 if( zDb==0 ) zDb = "main";
drh69ed38a2018-05-14 00:23:08 +00005807 rc = sqlite3_open_v2(zDestFile, &pDest,
5808 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
drh2ce15c32017-07-11 13:34:40 +00005809 if( rc!=SQLITE_OK ){
5810 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9e804032018-05-18 17:11:50 +00005811 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00005812 return 1;
5813 }
5814 open_db(p, 0);
5815 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5816 if( pBackup==0 ){
5817 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9e804032018-05-18 17:11:50 +00005818 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00005819 return 1;
5820 }
5821 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5822 sqlite3_backup_finish(pBackup);
5823 if( rc==SQLITE_DONE ){
5824 rc = 0;
5825 }else{
5826 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5827 rc = 1;
5828 }
drh9e804032018-05-18 17:11:50 +00005829 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00005830 }else
5831
5832 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5833 if( nArg==2 ){
5834 bail_on_error = booleanValue(azArg[1]);
5835 }else{
5836 raw_printf(stderr, "Usage: .bail on|off\n");
5837 rc = 1;
5838 }
5839 }else
5840
5841 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5842 if( nArg==2 ){
5843 if( booleanValue(azArg[1]) ){
5844 setBinaryMode(p->out, 1);
5845 }else{
5846 setTextMode(p->out, 1);
5847 }
5848 }else{
5849 raw_printf(stderr, "Usage: .binary on|off\n");
5850 rc = 1;
5851 }
5852 }else
5853
5854 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5855 if( nArg==2 ){
5856#if defined(_WIN32) || defined(WIN32)
5857 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5858 rc = !SetCurrentDirectoryW(z);
5859 sqlite3_free(z);
5860#else
5861 rc = chdir(azArg[1]);
5862#endif
5863 if( rc ){
5864 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5865 rc = 1;
5866 }
5867 }else{
5868 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5869 rc = 1;
5870 }
5871 }else
5872
5873 /* The undocumented ".breakpoint" command causes a call to the no-op
5874 ** routine named test_breakpoint().
5875 */
5876 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5877 test_breakpoint();
5878 }else
5879
5880 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5881 if( nArg==2 ){
5882 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
5883 }else{
5884 raw_printf(stderr, "Usage: .changes on|off\n");
5885 rc = 1;
5886 }
5887 }else
5888
5889 /* Cancel output redirection, if it is currently set (by .testcase)
5890 ** Then read the content of the testcase-out.txt file and compare against
5891 ** azArg[1]. If there are differences, report an error and exit.
5892 */
5893 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5894 char *zRes = 0;
5895 output_reset(p);
5896 if( nArg!=2 ){
5897 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
5898 rc = 2;
5899 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
5900 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5901 rc = 2;
5902 }else if( testcase_glob(azArg[1],zRes)==0 ){
5903 utf8_printf(stderr,
5904 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5905 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00005906 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00005907 }else{
5908 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
5909 p->nCheck++;
5910 }
5911 sqlite3_free(zRes);
5912 }else
5913
5914 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5915 if( nArg==2 ){
5916 tryToClone(p, azArg[1]);
5917 }else{
5918 raw_printf(stderr, "Usage: .clone FILENAME\n");
5919 rc = 1;
5920 }
5921 }else
5922
5923 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
5924 ShellState data;
5925 char *zErrMsg = 0;
5926 open_db(p, 0);
5927 memcpy(&data, p, sizeof(data));
5928 data.showHeader = 0;
5929 data.cMode = data.mode = MODE_List;
5930 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
5931 data.cnt = 0;
5932 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5933 callback, &data, &zErrMsg);
5934 if( zErrMsg ){
5935 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5936 sqlite3_free(zErrMsg);
5937 rc = 1;
5938 }
5939 }else
5940
drh7df01192018-04-28 12:43:16 +00005941 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
drheb7f2a02018-09-26 18:02:32 +00005942 static const struct DbConfigChoices {
5943 const char *zName;
5944 int op;
5945 } aDbConfig[] = {
drh7df01192018-04-28 12:43:16 +00005946 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
5947 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
5948 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
5949 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
5950 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
5951 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
5952 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
5953 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
5954 };
5955 int ii, v;
5956 open_db(p, 0);
5957 for(ii=0; ii<ArraySize(aDbConfig); ii++){
5958 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
5959 if( nArg>=3 ){
5960 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
5961 }
5962 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
5963 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
5964 if( nArg>1 ) break;
5965 }
5966 if( nArg>1 && ii==ArraySize(aDbConfig) ){
5967 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
5968 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
5969 }
5970 }else
5971
5972 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00005973 rc = shell_dbinfo_command(p, nArg, azArg);
5974 }else
5975
5976 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
5977 const char *zLike = 0;
5978 int i;
5979 int savedShowHeader = p->showHeader;
drhf213b332018-07-05 17:35:46 +00005980 int savedShellFlags = p->shellFlgs;
5981 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
drh2ce15c32017-07-11 13:34:40 +00005982 for(i=1; i<nArg; i++){
5983 if( azArg[i][0]=='-' ){
5984 const char *z = azArg[i]+1;
5985 if( z[0]=='-' ) z++;
5986 if( strcmp(z,"preserve-rowids")==0 ){
5987#ifdef SQLITE_OMIT_VIRTUALTABLE
5988 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5989 " with SQLITE_OMIT_VIRTUALTABLE\n");
5990 rc = 1;
5991 goto meta_command_exit;
5992#else
5993 ShellSetFlag(p, SHFLG_PreserveRowid);
5994#endif
5995 }else
5996 if( strcmp(z,"newlines")==0 ){
5997 ShellSetFlag(p, SHFLG_Newlines);
5998 }else
5999 {
6000 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
6001 rc = 1;
6002 goto meta_command_exit;
6003 }
6004 }else if( zLike ){
6005 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
6006 "?--newlines? ?LIKE-PATTERN?\n");
6007 rc = 1;
6008 goto meta_command_exit;
6009 }else{
6010 zLike = azArg[i];
6011 }
6012 }
6013 open_db(p, 0);
6014 /* When playing back a "dump", the content might appear in an order
6015 ** which causes immediate foreign key constraints to be violated.
6016 ** So disable foreign-key constraint enforcement to prevent problems. */
6017 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
6018 raw_printf(p->out, "BEGIN TRANSACTION;\n");
6019 p->writableSchema = 0;
6020 p->showHeader = 0;
6021 /* Set writable_schema=ON since doing so forces SQLite to initialize
6022 ** as much of the schema as it can even if the sqlite_master table is
6023 ** corrupt. */
6024 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
6025 p->nErr = 0;
6026 if( zLike==0 ){
6027 run_schema_dump_query(p,
6028 "SELECT name, type, sql FROM sqlite_master "
6029 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
6030 );
6031 run_schema_dump_query(p,
6032 "SELECT name, type, sql FROM sqlite_master "
6033 "WHERE name=='sqlite_sequence'"
6034 );
6035 run_table_dump_query(p,
6036 "SELECT sql FROM sqlite_master "
6037 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
6038 );
6039 }else{
6040 char *zSql;
6041 zSql = sqlite3_mprintf(
6042 "SELECT name, type, sql FROM sqlite_master "
6043 "WHERE tbl_name LIKE %Q AND type=='table'"
6044 " AND sql NOT NULL", zLike);
6045 run_schema_dump_query(p,zSql);
6046 sqlite3_free(zSql);
6047 zSql = sqlite3_mprintf(
6048 "SELECT sql FROM sqlite_master "
6049 "WHERE sql NOT NULL"
6050 " AND type IN ('index','trigger','view')"
6051 " AND tbl_name LIKE %Q", zLike);
6052 run_table_dump_query(p, zSql, 0);
6053 sqlite3_free(zSql);
6054 }
6055 if( p->writableSchema ){
6056 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
6057 p->writableSchema = 0;
6058 }
6059 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6060 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
6061 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
6062 p->showHeader = savedShowHeader;
drhf213b332018-07-05 17:35:46 +00006063 p->shellFlgs = savedShellFlags;
drh2ce15c32017-07-11 13:34:40 +00006064 }else
6065
6066 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
6067 if( nArg==2 ){
6068 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
6069 }else{
6070 raw_printf(stderr, "Usage: .echo on|off\n");
6071 rc = 1;
6072 }
6073 }else
6074
6075 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
6076 if( nArg==2 ){
drhe2ca99c2018-05-02 00:33:43 +00006077 p->autoEQPtest = 0;
drh2ce15c32017-07-11 13:34:40 +00006078 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00006079 p->autoEQP = AUTOEQP_full;
6080 }else if( strcmp(azArg[1],"trigger")==0 ){
6081 p->autoEQP = AUTOEQP_trigger;
drhe2ca99c2018-05-02 00:33:43 +00006082 }else if( strcmp(azArg[1],"test")==0 ){
6083 p->autoEQP = AUTOEQP_on;
6084 p->autoEQPtest = 1;
drh2ce15c32017-07-11 13:34:40 +00006085 }else{
mistachkinb71aa092018-01-23 00:05:18 +00006086 p->autoEQP = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00006087 }
6088 }else{
drhada70452017-12-21 21:02:27 +00006089 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00006090 rc = 1;
6091 }
6092 }else
6093
6094 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
6095 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
6096 rc = 2;
6097 }else
6098
6099 /* The ".explain" command is automatic now. It is largely pointless. It
6100 ** retained purely for backwards compatibility */
6101 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
6102 int val = 1;
6103 if( nArg>=2 ){
6104 if( strcmp(azArg[1],"auto")==0 ){
6105 val = 99;
6106 }else{
6107 val = booleanValue(azArg[1]);
6108 }
6109 }
6110 if( val==1 && p->mode!=MODE_Explain ){
6111 p->normalMode = p->mode;
6112 p->mode = MODE_Explain;
6113 p->autoExplain = 0;
6114 }else if( val==0 ){
6115 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6116 p->autoExplain = 0;
6117 }else if( val==99 ){
6118 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6119 p->autoExplain = 1;
6120 }
6121 }else
6122
dan6b046be2018-01-09 15:25:55 +00006123#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006124 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
6125 open_db(p, 0);
6126 expertDotCommand(p, azArg, nArg);
6127 }else
dan6b046be2018-01-09 15:25:55 +00006128#endif
dan43efc182017-12-19 17:42:13 +00006129
drh2ce15c32017-07-11 13:34:40 +00006130 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
6131 ShellState data;
6132 char *zErrMsg = 0;
6133 int doStats = 0;
6134 memcpy(&data, p, sizeof(data));
6135 data.showHeader = 0;
6136 data.cMode = data.mode = MODE_Semi;
6137 if( nArg==2 && optionMatch(azArg[1], "indent") ){
6138 data.cMode = data.mode = MODE_Pretty;
6139 nArg = 1;
6140 }
6141 if( nArg!=1 ){
6142 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
6143 rc = 1;
6144 goto meta_command_exit;
6145 }
6146 open_db(p, 0);
6147 rc = sqlite3_exec(p->db,
6148 "SELECT sql FROM"
6149 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
6150 " FROM sqlite_master UNION ALL"
6151 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
6152 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
6153 "ORDER BY rowid",
6154 callback, &data, &zErrMsg
6155 );
6156 if( rc==SQLITE_OK ){
6157 sqlite3_stmt *pStmt;
6158 rc = sqlite3_prepare_v2(p->db,
6159 "SELECT rowid FROM sqlite_master"
6160 " WHERE name GLOB 'sqlite_stat[134]'",
6161 -1, &pStmt, 0);
6162 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
6163 sqlite3_finalize(pStmt);
6164 }
6165 if( doStats==0 ){
6166 raw_printf(p->out, "/* No STAT tables available */\n");
6167 }else{
6168 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6169 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
6170 callback, &data, &zErrMsg);
6171 data.cMode = data.mode = MODE_Insert;
6172 data.zDestTable = "sqlite_stat1";
drh4c540452018-05-08 23:17:36 +00006173 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006174 data.zDestTable = "sqlite_stat3";
drh4c540452018-05-08 23:17:36 +00006175 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006176 data.zDestTable = "sqlite_stat4";
drh4c540452018-05-08 23:17:36 +00006177 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006178 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6179 }
6180 }else
6181
6182 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
6183 if( nArg==2 ){
6184 p->showHeader = booleanValue(azArg[1]);
6185 }else{
6186 raw_printf(stderr, "Usage: .headers on|off\n");
6187 rc = 1;
6188 }
6189 }else
6190
6191 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
drh98aa2ab2018-09-26 16:53:51 +00006192 if( nArg>=2 ){
drhe93f8262018-10-11 16:53:37 +00006193 n = showHelp(p->out, azArg[1]);
drh98aa2ab2018-09-26 16:53:51 +00006194 if( n==0 ){
6195 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
6196 }
6197 }else{
6198 showHelp(p->out, 0);
6199 }
drh2ce15c32017-07-11 13:34:40 +00006200 }else
6201
6202 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
6203 char *zTable; /* Insert data into this table */
6204 char *zFile; /* Name of file to extra content from */
6205 sqlite3_stmt *pStmt = NULL; /* A statement */
6206 int nCol; /* Number of columns in the table */
6207 int nByte; /* Number of bytes in an SQL string */
6208 int i, j; /* Loop counters */
6209 int needCommit; /* True to COMMIT or ROLLBACK at end */
6210 int nSep; /* Number of bytes in p->colSeparator[] */
6211 char *zSql; /* An SQL statement */
6212 ImportCtx sCtx; /* Reader context */
6213 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
6214 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
6215
6216 if( nArg!=3 ){
6217 raw_printf(stderr, "Usage: .import FILE TABLE\n");
6218 goto meta_command_exit;
6219 }
6220 zFile = azArg[1];
6221 zTable = azArg[2];
6222 seenInterrupt = 0;
6223 memset(&sCtx, 0, sizeof(sCtx));
6224 open_db(p, 0);
6225 nSep = strlen30(p->colSeparator);
6226 if( nSep==0 ){
6227 raw_printf(stderr,
6228 "Error: non-null column separator required for import\n");
6229 return 1;
6230 }
6231 if( nSep>1 ){
6232 raw_printf(stderr, "Error: multi-character column separators not allowed"
6233 " for import\n");
6234 return 1;
6235 }
6236 nSep = strlen30(p->rowSeparator);
6237 if( nSep==0 ){
6238 raw_printf(stderr, "Error: non-null row separator required for import\n");
6239 return 1;
6240 }
6241 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
6242 /* When importing CSV (only), if the row separator is set to the
6243 ** default output row separator, change it to the default input
6244 ** row separator. This avoids having to maintain different input
6245 ** and output row separators. */
6246 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6247 nSep = strlen30(p->rowSeparator);
6248 }
6249 if( nSep>1 ){
6250 raw_printf(stderr, "Error: multi-character row separators not allowed"
6251 " for import\n");
6252 return 1;
6253 }
6254 sCtx.zFile = zFile;
6255 sCtx.nLine = 1;
6256 if( sCtx.zFile[0]=='|' ){
6257#ifdef SQLITE_OMIT_POPEN
6258 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6259 return 1;
6260#else
6261 sCtx.in = popen(sCtx.zFile+1, "r");
6262 sCtx.zFile = "<pipe>";
6263 xCloser = pclose;
6264#endif
6265 }else{
6266 sCtx.in = fopen(sCtx.zFile, "rb");
6267 xCloser = fclose;
6268 }
6269 if( p->mode==MODE_Ascii ){
6270 xRead = ascii_read_one_field;
6271 }else{
6272 xRead = csv_read_one_field;
6273 }
6274 if( sCtx.in==0 ){
6275 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
6276 return 1;
6277 }
6278 sCtx.cColSep = p->colSeparator[0];
6279 sCtx.cRowSep = p->rowSeparator[0];
6280 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
6281 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00006282 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00006283 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00006284 }
6285 nByte = strlen30(zSql);
6286 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6287 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
6288 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
6289 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
6290 char cSep = '(';
6291 while( xRead(&sCtx) ){
6292 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
6293 cSep = ',';
6294 if( sCtx.cTerm!=sCtx.cColSep ) break;
6295 }
6296 if( cSep=='(' ){
6297 sqlite3_free(zCreate);
6298 sqlite3_free(sCtx.z);
6299 xCloser(sCtx.in);
6300 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
6301 return 1;
6302 }
6303 zCreate = sqlite3_mprintf("%z\n)", zCreate);
6304 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
6305 sqlite3_free(zCreate);
6306 if( rc ){
6307 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
6308 sqlite3_errmsg(p->db));
6309 sqlite3_free(sCtx.z);
6310 xCloser(sCtx.in);
6311 return 1;
6312 }
6313 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6314 }
6315 sqlite3_free(zSql);
6316 if( rc ){
6317 if (pStmt) sqlite3_finalize(pStmt);
6318 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
6319 xCloser(sCtx.in);
6320 return 1;
6321 }
6322 nCol = sqlite3_column_count(pStmt);
6323 sqlite3_finalize(pStmt);
6324 pStmt = 0;
6325 if( nCol==0 ) return 0; /* no columns, no error */
6326 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
6327 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00006328 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00006329 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00006330 }
6331 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
6332 j = strlen30(zSql);
6333 for(i=1; i<nCol; i++){
6334 zSql[j++] = ',';
6335 zSql[j++] = '?';
6336 }
6337 zSql[j++] = ')';
6338 zSql[j] = 0;
6339 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6340 sqlite3_free(zSql);
6341 if( rc ){
6342 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6343 if (pStmt) sqlite3_finalize(pStmt);
6344 xCloser(sCtx.in);
6345 return 1;
6346 }
6347 needCommit = sqlite3_get_autocommit(p->db);
6348 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
6349 do{
6350 int startLine = sCtx.nLine;
6351 for(i=0; i<nCol; i++){
6352 char *z = xRead(&sCtx);
6353 /*
6354 ** Did we reach end-of-file before finding any columns?
6355 ** If so, stop instead of NULL filling the remaining columns.
6356 */
6357 if( z==0 && i==0 ) break;
6358 /*
6359 ** Did we reach end-of-file OR end-of-line before finding any
6360 ** columns in ASCII mode? If so, stop instead of NULL filling
6361 ** the remaining columns.
6362 */
6363 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
6364 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
6365 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
6366 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6367 "filling the rest with NULL\n",
6368 sCtx.zFile, startLine, nCol, i+1);
6369 i += 2;
6370 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
6371 }
6372 }
6373 if( sCtx.cTerm==sCtx.cColSep ){
6374 do{
6375 xRead(&sCtx);
6376 i++;
6377 }while( sCtx.cTerm==sCtx.cColSep );
6378 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6379 "extras ignored\n",
6380 sCtx.zFile, startLine, nCol, i);
6381 }
6382 if( i>=nCol ){
6383 sqlite3_step(pStmt);
6384 rc = sqlite3_reset(pStmt);
6385 if( rc!=SQLITE_OK ){
6386 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
6387 startLine, sqlite3_errmsg(p->db));
6388 }
6389 }
6390 }while( sCtx.cTerm!=EOF );
6391
6392 xCloser(sCtx.in);
6393 sqlite3_free(sCtx.z);
6394 sqlite3_finalize(pStmt);
6395 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
6396 }else
6397
6398#ifndef SQLITE_UNTESTABLE
6399 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
6400 char *zSql;
6401 char *zCollist = 0;
6402 sqlite3_stmt *pStmt;
6403 int tnum = 0;
6404 int i;
drh48d219a2018-04-23 18:38:48 +00006405 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
6406 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
6407 " .imposter off\n");
drh2ce15c32017-07-11 13:34:40 +00006408 rc = 1;
6409 goto meta_command_exit;
6410 }
6411 open_db(p, 0);
drh48d219a2018-04-23 18:38:48 +00006412 if( nArg==2 ){
6413 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
6414 goto meta_command_exit;
6415 }
drh2ce15c32017-07-11 13:34:40 +00006416 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6417 " WHERE name='%q' AND type='index'", azArg[1]);
6418 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6419 sqlite3_free(zSql);
6420 if( sqlite3_step(pStmt)==SQLITE_ROW ){
6421 tnum = sqlite3_column_int(pStmt, 0);
6422 }
6423 sqlite3_finalize(pStmt);
6424 if( tnum==0 ){
6425 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
6426 rc = 1;
6427 goto meta_command_exit;
6428 }
6429 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
6430 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6431 sqlite3_free(zSql);
6432 i = 0;
6433 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6434 char zLabel[20];
6435 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
6436 i++;
6437 if( zCol==0 ){
6438 if( sqlite3_column_int(pStmt,1)==-1 ){
6439 zCol = "_ROWID_";
6440 }else{
6441 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
6442 zCol = zLabel;
6443 }
6444 }
6445 if( zCollist==0 ){
6446 zCollist = sqlite3_mprintf("\"%w\"", zCol);
6447 }else{
6448 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
6449 }
6450 }
6451 sqlite3_finalize(pStmt);
6452 zSql = sqlite3_mprintf(
6453 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6454 azArg[2], zCollist, zCollist);
6455 sqlite3_free(zCollist);
6456 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
6457 if( rc==SQLITE_OK ){
6458 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
6459 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
6460 if( rc ){
6461 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
6462 }else{
6463 utf8_printf(stdout, "%s;\n", zSql);
6464 raw_printf(stdout,
6465 "WARNING: writing to an imposter table will corrupt the index!\n"
6466 );
6467 }
6468 }else{
6469 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
6470 rc = 1;
6471 }
6472 sqlite3_free(zSql);
6473 }else
6474#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6475
6476#ifdef SQLITE_ENABLE_IOTRACE
6477 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
6478 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
6479 if( iotrace && iotrace!=stdout ) fclose(iotrace);
6480 iotrace = 0;
6481 if( nArg<2 ){
6482 sqlite3IoTrace = 0;
6483 }else if( strcmp(azArg[1], "-")==0 ){
6484 sqlite3IoTrace = iotracePrintf;
6485 iotrace = stdout;
6486 }else{
6487 iotrace = fopen(azArg[1], "w");
6488 if( iotrace==0 ){
6489 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
6490 sqlite3IoTrace = 0;
6491 rc = 1;
6492 }else{
6493 sqlite3IoTrace = iotracePrintf;
6494 }
6495 }
6496 }else
6497#endif
6498
6499 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
6500 static const struct {
6501 const char *zLimitName; /* Name of a limit */
6502 int limitCode; /* Integer code for that limit */
6503 } aLimit[] = {
6504 { "length", SQLITE_LIMIT_LENGTH },
6505 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
6506 { "column", SQLITE_LIMIT_COLUMN },
6507 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
6508 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
6509 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
6510 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
6511 { "attached", SQLITE_LIMIT_ATTACHED },
6512 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
6513 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
6514 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
6515 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
6516 };
6517 int i, n2;
6518 open_db(p, 0);
6519 if( nArg==1 ){
6520 for(i=0; i<ArraySize(aLimit); i++){
6521 printf("%20s %d\n", aLimit[i].zLimitName,
6522 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
6523 }
6524 }else if( nArg>3 ){
6525 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
6526 rc = 1;
6527 goto meta_command_exit;
6528 }else{
6529 int iLimit = -1;
6530 n2 = strlen30(azArg[1]);
6531 for(i=0; i<ArraySize(aLimit); i++){
6532 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
6533 if( iLimit<0 ){
6534 iLimit = i;
6535 }else{
6536 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
6537 rc = 1;
6538 goto meta_command_exit;
6539 }
6540 }
6541 }
6542 if( iLimit<0 ){
6543 utf8_printf(stderr, "unknown limit: \"%s\"\n"
6544 "enter \".limits\" with no arguments for a list.\n",
6545 azArg[1]);
6546 rc = 1;
6547 goto meta_command_exit;
6548 }
6549 if( nArg==3 ){
6550 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
6551 (int)integerValue(azArg[2]));
6552 }
6553 printf("%20s %d\n", aLimit[iLimit].zLimitName,
6554 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
6555 }
6556 }else
6557
6558 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
6559 open_db(p, 0);
6560 lintDotCommand(p, azArg, nArg);
6561 }else
6562
6563#ifndef SQLITE_OMIT_LOAD_EXTENSION
6564 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
6565 const char *zFile, *zProc;
6566 char *zErrMsg = 0;
6567 if( nArg<2 ){
6568 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
6569 rc = 1;
6570 goto meta_command_exit;
6571 }
6572 zFile = azArg[1];
6573 zProc = nArg>=3 ? azArg[2] : 0;
6574 open_db(p, 0);
6575 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
6576 if( rc!=SQLITE_OK ){
6577 utf8_printf(stderr, "Error: %s\n", zErrMsg);
6578 sqlite3_free(zErrMsg);
6579 rc = 1;
6580 }
6581 }else
6582#endif
6583
6584 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
6585 if( nArg!=2 ){
6586 raw_printf(stderr, "Usage: .log FILENAME\n");
6587 rc = 1;
6588 }else{
6589 const char *zFile = azArg[1];
6590 output_file_close(p->pLog);
drha92a01a2018-01-10 22:15:37 +00006591 p->pLog = output_file_open(zFile, 0);
drh2ce15c32017-07-11 13:34:40 +00006592 }
6593 }else
6594
6595 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6596 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00006597 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00006598 int c2 = zMode[0];
6599 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
6600 p->mode = MODE_Line;
6601 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6602 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
6603 p->mode = MODE_Column;
6604 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6605 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
6606 p->mode = MODE_List;
6607 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6608 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6609 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
6610 p->mode = MODE_Html;
6611 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
6612 p->mode = MODE_Tcl;
6613 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
6614 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6615 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
6616 p->mode = MODE_Csv;
6617 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6618 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6619 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
6620 p->mode = MODE_List;
6621 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
6622 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
6623 p->mode = MODE_Insert;
6624 set_table_name(p, nArg>=3 ? azArg[2] : "table");
6625 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6626 p->mode = MODE_Quote;
6627 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6628 p->mode = MODE_Ascii;
6629 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6630 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
6631 }else if( nArg==1 ){
6632 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6633 }else{
6634 raw_printf(stderr, "Error: mode should be one of: "
6635 "ascii column csv html insert line list quote tabs tcl\n");
6636 rc = 1;
6637 }
6638 p->cMode = p->mode;
6639 }else
6640
6641 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6642 if( nArg==2 ){
6643 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6644 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
6645 }else{
6646 raw_printf(stderr, "Usage: .nullvalue STRING\n");
6647 rc = 1;
6648 }
6649 }else
6650
6651 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
6652 char *zNewFilename; /* Name of the database file to open */
6653 int iName = 1; /* Index in azArg[] of the filename */
6654 int newFlag = 0; /* True to delete file before opening */
6655 /* Close the existing database */
6656 session_close_all(p);
drh9e804032018-05-18 17:11:50 +00006657 close_db(p->db);
drh2ce15c32017-07-11 13:34:40 +00006658 p->db = 0;
6659 p->zDbFilename = 0;
6660 sqlite3_free(p->zFreeOnClose);
6661 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00006662 p->openMode = SHELL_OPEN_UNSPEC;
drh2ce15c32017-07-11 13:34:40 +00006663 /* Check for command-line arguments */
6664 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6665 const char *z = azArg[iName];
6666 if( optionMatch(z,"new") ){
6667 newFlag = 1;
drh3baed312018-03-08 18:14:41 +00006668#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00006669 }else if( optionMatch(z, "zip") ){
6670 p->openMode = SHELL_OPEN_ZIPFILE;
6671#endif
6672 }else if( optionMatch(z, "append") ){
6673 p->openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00006674 }else if( optionMatch(z, "readonly") ){
6675 p->openMode = SHELL_OPEN_READONLY;
drh60f34ae2018-10-30 13:19:49 +00006676 }else if( optionMatch(z, "deserialize") ){
6677 p->openMode = SHELL_OPEN_DESERIALIZE;
drh2ce15c32017-07-11 13:34:40 +00006678 }else if( z[0]=='-' ){
6679 utf8_printf(stderr, "unknown option: %s\n", z);
6680 rc = 1;
6681 goto meta_command_exit;
6682 }
6683 }
6684 /* If a filename is specified, try to open it first */
6685 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
6686 if( zNewFilename ){
6687 if( newFlag ) shellDeleteFile(zNewFilename);
6688 p->zDbFilename = zNewFilename;
drhbe4ccb22018-05-17 20:04:24 +00006689 open_db(p, OPEN_DB_KEEPALIVE);
drh2ce15c32017-07-11 13:34:40 +00006690 if( p->db==0 ){
6691 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6692 sqlite3_free(zNewFilename);
6693 }else{
6694 p->zFreeOnClose = zNewFilename;
6695 }
6696 }
6697 if( p->db==0 ){
6698 /* As a fall-back open a TEMP database */
6699 p->zDbFilename = 0;
6700 open_db(p, 0);
6701 }
6702 }else
6703
drh13c20932018-01-10 21:41:55 +00006704 if( (c=='o'
6705 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
6706 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
drh2ce15c32017-07-11 13:34:40 +00006707 ){
6708 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
drha92a01a2018-01-10 22:15:37 +00006709 int bTxtMode = 0;
drh13c20932018-01-10 21:41:55 +00006710 if( azArg[0][0]=='e' ){
6711 /* Transform the ".excel" command into ".once -x" */
6712 nArg = 2;
6713 azArg[0] = "once";
6714 zFile = azArg[1] = "-x";
6715 n = 4;
6716 }
drh2ce15c32017-07-11 13:34:40 +00006717 if( nArg>2 ){
drh13c20932018-01-10 21:41:55 +00006718 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00006719 rc = 1;
6720 goto meta_command_exit;
6721 }
6722 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6723 if( nArg<2 ){
drh13c20932018-01-10 21:41:55 +00006724 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
drh2ce15c32017-07-11 13:34:40 +00006725 rc = 1;
6726 goto meta_command_exit;
6727 }
6728 p->outCount = 2;
6729 }else{
6730 p->outCount = 0;
6731 }
6732 output_reset(p);
drh13c20932018-01-10 21:41:55 +00006733 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
drh04a28c32018-01-31 01:38:44 +00006734#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00006735 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
drh3c484e82018-01-10 22:27:21 +00006736 p->doXdgOpen = 1;
6737 outputModePush(p);
drh13c20932018-01-10 21:41:55 +00006738 if( zFile[1]=='x' ){
6739 newTempFile(p, "csv");
6740 p->mode = MODE_Csv;
6741 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6742 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6743 }else{
6744 newTempFile(p, "txt");
drha92a01a2018-01-10 22:15:37 +00006745 bTxtMode = 1;
drh13c20932018-01-10 21:41:55 +00006746 }
6747 zFile = p->zTempFile;
6748 }
drh04a28c32018-01-31 01:38:44 +00006749#endif /* SQLITE_NOHAVE_SYSTEM */
drh2ce15c32017-07-11 13:34:40 +00006750 if( zFile[0]=='|' ){
6751#ifdef SQLITE_OMIT_POPEN
6752 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6753 rc = 1;
6754 p->out = stdout;
6755#else
6756 p->out = popen(zFile + 1, "w");
6757 if( p->out==0 ){
6758 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
6759 p->out = stdout;
6760 rc = 1;
6761 }else{
6762 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6763 }
6764#endif
6765 }else{
drha92a01a2018-01-10 22:15:37 +00006766 p->out = output_file_open(zFile, bTxtMode);
drh2ce15c32017-07-11 13:34:40 +00006767 if( p->out==0 ){
6768 if( strcmp(zFile,"off")!=0 ){
6769 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
6770 }
6771 p->out = stdout;
6772 rc = 1;
6773 } else {
6774 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6775 }
6776 }
6777 }else
6778
6779 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6780 int i;
6781 for(i=1; i<nArg; i++){
6782 if( i>1 ) raw_printf(p->out, " ");
6783 utf8_printf(p->out, "%s", azArg[i]);
6784 }
6785 raw_printf(p->out, "\n");
6786 }else
6787
6788 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
6789 if( nArg >= 2) {
6790 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6791 }
6792 if( nArg >= 3) {
6793 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6794 }
6795 }else
6796
6797 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
6798 rc = 2;
6799 }else
6800
6801 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6802 FILE *alt;
6803 if( nArg!=2 ){
6804 raw_printf(stderr, "Usage: .read FILE\n");
6805 rc = 1;
6806 goto meta_command_exit;
6807 }
6808 alt = fopen(azArg[1], "rb");
6809 if( alt==0 ){
6810 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6811 rc = 1;
6812 }else{
6813 rc = process_input(p, alt);
6814 fclose(alt);
6815 }
6816 }else
6817
6818 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
6819 const char *zSrcFile;
6820 const char *zDb;
6821 sqlite3 *pSrc;
6822 sqlite3_backup *pBackup;
6823 int nTimeout = 0;
6824
6825 if( nArg==2 ){
6826 zSrcFile = azArg[1];
6827 zDb = "main";
6828 }else if( nArg==3 ){
6829 zSrcFile = azArg[2];
6830 zDb = azArg[1];
6831 }else{
6832 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
6833 rc = 1;
6834 goto meta_command_exit;
6835 }
6836 rc = sqlite3_open(zSrcFile, &pSrc);
6837 if( rc!=SQLITE_OK ){
6838 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9e804032018-05-18 17:11:50 +00006839 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00006840 return 1;
6841 }
6842 open_db(p, 0);
6843 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6844 if( pBackup==0 ){
6845 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9e804032018-05-18 17:11:50 +00006846 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00006847 return 1;
6848 }
6849 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6850 || rc==SQLITE_BUSY ){
6851 if( rc==SQLITE_BUSY ){
6852 if( nTimeout++ >= 3 ) break;
6853 sqlite3_sleep(100);
6854 }
6855 }
6856 sqlite3_backup_finish(pBackup);
6857 if( rc==SQLITE_DONE ){
6858 rc = 0;
6859 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
6860 raw_printf(stderr, "Error: source database is busy\n");
6861 rc = 1;
6862 }else{
6863 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6864 rc = 1;
6865 }
drh9e804032018-05-18 17:11:50 +00006866 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00006867 }else
6868
drh2ce15c32017-07-11 13:34:40 +00006869 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6870 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00006871 p->scanstatsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00006872#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6873 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
6874#endif
6875 }else{
6876 raw_printf(stderr, "Usage: .scanstats on|off\n");
6877 rc = 1;
6878 }
6879 }else
6880
6881 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
6882 ShellText sSelect;
6883 ShellState data;
6884 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00006885 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00006886 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00006887 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00006888 int bDebug = 0;
6889 int ii;
drh2ce15c32017-07-11 13:34:40 +00006890
6891 open_db(p, 0);
6892 memcpy(&data, p, sizeof(data));
6893 data.showHeader = 0;
6894 data.cMode = data.mode = MODE_Semi;
6895 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00006896 for(ii=1; ii<nArg; ii++){
6897 if( optionMatch(azArg[ii],"indent") ){
6898 data.cMode = data.mode = MODE_Pretty;
6899 }else if( optionMatch(azArg[ii],"debug") ){
6900 bDebug = 1;
6901 }else if( zName==0 ){
6902 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00006903 }else{
drhceba7922018-01-01 21:28:25 +00006904 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6905 rc = 1;
6906 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00006907 }
drh2ce15c32017-07-11 13:34:40 +00006908 }
drhceba7922018-01-01 21:28:25 +00006909 if( zName!=0 ){
mistachkin9d107262018-03-23 14:24:34 +00006910 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
6911 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
drh2ce15c32017-07-11 13:34:40 +00006912 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00006913 new_argv[0] = sqlite3_mprintf(
6914 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00006915 " type text,\n"
6916 " name text,\n"
6917 " tbl_name text,\n"
6918 " rootpage integer,\n"
6919 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00006920 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00006921 new_argv[1] = 0;
6922 new_colv[0] = "sql";
6923 new_colv[1] = 0;
6924 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00006925 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00006926 }
drh2ce15c32017-07-11 13:34:40 +00006927 }
6928 if( zDiv ){
6929 sqlite3_stmt *pStmt = 0;
6930 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6931 -1, &pStmt, 0);
6932 if( rc ){
6933 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6934 sqlite3_finalize(pStmt);
6935 rc = 1;
6936 goto meta_command_exit;
6937 }
6938 appendText(&sSelect, "SELECT sql FROM", 0);
6939 iSchema = 0;
6940 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6941 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6942 char zScNum[30];
6943 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6944 appendText(&sSelect, zDiv, 0);
6945 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00006946 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
6947 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00006948 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00006949 }else{
drhceba7922018-01-01 21:28:25 +00006950 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00006951 }
drhceba7922018-01-01 21:28:25 +00006952 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6953 appendText(&sSelect, zScNum, 0);
6954 appendText(&sSelect, " AS snum, ", 0);
6955 appendText(&sSelect, zDb, '\'');
6956 appendText(&sSelect, " AS sname FROM ", 0);
6957 appendText(&sSelect, zDb, '"');
6958 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00006959 }
6960 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00006961#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00006962 if( zName ){
6963 appendText(&sSelect,
6964 " UNION ALL SELECT shell_module_schema(name),"
6965 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6966 }
drhcde7b772018-01-02 12:50:40 +00006967#endif
drh2ce15c32017-07-11 13:34:40 +00006968 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00006969 if( zName ){
6970 char *zQarg = sqlite3_mprintf("%Q", zName);
mistachkin9d107262018-03-23 14:24:34 +00006971 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
6972 strchr(zName, '[') != 0;
drhceba7922018-01-01 21:28:25 +00006973 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00006974 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6975 }else{
6976 appendText(&sSelect, "lower(tbl_name)", 0);
6977 }
mistachkin9d107262018-03-23 14:24:34 +00006978 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00006979 appendText(&sSelect, zQarg, 0);
mistachkin9d107262018-03-23 14:24:34 +00006980 if( !bGlob ){
6981 appendText(&sSelect, " ESCAPE '\\' ", 0);
6982 }
drh2ce15c32017-07-11 13:34:40 +00006983 appendText(&sSelect, " AND ", 0);
6984 sqlite3_free(zQarg);
6985 }
6986 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6987 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00006988 if( bDebug ){
6989 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
6990 }else{
6991 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6992 }
drh2ce15c32017-07-11 13:34:40 +00006993 freeText(&sSelect);
6994 }
6995 if( zErrMsg ){
6996 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6997 sqlite3_free(zErrMsg);
6998 rc = 1;
6999 }else if( rc != SQLITE_OK ){
7000 raw_printf(stderr,"Error: querying schema information\n");
7001 rc = 1;
7002 }else{
7003 rc = 0;
7004 }
7005 }else
7006
7007#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
7008 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
7009 sqlite3SelectTrace = (int)integerValue(azArg[1]);
7010 }else
7011#endif
7012
7013#if defined(SQLITE_ENABLE_SESSION)
7014 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
7015 OpenSession *pSession = &p->aSession[0];
7016 char **azCmd = &azArg[1];
7017 int iSes = 0;
7018 int nCmd = nArg - 1;
7019 int i;
7020 if( nArg<=1 ) goto session_syntax_error;
7021 open_db(p, 0);
7022 if( nArg>=3 ){
7023 for(iSes=0; iSes<p->nSession; iSes++){
7024 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
7025 }
7026 if( iSes<p->nSession ){
7027 pSession = &p->aSession[iSes];
7028 azCmd++;
7029 nCmd--;
7030 }else{
7031 pSession = &p->aSession[0];
7032 iSes = 0;
7033 }
7034 }
7035
7036 /* .session attach TABLE
7037 ** Invoke the sqlite3session_attach() interface to attach a particular
7038 ** table so that it is never filtered.
7039 */
7040 if( strcmp(azCmd[0],"attach")==0 ){
7041 if( nCmd!=2 ) goto session_syntax_error;
7042 if( pSession->p==0 ){
7043 session_not_open:
7044 raw_printf(stderr, "ERROR: No sessions are open\n");
7045 }else{
7046 rc = sqlite3session_attach(pSession->p, azCmd[1]);
7047 if( rc ){
7048 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
7049 rc = 0;
7050 }
7051 }
7052 }else
7053
7054 /* .session changeset FILE
7055 ** .session patchset FILE
7056 ** Write a changeset or patchset into a file. The file is overwritten.
7057 */
7058 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
7059 FILE *out = 0;
7060 if( nCmd!=2 ) goto session_syntax_error;
7061 if( pSession->p==0 ) goto session_not_open;
7062 out = fopen(azCmd[1], "wb");
7063 if( out==0 ){
7064 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
7065 }else{
7066 int szChng;
7067 void *pChng;
7068 if( azCmd[0][0]=='c' ){
7069 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
7070 }else{
7071 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
7072 }
7073 if( rc ){
7074 printf("Error: error code %d\n", rc);
7075 rc = 0;
7076 }
7077 if( pChng
7078 && fwrite(pChng, szChng, 1, out)!=1 ){
7079 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
7080 szChng);
7081 }
7082 sqlite3_free(pChng);
7083 fclose(out);
7084 }
7085 }else
7086
7087 /* .session close
7088 ** Close the identified session
7089 */
7090 if( strcmp(azCmd[0], "close")==0 ){
7091 if( nCmd!=1 ) goto session_syntax_error;
7092 if( p->nSession ){
7093 session_close(pSession);
7094 p->aSession[iSes] = p->aSession[--p->nSession];
7095 }
7096 }else
7097
7098 /* .session enable ?BOOLEAN?
7099 ** Query or set the enable flag
7100 */
7101 if( strcmp(azCmd[0], "enable")==0 ){
7102 int ii;
7103 if( nCmd>2 ) goto session_syntax_error;
7104 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7105 if( p->nSession ){
7106 ii = sqlite3session_enable(pSession->p, ii);
7107 utf8_printf(p->out, "session %s enable flag = %d\n",
7108 pSession->zName, ii);
7109 }
7110 }else
7111
7112 /* .session filter GLOB ....
7113 ** Set a list of GLOB patterns of table names to be excluded.
7114 */
7115 if( strcmp(azCmd[0], "filter")==0 ){
7116 int ii, nByte;
7117 if( nCmd<2 ) goto session_syntax_error;
7118 if( p->nSession ){
7119 for(ii=0; ii<pSession->nFilter; ii++){
7120 sqlite3_free(pSession->azFilter[ii]);
7121 }
7122 sqlite3_free(pSession->azFilter);
7123 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
7124 pSession->azFilter = sqlite3_malloc( nByte );
7125 if( pSession->azFilter==0 ){
7126 raw_printf(stderr, "Error: out or memory\n");
7127 exit(1);
7128 }
7129 for(ii=1; ii<nCmd; ii++){
7130 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
7131 }
7132 pSession->nFilter = ii-1;
7133 }
7134 }else
7135
7136 /* .session indirect ?BOOLEAN?
7137 ** Query or set the indirect flag
7138 */
7139 if( strcmp(azCmd[0], "indirect")==0 ){
7140 int ii;
7141 if( nCmd>2 ) goto session_syntax_error;
7142 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7143 if( p->nSession ){
7144 ii = sqlite3session_indirect(pSession->p, ii);
7145 utf8_printf(p->out, "session %s indirect flag = %d\n",
7146 pSession->zName, ii);
7147 }
7148 }else
7149
7150 /* .session isempty
7151 ** Determine if the session is empty
7152 */
7153 if( strcmp(azCmd[0], "isempty")==0 ){
7154 int ii;
7155 if( nCmd!=1 ) goto session_syntax_error;
7156 if( p->nSession ){
7157 ii = sqlite3session_isempty(pSession->p);
7158 utf8_printf(p->out, "session %s isempty flag = %d\n",
7159 pSession->zName, ii);
7160 }
7161 }else
7162
7163 /* .session list
7164 ** List all currently open sessions
7165 */
7166 if( strcmp(azCmd[0],"list")==0 ){
7167 for(i=0; i<p->nSession; i++){
7168 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
7169 }
7170 }else
7171
7172 /* .session open DB NAME
7173 ** Open a new session called NAME on the attached database DB.
7174 ** DB is normally "main".
7175 */
7176 if( strcmp(azCmd[0],"open")==0 ){
7177 char *zName;
7178 if( nCmd!=3 ) goto session_syntax_error;
7179 zName = azCmd[2];
7180 if( zName[0]==0 ) goto session_syntax_error;
7181 for(i=0; i<p->nSession; i++){
7182 if( strcmp(p->aSession[i].zName,zName)==0 ){
7183 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
7184 goto meta_command_exit;
7185 }
7186 }
7187 if( p->nSession>=ArraySize(p->aSession) ){
7188 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
7189 goto meta_command_exit;
7190 }
7191 pSession = &p->aSession[p->nSession];
7192 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
7193 if( rc ){
7194 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
7195 rc = 0;
7196 goto meta_command_exit;
7197 }
7198 pSession->nFilter = 0;
7199 sqlite3session_table_filter(pSession->p, session_filter, pSession);
7200 p->nSession++;
7201 pSession->zName = sqlite3_mprintf("%s", zName);
7202 }else
7203 /* If no command name matches, show a syntax error */
7204 session_syntax_error:
drheb7f2a02018-09-26 18:02:32 +00007205 showHelp(p->out, "session");
drh2ce15c32017-07-11 13:34:40 +00007206 }else
7207#endif
7208
7209#ifdef SQLITE_DEBUG
7210 /* Undocumented commands for internal testing. Subject to change
7211 ** without notice. */
7212 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
7213 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
7214 int i, v;
7215 for(i=1; i<nArg; i++){
7216 v = booleanValue(azArg[i]);
7217 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
7218 }
7219 }
7220 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
7221 int i; sqlite3_int64 v;
7222 for(i=1; i<nArg; i++){
7223 char zBuf[200];
7224 v = integerValue(azArg[i]);
7225 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
7226 utf8_printf(p->out, "%s", zBuf);
7227 }
7228 }
7229 }else
7230#endif
7231
7232 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
7233 int bIsInit = 0; /* True to initialize the SELFTEST table */
7234 int bVerbose = 0; /* Verbose output */
7235 int bSelftestExists; /* True if SELFTEST already exists */
7236 int i, k; /* Loop counters */
7237 int nTest = 0; /* Number of tests runs */
7238 int nErr = 0; /* Number of errors seen */
7239 ShellText str; /* Answer for a query */
7240 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
7241
7242 open_db(p,0);
7243 for(i=1; i<nArg; i++){
7244 const char *z = azArg[i];
7245 if( z[0]=='-' && z[1]=='-' ) z++;
7246 if( strcmp(z,"-init")==0 ){
7247 bIsInit = 1;
7248 }else
7249 if( strcmp(z,"-v")==0 ){
7250 bVerbose++;
7251 }else
7252 {
7253 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7254 azArg[i], azArg[0]);
7255 raw_printf(stderr, "Should be one of: --init -v\n");
7256 rc = 1;
7257 goto meta_command_exit;
7258 }
7259 }
7260 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
7261 != SQLITE_OK ){
7262 bSelftestExists = 0;
7263 }else{
7264 bSelftestExists = 1;
7265 }
7266 if( bIsInit ){
7267 createSelftestTable(p);
7268 bSelftestExists = 1;
7269 }
7270 initText(&str);
7271 appendText(&str, "x", 0);
7272 for(k=bSelftestExists; k>=0; k--){
7273 if( k==1 ){
7274 rc = sqlite3_prepare_v2(p->db,
7275 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
7276 -1, &pStmt, 0);
7277 }else{
7278 rc = sqlite3_prepare_v2(p->db,
7279 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
7280 " (1,'run','PRAGMA integrity_check','ok')",
7281 -1, &pStmt, 0);
7282 }
7283 if( rc ){
7284 raw_printf(stderr, "Error querying the selftest table\n");
7285 rc = 1;
7286 sqlite3_finalize(pStmt);
7287 goto meta_command_exit;
7288 }
7289 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
7290 int tno = sqlite3_column_int(pStmt, 0);
7291 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
7292 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
7293 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
7294
7295 k = 0;
7296 if( bVerbose>0 ){
7297 char *zQuote = sqlite3_mprintf("%q", zSql);
7298 printf("%d: %s %s\n", tno, zOp, zSql);
7299 sqlite3_free(zQuote);
7300 }
7301 if( strcmp(zOp,"memo")==0 ){
7302 utf8_printf(p->out, "%s\n", zSql);
7303 }else
7304 if( strcmp(zOp,"run")==0 ){
7305 char *zErrMsg = 0;
7306 str.n = 0;
7307 str.z[0] = 0;
7308 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
7309 nTest++;
7310 if( bVerbose ){
7311 utf8_printf(p->out, "Result: %s\n", str.z);
7312 }
7313 if( rc || zErrMsg ){
7314 nErr++;
7315 rc = 1;
7316 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
7317 sqlite3_free(zErrMsg);
7318 }else if( strcmp(zAns,str.z)!=0 ){
7319 nErr++;
7320 rc = 1;
7321 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
7322 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
7323 }
7324 }else
7325 {
7326 utf8_printf(stderr,
7327 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
7328 rc = 1;
7329 break;
7330 }
7331 } /* End loop over rows of content from SELFTEST */
7332 sqlite3_finalize(pStmt);
7333 } /* End loop over k */
7334 freeText(&str);
7335 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
7336 }else
7337
7338 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
7339 if( nArg<2 || nArg>3 ){
7340 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
7341 rc = 1;
7342 }
7343 if( nArg>=2 ){
7344 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
7345 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
7346 }
7347 if( nArg>=3 ){
7348 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
7349 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
7350 }
7351 }else
7352
7353 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
7354 const char *zLike = 0; /* Which table to checksum. 0 means everything */
7355 int i; /* Loop counter */
7356 int bSchema = 0; /* Also hash the schema */
7357 int bSeparate = 0; /* Hash each table separately */
7358 int iSize = 224; /* Hash algorithm to use */
7359 int bDebug = 0; /* Only show the query that would have run */
7360 sqlite3_stmt *pStmt; /* For querying tables names */
7361 char *zSql; /* SQL to be run */
7362 char *zSep; /* Separator */
7363 ShellText sSql; /* Complete SQL for the query to run the hash */
7364 ShellText sQuery; /* Set of queries used to read all content */
7365 open_db(p, 0);
7366 for(i=1; i<nArg; i++){
7367 const char *z = azArg[i];
7368 if( z[0]=='-' ){
7369 z++;
7370 if( z[0]=='-' ) z++;
7371 if( strcmp(z,"schema")==0 ){
7372 bSchema = 1;
7373 }else
7374 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
7375 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
7376 ){
7377 iSize = atoi(&z[5]);
7378 }else
7379 if( strcmp(z,"debug")==0 ){
7380 bDebug = 1;
7381 }else
7382 {
7383 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7384 azArg[i], azArg[0]);
7385 raw_printf(stderr, "Should be one of: --schema"
drh003edba2018-05-11 15:10:43 +00007386 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
drh2ce15c32017-07-11 13:34:40 +00007387 rc = 1;
7388 goto meta_command_exit;
7389 }
7390 }else if( zLike ){
7391 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7392 rc = 1;
7393 goto meta_command_exit;
7394 }else{
7395 zLike = z;
7396 bSeparate = 1;
drhcedfecf2018-03-23 12:59:10 +00007397 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
drh2ce15c32017-07-11 13:34:40 +00007398 }
7399 }
7400 if( bSchema ){
7401 zSql = "SELECT lower(name) FROM sqlite_master"
7402 " WHERE type='table' AND coalesce(rootpage,0)>1"
7403 " UNION ALL SELECT 'sqlite_master'"
7404 " ORDER BY 1 collate nocase";
7405 }else{
7406 zSql = "SELECT lower(name) FROM sqlite_master"
7407 " WHERE type='table' AND coalesce(rootpage,0)>1"
7408 " AND name NOT LIKE 'sqlite_%'"
7409 " ORDER BY 1 collate nocase";
7410 }
7411 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7412 initText(&sQuery);
7413 initText(&sSql);
7414 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
7415 zSep = "VALUES(";
7416 while( SQLITE_ROW==sqlite3_step(pStmt) ){
7417 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
7418 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
7419 if( strncmp(zTab, "sqlite_",7)!=0 ){
7420 appendText(&sQuery,"SELECT * FROM ", 0);
7421 appendText(&sQuery,zTab,'"');
7422 appendText(&sQuery," NOT INDEXED;", 0);
7423 }else if( strcmp(zTab, "sqlite_master")==0 ){
7424 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7425 " ORDER BY name;", 0);
7426 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
7427 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
7428 " ORDER BY name;", 0);
7429 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
7430 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
7431 " ORDER BY tbl,idx;", 0);
7432 }else if( strcmp(zTab, "sqlite_stat3")==0
7433 || strcmp(zTab, "sqlite_stat4")==0 ){
7434 appendText(&sQuery, "SELECT * FROM ", 0);
7435 appendText(&sQuery, zTab, 0);
7436 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
7437 }
7438 appendText(&sSql, zSep, 0);
7439 appendText(&sSql, sQuery.z, '\'');
7440 sQuery.n = 0;
7441 appendText(&sSql, ",", 0);
7442 appendText(&sSql, zTab, '\'');
7443 zSep = "),(";
7444 }
7445 sqlite3_finalize(pStmt);
7446 if( bSeparate ){
7447 zSql = sqlite3_mprintf(
7448 "%s))"
7449 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7450 " FROM [sha3sum$query]",
7451 sSql.z, iSize);
7452 }else{
7453 zSql = sqlite3_mprintf(
7454 "%s))"
7455 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7456 " FROM [sha3sum$query]",
7457 sSql.z, iSize);
7458 }
7459 freeText(&sQuery);
7460 freeText(&sSql);
7461 if( bDebug ){
7462 utf8_printf(p->out, "%s\n", zSql);
7463 }else{
drha10b9992018-03-09 15:24:33 +00007464 shell_exec(p, zSql, 0);
drh2ce15c32017-07-11 13:34:40 +00007465 }
7466 sqlite3_free(zSql);
7467 }else
7468
drh04a28c32018-01-31 01:38:44 +00007469#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00007470 if( c=='s'
7471 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
7472 ){
7473 char *zCmd;
7474 int i, x;
7475 if( nArg<2 ){
7476 raw_printf(stderr, "Usage: .system COMMAND\n");
7477 rc = 1;
7478 goto meta_command_exit;
7479 }
7480 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
7481 for(i=2; i<nArg; i++){
7482 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
7483 zCmd, azArg[i]);
7484 }
7485 x = system(zCmd);
7486 sqlite3_free(zCmd);
7487 if( x ) raw_printf(stderr, "System command returns %d\n", x);
7488 }else
drh04a28c32018-01-31 01:38:44 +00007489#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00007490
7491 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00007492 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00007493 int i;
7494 if( nArg!=1 ){
7495 raw_printf(stderr, "Usage: .show\n");
7496 rc = 1;
7497 goto meta_command_exit;
7498 }
7499 utf8_printf(p->out, "%12.12s: %s\n","echo",
7500 azBool[ShellHasFlag(p, SHFLG_Echo)]);
7501 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
7502 utf8_printf(p->out, "%12.12s: %s\n","explain",
7503 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
7504 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
7505 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
7506 utf8_printf(p->out, "%12.12s: ", "nullvalue");
7507 output_c_string(p->out, p->nullValue);
7508 raw_printf(p->out, "\n");
7509 utf8_printf(p->out,"%12.12s: %s\n","output",
7510 strlen30(p->outfile) ? p->outfile : "stdout");
7511 utf8_printf(p->out,"%12.12s: ", "colseparator");
7512 output_c_string(p->out, p->colSeparator);
7513 raw_printf(p->out, "\n");
7514 utf8_printf(p->out,"%12.12s: ", "rowseparator");
7515 output_c_string(p->out, p->rowSeparator);
7516 raw_printf(p->out, "\n");
7517 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
7518 utf8_printf(p->out, "%12.12s: ", "width");
7519 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
7520 raw_printf(p->out, "%d ", p->colWidth[i]);
7521 }
7522 raw_printf(p->out, "\n");
7523 utf8_printf(p->out, "%12.12s: %s\n", "filename",
7524 p->zDbFilename ? p->zDbFilename : "");
7525 }else
7526
7527 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
7528 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00007529 p->statsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007530 }else if( nArg==1 ){
7531 display_stats(p->db, p, 0);
7532 }else{
7533 raw_printf(stderr, "Usage: .stats ?on|off?\n");
7534 rc = 1;
7535 }
7536 }else
7537
7538 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
7539 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
7540 || strncmp(azArg[0], "indexes", n)==0) )
7541 ){
7542 sqlite3_stmt *pStmt;
7543 char **azResult;
7544 int nRow, nAlloc;
7545 int ii;
7546 ShellText s;
7547 initText(&s);
7548 open_db(p, 0);
7549 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
drh9e804032018-05-18 17:11:50 +00007550 if( rc ){
7551 sqlite3_finalize(pStmt);
7552 return shellDatabaseError(p->db);
7553 }
drh2ce15c32017-07-11 13:34:40 +00007554
7555 if( nArg>2 && c=='i' ){
7556 /* It is an historical accident that the .indexes command shows an error
7557 ** when called with the wrong number of arguments whereas the .tables
7558 ** command does not. */
7559 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
7560 rc = 1;
drh9e804032018-05-18 17:11:50 +00007561 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00007562 goto meta_command_exit;
7563 }
7564 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
7565 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
7566 if( zDbName==0 ) continue;
7567 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
7568 if( sqlite3_stricmp(zDbName, "main")==0 ){
7569 appendText(&s, "SELECT name FROM ", 0);
7570 }else{
7571 appendText(&s, "SELECT ", 0);
7572 appendText(&s, zDbName, '\'');
7573 appendText(&s, "||'.'||name FROM ", 0);
7574 }
7575 appendText(&s, zDbName, '"');
7576 appendText(&s, ".sqlite_master ", 0);
7577 if( c=='t' ){
7578 appendText(&s," WHERE type IN ('table','view')"
7579 " AND name NOT LIKE 'sqlite_%'"
7580 " AND name LIKE ?1", 0);
7581 }else{
7582 appendText(&s," WHERE type='index'"
7583 " AND tbl_name LIKE ?1", 0);
7584 }
7585 }
7586 rc = sqlite3_finalize(pStmt);
7587 appendText(&s, " ORDER BY 1", 0);
7588 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
7589 freeText(&s);
7590 if( rc ) return shellDatabaseError(p->db);
7591
7592 /* Run the SQL statement prepared by the above block. Store the results
7593 ** as an array of nul-terminated strings in azResult[]. */
7594 nRow = nAlloc = 0;
7595 azResult = 0;
7596 if( nArg>1 ){
7597 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
7598 }else{
7599 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
7600 }
7601 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7602 if( nRow>=nAlloc ){
7603 char **azNew;
7604 int n2 = nAlloc*2 + 10;
7605 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh4b5345c2018-04-24 13:07:40 +00007606 if( azNew==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007607 nAlloc = n2;
7608 azResult = azNew;
7609 }
7610 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
drh4b5345c2018-04-24 13:07:40 +00007611 if( 0==azResult[nRow] ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007612 nRow++;
7613 }
7614 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
7615 rc = shellDatabaseError(p->db);
7616 }
7617
7618 /* Pretty-print the contents of array azResult[] to the output */
7619 if( rc==0 && nRow>0 ){
7620 int len, maxlen = 0;
7621 int i, j;
7622 int nPrintCol, nPrintRow;
7623 for(i=0; i<nRow; i++){
7624 len = strlen30(azResult[i]);
7625 if( len>maxlen ) maxlen = len;
7626 }
7627 nPrintCol = 80/(maxlen+2);
7628 if( nPrintCol<1 ) nPrintCol = 1;
7629 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
7630 for(i=0; i<nPrintRow; i++){
7631 for(j=i; j<nRow; j+=nPrintRow){
7632 char *zSp = j<nPrintRow ? "" : " ";
7633 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
7634 azResult[j] ? azResult[j]:"");
7635 }
7636 raw_printf(p->out, "\n");
7637 }
7638 }
7639
7640 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
7641 sqlite3_free(azResult);
7642 }else
7643
7644 /* Begin redirecting output to the file "testcase-out.txt" */
7645 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
7646 output_reset(p);
drha92a01a2018-01-10 22:15:37 +00007647 p->out = output_file_open("testcase-out.txt", 0);
drh2ce15c32017-07-11 13:34:40 +00007648 if( p->out==0 ){
7649 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
7650 }
7651 if( nArg>=2 ){
7652 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
7653 }else{
7654 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
7655 }
7656 }else
7657
7658#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00007659 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007660 static const struct {
7661 const char *zCtrlName; /* Name of a test-control option */
7662 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00007663 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00007664 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00007665 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
7666 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
7667 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7668 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7669 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
7670 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7671 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
drhef302e82017-11-15 19:14:08 +00007672 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
7673 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
7674 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00007675#ifdef YYCOVERAGE
7676 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
7677#endif
drhef302e82017-11-15 19:14:08 +00007678 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
7679 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
7680 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
7681 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
7682 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00007683 };
7684 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00007685 int iCtrl = -1;
7686 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7687 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00007688 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00007689 const char *zCmd = 0;
7690
drh2ce15c32017-07-11 13:34:40 +00007691 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00007692 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00007693
7694 /* The argument can optionally begin with "-" or "--" */
7695 if( zCmd[0]=='-' && zCmd[1] ){
7696 zCmd++;
7697 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7698 }
7699
7700 /* --help lists all test-controls */
7701 if( strcmp(zCmd,"help")==0 ){
7702 utf8_printf(p->out, "Available test-controls:\n");
7703 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00007704 utf8_printf(p->out, " .testctrl %s %s\n",
7705 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00007706 }
7707 rc = 1;
7708 goto meta_command_exit;
7709 }
drh2ce15c32017-07-11 13:34:40 +00007710
7711 /* convert testctrl text option to value. allow any unique prefix
7712 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00007713 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00007714 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00007715 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007716 if( testctrl<0 ){
7717 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00007718 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00007719 }else{
drh35f51a42017-11-15 17:07:22 +00007720 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
7721 "Use \".testctrl --help\" for help\n", zCmd);
7722 rc = 1;
7723 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00007724 }
7725 }
7726 }
drhef302e82017-11-15 19:14:08 +00007727 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00007728 utf8_printf(stderr,"Error: unknown test-control: %s\n"
7729 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00007730 }else{
7731 switch(testctrl){
7732
7733 /* sqlite3_test_control(int, db, int) */
7734 case SQLITE_TESTCTRL_OPTIMIZATIONS:
7735 case SQLITE_TESTCTRL_RESERVE:
7736 if( nArg==3 ){
7737 int opt = (int)strtol(azArg[2], 0, 0);
7738 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00007739 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007740 }
7741 break;
7742
7743 /* sqlite3_test_control(int) */
7744 case SQLITE_TESTCTRL_PRNG_SAVE:
7745 case SQLITE_TESTCTRL_PRNG_RESTORE:
7746 case SQLITE_TESTCTRL_PRNG_RESET:
7747 case SQLITE_TESTCTRL_BYTEORDER:
7748 if( nArg==2 ){
7749 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00007750 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00007751 }
7752 break;
7753
7754 /* sqlite3_test_control(int, uint) */
7755 case SQLITE_TESTCTRL_PENDING_BYTE:
7756 if( nArg==3 ){
7757 unsigned int opt = (unsigned int)integerValue(azArg[2]);
7758 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007759 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007760 }
7761 break;
7762
7763 /* sqlite3_test_control(int, int) */
7764 case SQLITE_TESTCTRL_ASSERT:
7765 case SQLITE_TESTCTRL_ALWAYS:
drhef302e82017-11-15 19:14:08 +00007766 if( nArg==3 ){
7767 int opt = booleanValue(azArg[2]);
7768 rc2 = sqlite3_test_control(testctrl, opt);
7769 isOk = 1;
7770 }
7771 break;
7772
7773 /* sqlite3_test_control(int, int) */
7774 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00007775 case SQLITE_TESTCTRL_NEVER_CORRUPT:
7776 if( nArg==3 ){
7777 int opt = booleanValue(azArg[2]);
7778 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007779 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007780 }
7781 break;
7782
drh2ce15c32017-07-11 13:34:40 +00007783 case SQLITE_TESTCTRL_IMPOSTER:
7784 if( nArg==5 ){
7785 rc2 = sqlite3_test_control(testctrl, p->db,
7786 azArg[2],
7787 integerValue(azArg[3]),
7788 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00007789 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007790 }
7791 break;
drh0d9de992017-12-26 18:04:23 +00007792
7793#ifdef YYCOVERAGE
7794 case SQLITE_TESTCTRL_PARSER_COVERAGE:
7795 if( nArg==2 ){
7796 sqlite3_test_control(testctrl, p->out);
7797 isOk = 3;
7798 }
7799#endif
drh2ce15c32017-07-11 13:34:40 +00007800 }
7801 }
drhef302e82017-11-15 19:14:08 +00007802 if( isOk==0 && iCtrl>=0 ){
7803 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
7804 rc = 1;
7805 }else if( isOk==1 ){
7806 raw_printf(p->out, "%d\n", rc2);
7807 }else if( isOk==2 ){
7808 raw_printf(p->out, "0x%08x\n", rc2);
7809 }
drh2ce15c32017-07-11 13:34:40 +00007810 }else
7811#endif /* !defined(SQLITE_UNTESTABLE) */
7812
7813 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
7814 open_db(p, 0);
7815 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
7816 }else
7817
7818 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7819 if( nArg==2 ){
7820 enableTimer = booleanValue(azArg[1]);
7821 if( enableTimer && !HAS_TIMER ){
7822 raw_printf(stderr, "Error: timer not available on this system.\n");
7823 enableTimer = 0;
7824 }
7825 }else{
7826 raw_printf(stderr, "Usage: .timer on|off\n");
7827 rc = 1;
7828 }
7829 }else
7830
7831 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
7832 open_db(p, 0);
7833 if( nArg!=2 ){
7834 raw_printf(stderr, "Usage: .trace FILE|off\n");
7835 rc = 1;
7836 goto meta_command_exit;
7837 }
7838 output_file_close(p->traceOut);
drha92a01a2018-01-10 22:15:37 +00007839 p->traceOut = output_file_open(azArg[1], 0);
drh2ce15c32017-07-11 13:34:40 +00007840#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7841 if( p->traceOut==0 ){
7842 sqlite3_trace_v2(p->db, 0, 0, 0);
7843 }else{
7844 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
7845 }
7846#endif
7847 }else
7848
7849#if SQLITE_USER_AUTHENTICATION
7850 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7851 if( nArg<2 ){
7852 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
7853 rc = 1;
7854 goto meta_command_exit;
7855 }
7856 open_db(p, 0);
7857 if( strcmp(azArg[1],"login")==0 ){
7858 if( nArg!=4 ){
7859 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
7860 rc = 1;
7861 goto meta_command_exit;
7862 }
drhaf2770f2018-01-05 14:55:43 +00007863 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00007864 if( rc ){
7865 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
7866 rc = 1;
7867 }
7868 }else if( strcmp(azArg[1],"add")==0 ){
7869 if( nArg!=5 ){
7870 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
7871 rc = 1;
7872 goto meta_command_exit;
7873 }
drhaf2770f2018-01-05 14:55:43 +00007874 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007875 booleanValue(azArg[4]));
7876 if( rc ){
7877 raw_printf(stderr, "User-Add failed: %d\n", rc);
7878 rc = 1;
7879 }
7880 }else if( strcmp(azArg[1],"edit")==0 ){
7881 if( nArg!=5 ){
7882 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
7883 rc = 1;
7884 goto meta_command_exit;
7885 }
drhaf2770f2018-01-05 14:55:43 +00007886 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007887 booleanValue(azArg[4]));
7888 if( rc ){
7889 raw_printf(stderr, "User-Edit failed: %d\n", rc);
7890 rc = 1;
7891 }
7892 }else if( strcmp(azArg[1],"delete")==0 ){
7893 if( nArg!=3 ){
7894 raw_printf(stderr, "Usage: .user delete USER\n");
7895 rc = 1;
7896 goto meta_command_exit;
7897 }
7898 rc = sqlite3_user_delete(p->db, azArg[2]);
7899 if( rc ){
7900 raw_printf(stderr, "User-Delete failed: %d\n", rc);
7901 rc = 1;
7902 }
7903 }else{
7904 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
7905 rc = 1;
7906 goto meta_command_exit;
7907 }
7908 }else
7909#endif /* SQLITE_USER_AUTHENTICATION */
7910
7911 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
7912 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
7913 sqlite3_libversion(), sqlite3_sourceid());
drh0ed2fd82018-01-16 20:05:27 +00007914#if SQLITE_HAVE_ZLIB
7915 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
7916#endif
7917#define CTIMEOPT_VAL_(opt) #opt
7918#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
7919#if defined(__clang__) && defined(__clang_major__)
7920 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
7921 CTIMEOPT_VAL(__clang_minor__) "."
7922 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
7923#elif defined(_MSC_VER)
7924 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
7925#elif defined(__GNUC__) && defined(__VERSION__)
7926 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
7927#endif
drh2ce15c32017-07-11 13:34:40 +00007928 }else
7929
7930 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7931 const char *zDbName = nArg==2 ? azArg[1] : "main";
7932 sqlite3_vfs *pVfs = 0;
7933 if( p->db ){
7934 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7935 if( pVfs ){
7936 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7937 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7938 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7939 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7940 }
7941 }
7942 }else
7943
7944 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7945 sqlite3_vfs *pVfs;
7946 sqlite3_vfs *pCurrent = 0;
7947 if( p->db ){
7948 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7949 }
7950 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7951 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7952 pVfs==pCurrent ? " <--- CURRENT" : "");
7953 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7954 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7955 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7956 if( pVfs->pNext ){
7957 raw_printf(p->out, "-----------------------------------\n");
7958 }
7959 }
7960 }else
7961
7962 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7963 const char *zDbName = nArg==2 ? azArg[1] : "main";
7964 char *zVfsName = 0;
7965 if( p->db ){
7966 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7967 if( zVfsName ){
7968 utf8_printf(p->out, "%s\n", zVfsName);
7969 sqlite3_free(zVfsName);
7970 }
7971 }
7972 }else
7973
7974#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7975 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
7976 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
7977 }else
7978#endif
7979
7980 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
7981 int j;
7982 assert( nArg<=ArraySize(azArg) );
7983 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
7984 p->colWidth[j-1] = (int)integerValue(azArg[j]);
7985 }
7986 }else
7987
7988 {
7989 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
7990 " \"%s\". Enter \".help\" for help\n", azArg[0]);
7991 rc = 1;
7992 }
7993
7994meta_command_exit:
7995 if( p->outCount ){
7996 p->outCount--;
7997 if( p->outCount==0 ) output_reset(p);
7998 }
7999 return rc;
8000}
8001
8002/*
8003** Return TRUE if a semicolon occurs anywhere in the first N characters
8004** of string z[].
8005*/
8006static int line_contains_semicolon(const char *z, int N){
8007 int i;
8008 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
8009 return 0;
8010}
8011
8012/*
8013** Test to see if a line consists entirely of whitespace.
8014*/
8015static int _all_whitespace(const char *z){
8016 for(; *z; z++){
8017 if( IsSpace(z[0]) ) continue;
8018 if( *z=='/' && z[1]=='*' ){
8019 z += 2;
8020 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
8021 if( *z==0 ) return 0;
8022 z++;
8023 continue;
8024 }
8025 if( *z=='-' && z[1]=='-' ){
8026 z += 2;
8027 while( *z && *z!='\n' ){ z++; }
8028 if( *z==0 ) return 1;
8029 continue;
8030 }
8031 return 0;
8032 }
8033 return 1;
8034}
8035
8036/*
8037** Return TRUE if the line typed in is an SQL command terminator other
8038** than a semi-colon. The SQL Server style "go" command is understood
8039** as is the Oracle "/".
8040*/
8041static int line_is_command_terminator(const char *zLine){
8042 while( IsSpace(zLine[0]) ){ zLine++; };
8043 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
8044 return 1; /* Oracle */
8045 }
8046 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
8047 && _all_whitespace(&zLine[2]) ){
8048 return 1; /* SQL Server */
8049 }
8050 return 0;
8051}
8052
8053/*
drh56f17742018-01-24 01:58:49 +00008054** We need a default sqlite3_complete() implementation to use in case
8055** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
8056** any arbitrary text is a complete SQL statement. This is not very
8057** user-friendly, but it does seem to work.
8058*/
8059#ifdef SQLITE_OMIT_COMPLETE
8060int sqlite3_complete(const char *zSql){ return 1; }
8061#endif
8062
8063/*
drh2ce15c32017-07-11 13:34:40 +00008064** Return true if zSql is a complete SQL statement. Return false if it
8065** ends in the middle of a string literal or C-style comment.
8066*/
8067static int line_is_complete(char *zSql, int nSql){
8068 int rc;
8069 if( zSql==0 ) return 1;
8070 zSql[nSql] = ';';
8071 zSql[nSql+1] = 0;
8072 rc = sqlite3_complete(zSql);
8073 zSql[nSql] = 0;
8074 return rc;
8075}
8076
8077/*
drhfc29a862018-05-11 19:11:18 +00008078** Run a single line of SQL. Return the number of errors.
drh2ce15c32017-07-11 13:34:40 +00008079*/
8080static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
8081 int rc;
8082 char *zErrMsg = 0;
8083
8084 open_db(p, 0);
8085 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
8086 BEGIN_TIMER;
drha10b9992018-03-09 15:24:33 +00008087 rc = shell_exec(p, zSql, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008088 END_TIMER;
8089 if( rc || zErrMsg ){
8090 char zPrefix[100];
8091 if( in!=0 || !stdin_is_interactive ){
8092 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
8093 "Error: near line %d:", startline);
8094 }else{
8095 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
8096 }
8097 if( zErrMsg!=0 ){
8098 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
8099 sqlite3_free(zErrMsg);
8100 zErrMsg = 0;
8101 }else{
8102 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
8103 }
8104 return 1;
8105 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
8106 raw_printf(p->out, "changes: %3d total_changes: %d\n",
8107 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
8108 }
8109 return 0;
8110}
8111
8112
8113/*
8114** Read input from *in and process it. If *in==0 then input
8115** is interactive - the user is typing it it. Otherwise, input
8116** is coming from a file or device. A prompt is issued and history
8117** is saved only if input is interactive. An interrupt signal will
8118** cause this routine to exit immediately, unless input is interactive.
8119**
8120** Return the number of errors.
8121*/
8122static int process_input(ShellState *p, FILE *in){
8123 char *zLine = 0; /* A single input line */
8124 char *zSql = 0; /* Accumulated SQL text */
8125 int nLine; /* Length of current line */
8126 int nSql = 0; /* Bytes of zSql[] used */
8127 int nAlloc = 0; /* Allocated zSql[] space */
8128 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
8129 int rc; /* Error code */
8130 int errCnt = 0; /* Number of errors seen */
8131 int lineno = 0; /* Current line number */
8132 int startline = 0; /* Line number for start of current input */
8133
8134 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
8135 fflush(p->out);
8136 zLine = one_input_line(in, zLine, nSql>0);
8137 if( zLine==0 ){
8138 /* End of input */
8139 if( in==0 && stdin_is_interactive ) printf("\n");
8140 break;
8141 }
8142 if( seenInterrupt ){
8143 if( in!=0 ) break;
8144 seenInterrupt = 0;
8145 }
8146 lineno++;
8147 if( nSql==0 && _all_whitespace(zLine) ){
8148 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
8149 continue;
8150 }
drh1615c372018-05-12 23:56:22 +00008151 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00008152 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh1615c372018-05-12 23:56:22 +00008153 if( zLine[0]=='.' ){
8154 rc = do_meta_command(zLine, p);
8155 if( rc==2 ){ /* exit requested */
8156 break;
8157 }else if( rc ){
8158 errCnt++;
8159 }
drh2ce15c32017-07-11 13:34:40 +00008160 }
8161 continue;
8162 }
8163 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
8164 memcpy(zLine,";",2);
8165 }
8166 nLine = strlen30(zLine);
8167 if( nSql+nLine+2>=nAlloc ){
8168 nAlloc = nSql+nLine+100;
8169 zSql = realloc(zSql, nAlloc);
drh4b5345c2018-04-24 13:07:40 +00008170 if( zSql==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008171 }
8172 nSqlPrior = nSql;
8173 if( nSql==0 ){
8174 int i;
8175 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
8176 assert( nAlloc>0 && zSql!=0 );
8177 memcpy(zSql, zLine+i, nLine+1-i);
8178 startline = lineno;
8179 nSql = nLine-i;
8180 }else{
8181 zSql[nSql++] = '\n';
8182 memcpy(zSql+nSql, zLine, nLine+1);
8183 nSql += nLine;
8184 }
8185 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
8186 && sqlite3_complete(zSql) ){
8187 errCnt += runOneSqlLine(p, zSql, in, startline);
8188 nSql = 0;
8189 if( p->outCount ){
8190 output_reset(p);
8191 p->outCount = 0;
drh13c20932018-01-10 21:41:55 +00008192 }else{
8193 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00008194 }
8195 }else if( nSql && _all_whitespace(zSql) ){
8196 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
8197 nSql = 0;
8198 }
8199 }
8200 if( nSql && !_all_whitespace(zSql) ){
drhfc29a862018-05-11 19:11:18 +00008201 errCnt += runOneSqlLine(p, zSql, in, startline);
drh2ce15c32017-07-11 13:34:40 +00008202 }
8203 free(zSql);
8204 free(zLine);
8205 return errCnt>0;
8206}
8207
8208/*
8209** Return a pathname which is the user's home directory. A
8210** 0 return indicates an error of some kind.
8211*/
8212static char *find_home_dir(int clearFlag){
8213 static char *home_dir = NULL;
8214 if( clearFlag ){
8215 free(home_dir);
8216 home_dir = 0;
8217 return 0;
8218 }
8219 if( home_dir ) return home_dir;
8220
8221#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
8222 && !defined(__RTP__) && !defined(_WRS_KERNEL)
8223 {
8224 struct passwd *pwent;
8225 uid_t uid = getuid();
8226 if( (pwent=getpwuid(uid)) != NULL) {
8227 home_dir = pwent->pw_dir;
8228 }
8229 }
8230#endif
8231
8232#if defined(_WIN32_WCE)
8233 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
8234 */
8235 home_dir = "/";
8236#else
8237
8238#if defined(_WIN32) || defined(WIN32)
8239 if (!home_dir) {
8240 home_dir = getenv("USERPROFILE");
8241 }
8242#endif
8243
8244 if (!home_dir) {
8245 home_dir = getenv("HOME");
8246 }
8247
8248#if defined(_WIN32) || defined(WIN32)
8249 if (!home_dir) {
8250 char *zDrive, *zPath;
8251 int n;
8252 zDrive = getenv("HOMEDRIVE");
8253 zPath = getenv("HOMEPATH");
8254 if( zDrive && zPath ){
8255 n = strlen30(zDrive) + strlen30(zPath) + 1;
8256 home_dir = malloc( n );
8257 if( home_dir==0 ) return 0;
8258 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
8259 return home_dir;
8260 }
8261 home_dir = "c:\\";
8262 }
8263#endif
8264
8265#endif /* !_WIN32_WCE */
8266
8267 if( home_dir ){
8268 int n = strlen30(home_dir) + 1;
8269 char *z = malloc( n );
8270 if( z ) memcpy(z, home_dir, n);
8271 home_dir = z;
8272 }
8273
8274 return home_dir;
8275}
8276
8277/*
8278** Read input from the file given by sqliterc_override. Or if that
8279** parameter is NULL, take input from ~/.sqliterc
8280**
8281** Returns the number of errors.
8282*/
8283static void process_sqliterc(
8284 ShellState *p, /* Configuration data */
8285 const char *sqliterc_override /* Name of config file. NULL to use default */
8286){
8287 char *home_dir = NULL;
8288 const char *sqliterc = sqliterc_override;
8289 char *zBuf = 0;
8290 FILE *in = NULL;
8291
8292 if (sqliterc == NULL) {
8293 home_dir = find_home_dir(0);
8294 if( home_dir==0 ){
8295 raw_printf(stderr, "-- warning: cannot find home directory;"
8296 " cannot read ~/.sqliterc\n");
8297 return;
8298 }
drh2ce15c32017-07-11 13:34:40 +00008299 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
8300 sqliterc = zBuf;
8301 }
8302 in = fopen(sqliterc,"rb");
8303 if( in ){
8304 if( stdin_is_interactive ){
8305 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
8306 }
8307 process_input(p,in);
8308 fclose(in);
8309 }
8310 sqlite3_free(zBuf);
8311}
8312
8313/*
8314** Show available command line options
8315*/
8316static const char zOptions[] =
drhda57d962018-03-05 19:34:05 +00008317#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhad7fd5d2018-03-05 20:21:50 +00008318 " -A ARGS... run \".archive ARGS\" and exit\n"
drhda57d962018-03-05 19:34:05 +00008319#endif
drh3baed312018-03-08 18:14:41 +00008320 " -append append the database to the end of the file\n"
drh2ce15c32017-07-11 13:34:40 +00008321 " -ascii set output mode to 'ascii'\n"
8322 " -bail stop after hitting an error\n"
8323 " -batch force batch I/O\n"
8324 " -column set output mode to 'column'\n"
8325 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
8326 " -csv set output mode to 'csv'\n"
8327 " -echo print commands before execution\n"
8328 " -init FILENAME read/process named file\n"
8329 " -[no]header turn headers on or off\n"
8330#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8331 " -heap SIZE Size of heap for memsys3 or memsys5\n"
8332#endif
8333 " -help show this message\n"
8334 " -html set output mode to HTML\n"
8335 " -interactive force interactive I/O\n"
8336 " -line set output mode to 'line'\n"
8337 " -list set output mode to 'list'\n"
8338 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
8339 " -mmap N default mmap size set to N\n"
8340#ifdef SQLITE_ENABLE_MULTIPLEX
8341 " -multiplex enable the multiplexor VFS\n"
8342#endif
8343 " -newline SEP set output row separator. Default: '\\n'\n"
8344 " -nullvalue TEXT set text string for NULL values. Default ''\n"
8345 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
8346 " -quote set output mode to 'quote'\n"
drhee269a62018-02-14 23:27:43 +00008347 " -readonly open the database read-only\n"
drh2ce15c32017-07-11 13:34:40 +00008348 " -separator SEP set output column separator. Default: '|'\n"
drha90d84f2018-04-18 15:21:13 +00008349#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8350 " -sorterref SIZE sorter references threshold size\n"
8351#endif
drh2ce15c32017-07-11 13:34:40 +00008352 " -stats print memory stats before each finalize\n"
8353 " -version show SQLite version\n"
8354 " -vfs NAME use NAME as the default VFS\n"
8355#ifdef SQLITE_ENABLE_VFSTRACE
8356 " -vfstrace enable tracing of all VFS calls\n"
8357#endif
drh3baed312018-03-08 18:14:41 +00008358#ifdef SQLITE_HAVE_ZLIB
8359 " -zip open the file as a ZIP Archive\n"
8360#endif
drh2ce15c32017-07-11 13:34:40 +00008361;
8362static void usage(int showDetail){
8363 utf8_printf(stderr,
8364 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8365 "FILENAME is the name of an SQLite database. A new database is created\n"
8366 "if the file does not previously exist.\n", Argv0);
8367 if( showDetail ){
8368 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
8369 }else{
8370 raw_printf(stderr, "Use the -help option for additional information\n");
8371 }
8372 exit(1);
8373}
8374
8375/*
drhe7df8922018-04-18 10:44:58 +00008376** Internal check: Verify that the SQLite is uninitialized. Print a
8377** error message if it is initialized.
8378*/
8379static void verify_uninitialized(void){
8380 if( sqlite3_config(-1)==SQLITE_MISUSE ){
drh8e02a182018-05-30 07:24:41 +00008381 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
drhe7df8922018-04-18 10:44:58 +00008382 " initialization.\n");
8383 }
8384}
8385
8386/*
drh2ce15c32017-07-11 13:34:40 +00008387** Initialize the state information in data
8388*/
8389static void main_init(ShellState *data) {
8390 memset(data, 0, sizeof(*data));
8391 data->normalMode = data->cMode = data->mode = MODE_List;
8392 data->autoExplain = 1;
8393 memcpy(data->colSeparator,SEP_Column, 2);
8394 memcpy(data->rowSeparator,SEP_Row, 2);
8395 data->showHeader = 0;
8396 data->shellFlgs = SHFLG_Lookaside;
drhe7df8922018-04-18 10:44:58 +00008397 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00008398 sqlite3_config(SQLITE_CONFIG_URI, 1);
8399 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
8400 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
8401 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
8402 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
8403}
8404
8405/*
8406** Output text to the console in a font that attracts extra attention.
8407*/
8408#ifdef _WIN32
8409static void printBold(const char *zText){
8410 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
8411 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
8412 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
8413 SetConsoleTextAttribute(out,
8414 FOREGROUND_RED|FOREGROUND_INTENSITY
8415 );
8416 printf("%s", zText);
8417 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
8418}
8419#else
8420static void printBold(const char *zText){
8421 printf("\033[1m%s\033[0m", zText);
8422}
8423#endif
8424
8425/*
8426** Get the argument to an --option. Throw an error and die if no argument
8427** is available.
8428*/
8429static char *cmdline_option_value(int argc, char **argv, int i){
8430 if( i==argc ){
8431 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
8432 argv[0], argv[argc-1]);
8433 exit(1);
8434 }
8435 return argv[i];
8436}
8437
8438#ifndef SQLITE_SHELL_IS_UTF8
8439# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8440# define SQLITE_SHELL_IS_UTF8 (0)
8441# else
8442# define SQLITE_SHELL_IS_UTF8 (1)
8443# endif
8444#endif
8445
8446#if SQLITE_SHELL_IS_UTF8
8447int SQLITE_CDECL main(int argc, char **argv){
8448#else
8449int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
8450 char **argv;
8451#endif
8452 char *zErrMsg = 0;
8453 ShellState data;
8454 const char *zInitFile = 0;
8455 int i;
8456 int rc = 0;
8457 int warnInmemoryDb = 0;
8458 int readStdin = 1;
8459 int nCmd = 0;
8460 char **azCmd = 0;
dan16a47422018-04-18 09:16:11 +00008461 const char *zVfs = 0; /* Value of -vfs command-line option */
drh1f22f622018-05-17 13:29:14 +00008462#if !SQLITE_SHELL_IS_UTF8
8463 char **argvToFree = 0;
8464 int argcToFree = 0;
8465#endif
drh2ce15c32017-07-11 13:34:40 +00008466
8467 setBinaryMode(stdin, 0);
8468 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
8469 stdin_is_interactive = isatty(0);
8470 stdout_is_console = isatty(1);
8471
mistachkin1e8487d2018-07-22 06:25:35 +00008472#if !defined(_WIN32_WCE)
8473 if( getenv("SQLITE_DEBUG_BREAK") ){
8474 if( isatty(0) && isatty(2) ){
8475 fprintf(stderr,
8476 "attach debugger to process %d and press any key to continue.\n",
8477 GETPID());
8478 fgetc(stdin);
8479 }else{
8480#if defined(_WIN32) || defined(WIN32)
8481 DebugBreak();
8482#elif defined(SIGTRAP)
8483 raise(SIGTRAP);
8484#endif
8485 }
8486 }
8487#endif
8488
drh2ce15c32017-07-11 13:34:40 +00008489#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00008490 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00008491 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
8492 sqlite3_sourceid(), SQLITE_SOURCE_ID);
8493 exit(1);
8494 }
8495#endif
8496 main_init(&data);
drh501ea052018-02-15 01:03:37 +00008497
8498 /* On Windows, we must translate command-line arguments into UTF-8.
8499 ** The SQLite memory allocator subsystem has to be enabled in order to
8500 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
8501 ** subsequent sqlite3_config() calls will work. So copy all results into
8502 ** memory that does not come from the SQLite memory allocator.
8503 */
drh4b18c1d2018-02-04 20:33:13 +00008504#if !SQLITE_SHELL_IS_UTF8
drh501ea052018-02-15 01:03:37 +00008505 sqlite3_initialize();
drh1f22f622018-05-17 13:29:14 +00008506 argvToFree = malloc(sizeof(argv[0])*argc*2);
8507 argcToFree = argc;
8508 argv = argvToFree + argc;
drh4b5345c2018-04-24 13:07:40 +00008509 if( argv==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008510 for(i=0; i<argc; i++){
drh501ea052018-02-15 01:03:37 +00008511 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
8512 int n;
drh4b5345c2018-04-24 13:07:40 +00008513 if( z==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00008514 n = (int)strlen(z);
8515 argv[i] = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00008516 if( argv[i]==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00008517 memcpy(argv[i], z, n+1);
drh1f22f622018-05-17 13:29:14 +00008518 argvToFree[i] = argv[i];
drh501ea052018-02-15 01:03:37 +00008519 sqlite3_free(z);
drh2ce15c32017-07-11 13:34:40 +00008520 }
drh501ea052018-02-15 01:03:37 +00008521 sqlite3_shutdown();
drh2ce15c32017-07-11 13:34:40 +00008522#endif
drh501ea052018-02-15 01:03:37 +00008523
drh2ce15c32017-07-11 13:34:40 +00008524 assert( argc>=1 && argv && argv[0] );
8525 Argv0 = argv[0];
8526
8527 /* Make sure we have a valid signal handler early, before anything
8528 ** else is done.
8529 */
8530#ifdef SIGINT
8531 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00008532#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
8533 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00008534#endif
8535
8536#ifdef SQLITE_SHELL_DBNAME_PROC
8537 {
8538 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8539 ** of a C-function that will provide the name of the database file. Use
8540 ** this compile-time option to embed this shell program in larger
8541 ** applications. */
8542 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8543 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
8544 warnInmemoryDb = 0;
8545 }
8546#endif
8547
8548 /* Do an initial pass through the command-line argument to locate
8549 ** the name of the database file, the name of the initialization file,
8550 ** the size of the alternative malloc heap,
8551 ** and the first command to execute.
8552 */
drhe7df8922018-04-18 10:44:58 +00008553 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00008554 for(i=1; i<argc; i++){
8555 char *z;
8556 z = argv[i];
8557 if( z[0]!='-' ){
8558 if( data.zDbFilename==0 ){
8559 data.zDbFilename = z;
8560 }else{
8561 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8562 ** mean that nothing is read from stdin */
8563 readStdin = 0;
8564 nCmd++;
8565 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
drh4b5345c2018-04-24 13:07:40 +00008566 if( azCmd==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008567 azCmd[nCmd-1] = z;
8568 }
8569 }
8570 if( z[1]=='-' ) z++;
8571 if( strcmp(z,"-separator")==0
8572 || strcmp(z,"-nullvalue")==0
8573 || strcmp(z,"-newline")==0
8574 || strcmp(z,"-cmd")==0
8575 ){
8576 (void)cmdline_option_value(argc, argv, ++i);
8577 }else if( strcmp(z,"-init")==0 ){
8578 zInitFile = cmdline_option_value(argc, argv, ++i);
8579 }else if( strcmp(z,"-batch")==0 ){
8580 /* Need to check for batch mode here to so we can avoid printing
8581 ** informational messages (like from process_sqliterc) before
8582 ** we do the actual processing of arguments later in a second pass.
8583 */
8584 stdin_is_interactive = 0;
8585 }else if( strcmp(z,"-heap")==0 ){
8586#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8587 const char *zSize;
8588 sqlite3_int64 szHeap;
8589
8590 zSize = cmdline_option_value(argc, argv, ++i);
8591 szHeap = integerValue(zSize);
8592 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
8593 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
8594#else
8595 (void)cmdline_option_value(argc, argv, ++i);
8596#endif
drh2ce15c32017-07-11 13:34:40 +00008597 }else if( strcmp(z,"-pagecache")==0 ){
8598 int n, sz;
8599 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8600 if( sz>70000 ) sz = 70000;
8601 if( sz<0 ) sz = 0;
8602 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8603 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
8604 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
8605 data.shellFlgs |= SHFLG_Pagecache;
8606 }else if( strcmp(z,"-lookaside")==0 ){
8607 int n, sz;
8608 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8609 if( sz<0 ) sz = 0;
8610 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8611 if( n<0 ) n = 0;
8612 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
8613 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
8614#ifdef SQLITE_ENABLE_VFSTRACE
8615 }else if( strcmp(z,"-vfstrace")==0 ){
8616 extern int vfstrace_register(
8617 const char *zTraceName,
8618 const char *zOldVfsName,
8619 int (*xOut)(const char*,void*),
8620 void *pOutArg,
8621 int makeDefault
8622 );
8623 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
8624#endif
8625#ifdef SQLITE_ENABLE_MULTIPLEX
8626 }else if( strcmp(z,"-multiplex")==0 ){
8627 extern int sqlite3_multiple_initialize(const char*,int);
8628 sqlite3_multiplex_initialize(0, 1);
8629#endif
8630 }else if( strcmp(z,"-mmap")==0 ){
8631 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8632 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drha90d84f2018-04-18 15:21:13 +00008633#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8634 }else if( strcmp(z,"-sorterref")==0 ){
8635 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8636 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
8637#endif
drh2ce15c32017-07-11 13:34:40 +00008638 }else if( strcmp(z,"-vfs")==0 ){
dan16a47422018-04-18 09:16:11 +00008639 zVfs = cmdline_option_value(argc, argv, ++i);
drh3baed312018-03-08 18:14:41 +00008640#ifdef SQLITE_HAVE_ZLIB
drh8682e122018-01-07 20:38:10 +00008641 }else if( strcmp(z,"-zip")==0 ){
8642 data.openMode = SHELL_OPEN_ZIPFILE;
8643#endif
8644 }else if( strcmp(z,"-append")==0 ){
8645 data.openMode = SHELL_OPEN_APPENDVFS;
drh60f34ae2018-10-30 13:19:49 +00008646 }else if( strcmp(z,"-deserialize")==0 ){
8647 data.openMode = SHELL_OPEN_DESERIALIZE;
drhee269a62018-02-14 23:27:43 +00008648 }else if( strcmp(z,"-readonly")==0 ){
8649 data.openMode = SHELL_OPEN_READONLY;
drhda57d962018-03-05 19:34:05 +00008650#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00008651 }else if( strncmp(z, "-A",2)==0 ){
drhda57d962018-03-05 19:34:05 +00008652 /* All remaining command-line arguments are passed to the ".archive"
8653 ** command, so ignore them */
8654 break;
8655#endif
drh2ce15c32017-07-11 13:34:40 +00008656 }
8657 }
drhe7df8922018-04-18 10:44:58 +00008658 verify_uninitialized();
8659
dan16a47422018-04-18 09:16:11 +00008660
drhd11b8f62018-04-25 13:27:07 +00008661#ifdef SQLITE_SHELL_INIT_PROC
8662 {
8663 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
8664 ** of a C-function that will perform initialization actions on SQLite that
8665 ** occur just before or after sqlite3_initialize(). Use this compile-time
8666 ** option to embed this shell program in larger applications. */
8667 extern void SQLITE_SHELL_INIT_PROC(void);
8668 SQLITE_SHELL_INIT_PROC();
8669 }
8670#else
dan16a47422018-04-18 09:16:11 +00008671 /* All the sqlite3_config() calls have now been made. So it is safe
8672 ** to call sqlite3_initialize() and process any command line -vfs option. */
8673 sqlite3_initialize();
drhd11b8f62018-04-25 13:27:07 +00008674#endif
8675
dan16a47422018-04-18 09:16:11 +00008676 if( zVfs ){
8677 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
8678 if( pVfs ){
8679 sqlite3_vfs_register(pVfs, 1);
8680 }else{
8681 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
8682 exit(1);
8683 }
8684 }
8685
drh2ce15c32017-07-11 13:34:40 +00008686 if( data.zDbFilename==0 ){
8687#ifndef SQLITE_OMIT_MEMORYDB
8688 data.zDbFilename = ":memory:";
8689 warnInmemoryDb = argc==1;
8690#else
8691 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
8692 return 1;
8693#endif
8694 }
8695 data.out = stdout;
drh8682e122018-01-07 20:38:10 +00008696 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +00008697
8698 /* Go ahead and open the database file if it already exists. If the
8699 ** file does not exist, delay opening it. This prevents empty database
8700 ** files from being created if a user mistypes the database name argument
8701 ** to the sqlite command-line tool.
8702 */
8703 if( access(data.zDbFilename, 0)==0 ){
8704 open_db(&data, 0);
8705 }
8706
8707 /* Process the initialization file if there is one. If no -init option
8708 ** is given on the command line, look for a file named ~/.sqliterc and
8709 ** try to process it.
8710 */
8711 process_sqliterc(&data,zInitFile);
8712
8713 /* Make a second pass through the command-line argument and set
8714 ** options. This second pass is delayed until after the initialization
8715 ** file is processed so that the command-line arguments will override
8716 ** settings in the initialization file.
8717 */
8718 for(i=1; i<argc; i++){
8719 char *z = argv[i];
8720 if( z[0]!='-' ) continue;
8721 if( z[1]=='-' ){ z++; }
8722 if( strcmp(z,"-init")==0 ){
8723 i++;
8724 }else if( strcmp(z,"-html")==0 ){
8725 data.mode = MODE_Html;
8726 }else if( strcmp(z,"-list")==0 ){
8727 data.mode = MODE_List;
8728 }else if( strcmp(z,"-quote")==0 ){
8729 data.mode = MODE_Quote;
8730 }else if( strcmp(z,"-line")==0 ){
8731 data.mode = MODE_Line;
8732 }else if( strcmp(z,"-column")==0 ){
8733 data.mode = MODE_Column;
8734 }else if( strcmp(z,"-csv")==0 ){
8735 data.mode = MODE_Csv;
8736 memcpy(data.colSeparator,",",2);
drh3baed312018-03-08 18:14:41 +00008737#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00008738 }else if( strcmp(z,"-zip")==0 ){
8739 data.openMode = SHELL_OPEN_ZIPFILE;
8740#endif
8741 }else if( strcmp(z,"-append")==0 ){
8742 data.openMode = SHELL_OPEN_APPENDVFS;
drh60f34ae2018-10-30 13:19:49 +00008743 }else if( strcmp(z,"-deserialize")==0 ){
8744 data.openMode = SHELL_OPEN_DESERIALIZE;
drh4aafe592018-03-23 16:08:30 +00008745 }else if( strcmp(z,"-readonly")==0 ){
8746 data.openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +00008747 }else if( strcmp(z,"-ascii")==0 ){
8748 data.mode = MODE_Ascii;
8749 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8750 SEP_Unit);
8751 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8752 SEP_Record);
8753 }else if( strcmp(z,"-separator")==0 ){
8754 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8755 "%s",cmdline_option_value(argc,argv,++i));
8756 }else if( strcmp(z,"-newline")==0 ){
8757 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8758 "%s",cmdline_option_value(argc,argv,++i));
8759 }else if( strcmp(z,"-nullvalue")==0 ){
8760 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
8761 "%s",cmdline_option_value(argc,argv,++i));
8762 }else if( strcmp(z,"-header")==0 ){
8763 data.showHeader = 1;
8764 }else if( strcmp(z,"-noheader")==0 ){
8765 data.showHeader = 0;
8766 }else if( strcmp(z,"-echo")==0 ){
8767 ShellSetFlag(&data, SHFLG_Echo);
8768 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +00008769 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +00008770 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +00008771 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +00008772 }else if( strcmp(z,"-stats")==0 ){
8773 data.statsOn = 1;
8774 }else if( strcmp(z,"-scanstats")==0 ){
8775 data.scanstatsOn = 1;
8776 }else if( strcmp(z,"-backslash")==0 ){
8777 /* Undocumented command-line option: -backslash
8778 ** Causes C-style backslash escapes to be evaluated in SQL statements
8779 ** prior to sending the SQL into SQLite. Useful for injecting
8780 ** crazy bytes in the middle of SQL statements for testing and debugging.
8781 */
8782 ShellSetFlag(&data, SHFLG_Backslash);
8783 }else if( strcmp(z,"-bail")==0 ){
8784 bail_on_error = 1;
8785 }else if( strcmp(z,"-version")==0 ){
8786 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8787 return 0;
8788 }else if( strcmp(z,"-interactive")==0 ){
8789 stdin_is_interactive = 1;
8790 }else if( strcmp(z,"-batch")==0 ){
8791 stdin_is_interactive = 0;
8792 }else if( strcmp(z,"-heap")==0 ){
8793 i++;
drh2ce15c32017-07-11 13:34:40 +00008794 }else if( strcmp(z,"-pagecache")==0 ){
8795 i+=2;
8796 }else if( strcmp(z,"-lookaside")==0 ){
8797 i+=2;
8798 }else if( strcmp(z,"-mmap")==0 ){
8799 i++;
drha90d84f2018-04-18 15:21:13 +00008800#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8801 }else if( strcmp(z,"-sorterref")==0 ){
8802 i++;
8803#endif
drh2ce15c32017-07-11 13:34:40 +00008804 }else if( strcmp(z,"-vfs")==0 ){
8805 i++;
8806#ifdef SQLITE_ENABLE_VFSTRACE
8807 }else if( strcmp(z,"-vfstrace")==0 ){
8808 i++;
8809#endif
8810#ifdef SQLITE_ENABLE_MULTIPLEX
8811 }else if( strcmp(z,"-multiplex")==0 ){
8812 i++;
8813#endif
8814 }else if( strcmp(z,"-help")==0 ){
8815 usage(1);
8816 }else if( strcmp(z,"-cmd")==0 ){
8817 /* Run commands that follow -cmd first and separately from commands
8818 ** that simply appear on the command-line. This seems goofy. It would
8819 ** be better if all commands ran in the order that they appear. But
8820 ** we retain the goofy behavior for historical compatibility. */
8821 if( i==argc-1 ) break;
8822 z = cmdline_option_value(argc,argv,++i);
8823 if( z[0]=='.' ){
8824 rc = do_meta_command(z, &data);
8825 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
8826 }else{
8827 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00008828 rc = shell_exec(&data, z, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008829 if( zErrMsg!=0 ){
8830 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8831 if( bail_on_error ) return rc!=0 ? rc : 1;
8832 }else if( rc!=0 ){
8833 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
8834 if( bail_on_error ) return rc;
8835 }
8836 }
drhda57d962018-03-05 19:34:05 +00008837#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00008838 }else if( strncmp(z, "-A", 2)==0 ){
drhda57d962018-03-05 19:34:05 +00008839 if( nCmd>0 ){
8840 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
8841 " with \"%s\"\n", z);
8842 return 1;
8843 }
drhbe4ccb22018-05-17 20:04:24 +00008844 open_db(&data, OPEN_DB_ZIPFILE);
drh93b77312018-03-05 20:20:22 +00008845 if( z[2] ){
8846 argv[i] = &z[2];
drhd0f9cdc2018-05-17 14:09:06 +00008847 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
drh93b77312018-03-05 20:20:22 +00008848 }else{
drhd0f9cdc2018-05-17 14:09:06 +00008849 arDotCommand(&data, 1, argv+i, argc-i);
drh93b77312018-03-05 20:20:22 +00008850 }
drhda57d962018-03-05 19:34:05 +00008851 readStdin = 0;
8852 break;
8853#endif
drh2ce15c32017-07-11 13:34:40 +00008854 }else{
8855 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
8856 raw_printf(stderr,"Use -help for a list of options.\n");
8857 return 1;
8858 }
8859 data.cMode = data.mode;
8860 }
8861
8862 if( !readStdin ){
8863 /* Run all arguments that do not begin with '-' as if they were separate
8864 ** command-line inputs, except for the argToSkip argument which contains
8865 ** the database filename.
8866 */
8867 for(i=0; i<nCmd; i++){
8868 if( azCmd[i][0]=='.' ){
8869 rc = do_meta_command(azCmd[i], &data);
8870 if( rc ) return rc==2 ? 0 : rc;
8871 }else{
8872 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00008873 rc = shell_exec(&data, azCmd[i], &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008874 if( zErrMsg!=0 ){
8875 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8876 return rc!=0 ? rc : 1;
8877 }else if( rc!=0 ){
8878 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
8879 return rc;
8880 }
8881 }
8882 }
8883 free(azCmd);
8884 }else{
8885 /* Run commands received from standard input
8886 */
8887 if( stdin_is_interactive ){
8888 char *zHome;
drha9e4be32018-10-10 18:56:40 +00008889 char *zHistory;
drh2ce15c32017-07-11 13:34:40 +00008890 int nHistory;
8891 printf(
8892 "SQLite version %s %.19s\n" /*extra-version-info*/
8893 "Enter \".help\" for usage hints.\n",
8894 sqlite3_libversion(), sqlite3_sourceid()
8895 );
8896 if( warnInmemoryDb ){
8897 printf("Connected to a ");
8898 printBold("transient in-memory database");
8899 printf(".\nUse \".open FILENAME\" to reopen on a "
8900 "persistent database.\n");
8901 }
drha9e4be32018-10-10 18:56:40 +00008902 zHistory = getenv("SQLITE_HISTORY");
8903 if( zHistory ){
8904 zHistory = strdup(zHistory);
8905 }else if( (zHome = find_home_dir(0))!=0 ){
drh2ce15c32017-07-11 13:34:40 +00008906 nHistory = strlen30(zHome) + 20;
8907 if( (zHistory = malloc(nHistory))!=0 ){
8908 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8909 }
8910 }
8911 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +00008912#if HAVE_READLINE || HAVE_EDITLINE
8913 rl_attempted_completion_function = readline_completion;
8914#elif HAVE_LINENOISE
8915 linenoiseSetCompletionCallback(linenoise_completion);
8916#endif
drh2ce15c32017-07-11 13:34:40 +00008917 rc = process_input(&data, 0);
8918 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +00008919 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +00008920 shell_write_history(zHistory);
8921 free(zHistory);
8922 }
8923 }else{
8924 rc = process_input(&data, stdin);
8925 }
8926 }
8927 set_table_name(&data, 0);
8928 if( data.db ){
8929 session_close_all(&data);
drh9e804032018-05-18 17:11:50 +00008930 close_db(data.db);
drh2ce15c32017-07-11 13:34:40 +00008931 }
8932 sqlite3_free(data.zFreeOnClose);
8933 find_home_dir(1);
drh536c3452018-01-11 00:38:39 +00008934 output_reset(&data);
8935 data.doXdgOpen = 0;
drh13c20932018-01-10 21:41:55 +00008936 clearTempFile(&data);
drh2ce15c32017-07-11 13:34:40 +00008937#if !SQLITE_SHELL_IS_UTF8
drh1f22f622018-05-17 13:29:14 +00008938 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
8939 free(argvToFree);
drh2ce15c32017-07-11 13:34:40 +00008940#endif
drh9e804032018-05-18 17:11:50 +00008941 /* Clear the global data structure so that valgrind will detect memory
8942 ** leaks */
8943 memset(&data, 0, sizeof(data));
drh2ce15c32017-07-11 13:34:40 +00008944 return rc;
8945}