blob: f9942446a536b3c0587561442a43b5f58dd83595 [file] [log] [blame]
drh2ce15c32017-07-11 13:34:40 +00001/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Warning pragmas copied from msvc.h in the core.
22*/
23#if defined(_MSC_VER)
24#pragma warning(disable : 4054)
25#pragma warning(disable : 4055)
26#pragma warning(disable : 4100)
27#pragma warning(disable : 4127)
28#pragma warning(disable : 4130)
29#pragma warning(disable : 4152)
30#pragma warning(disable : 4189)
31#pragma warning(disable : 4206)
32#pragma warning(disable : 4210)
33#pragma warning(disable : 4232)
34#pragma warning(disable : 4244)
35#pragma warning(disable : 4305)
36#pragma warning(disable : 4306)
37#pragma warning(disable : 4702)
38#pragma warning(disable : 4706)
39#endif /* defined(_MSC_VER) */
40
41/*
42** No support for loadable extensions in VxWorks.
43*/
44#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45# define SQLITE_OMIT_LOAD_EXTENSION 1
46#endif
47
48/*
49** Enable large-file support for fopen() and friends on unix.
50*/
51#ifndef SQLITE_DISABLE_LFS
52# define _LARGE_FILE 1
53# ifndef _FILE_OFFSET_BITS
54# define _FILE_OFFSET_BITS 64
55# endif
56# define _LARGEFILE_SOURCE 1
57#endif
58
59#include <stdlib.h>
60#include <string.h>
61#include <stdio.h>
62#include <assert.h>
63#include "sqlite3.h"
drh1e506b52018-01-05 21:01:37 +000064typedef sqlite3_int64 i64;
65typedef sqlite3_uint64 u64;
drh1fa6d9f2018-01-06 21:46:01 +000066typedef unsigned char u8;
drh2ce15c32017-07-11 13:34:40 +000067#if SQLITE_USER_AUTHENTICATION
68# include "sqlite3userauth.h"
69#endif
70#include <ctype.h>
71#include <stdarg.h>
72
73#if !defined(_WIN32) && !defined(WIN32)
74# include <signal.h>
75# if !defined(__RTP__) && !defined(_WRS_KERNEL)
76# include <pwd.h>
77# endif
mistachkinacae8c32018-01-05 20:08:46 +000078#endif
mistachkin562f0c82018-01-09 00:28:24 +000079#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
drh2ce15c32017-07-11 13:34:40 +000080# include <unistd.h>
mistachkinacae8c32018-01-05 20:08:46 +000081# include <dirent.h>
mistachkin562f0c82018-01-09 00:28:24 +000082# if defined(__MINGW32__)
mistachkinacae8c32018-01-05 20:08:46 +000083# define DIRENT dirent
mistachkin2f74b3c2018-01-05 20:26:06 +000084# ifndef S_ISLNK
85# define S_ISLNK(mode) (0)
86# endif
mistachkinacae8c32018-01-05 20:08:46 +000087# endif
drh2ce15c32017-07-11 13:34:40 +000088#endif
mistachkindfdfd8c2018-01-04 22:46:08 +000089#include <sys/types.h>
90#include <sys/stat.h>
drh2ce15c32017-07-11 13:34:40 +000091
92#if HAVE_READLINE
93# include <readline/readline.h>
94# include <readline/history.h>
95#endif
96
97#if HAVE_EDITLINE
98# include <editline/readline.h>
99#endif
100
101#if HAVE_EDITLINE || HAVE_READLINE
102
103# define shell_add_history(X) add_history(X)
104# define shell_read_history(X) read_history(X)
105# define shell_write_history(X) write_history(X)
106# define shell_stifle_history(X) stifle_history(X)
107# define shell_readline(X) readline(X)
108
109#elif HAVE_LINENOISE
110
111# include "linenoise.h"
112# define shell_add_history(X) linenoiseHistoryAdd(X)
113# define shell_read_history(X) linenoiseHistoryLoad(X)
114# define shell_write_history(X) linenoiseHistorySave(X)
115# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
116# define shell_readline(X) linenoise(X)
117
118#else
119
120# define shell_read_history(X)
121# define shell_write_history(X)
122# define shell_stifle_history(X)
123
124# define SHELL_USE_LOCAL_GETLINE 1
125#endif
126
127
128#if defined(_WIN32) || defined(WIN32)
129# include <io.h>
130# include <fcntl.h>
131# define isatty(h) _isatty(h)
132# ifndef access
133# define access(f,m) _access((f),(m))
134# endif
135# undef popen
136# define popen _popen
137# undef pclose
138# define pclose _pclose
139#else
140 /* Make sure isatty() has a prototype. */
141 extern int isatty(int);
142
143# if !defined(__RTP__) && !defined(_WRS_KERNEL)
144 /* popen and pclose are not C89 functions and so are
145 ** sometimes omitted from the <stdio.h> header */
146 extern FILE *popen(const char*,const char*);
147 extern int pclose(FILE*);
148# else
149# define SQLITE_OMIT_POPEN 1
150# endif
151#endif
152
153#if defined(_WIN32_WCE)
154/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
155 * thus we always assume that we have a console. That can be
156 * overridden with the -batch command line option.
157 */
158#define isatty(x) 1
159#endif
160
161/* ctype macros that work with signed characters */
162#define IsSpace(X) isspace((unsigned char)X)
163#define IsDigit(X) isdigit((unsigned char)X)
164#define ToLower(X) (char)tolower((unsigned char)X)
165
166#if defined(_WIN32) || defined(WIN32)
167#include <windows.h>
168
169/* string conversion routines only needed on Win32 */
170extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
171extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
172extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
173extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
174#endif
175
176/* On Windows, we normally run with output mode of TEXT so that \n characters
177** are automatically translated into \r\n. However, this behavior needs
178** to be disabled in some cases (ex: when generating CSV output and when
179** rendering quoted strings that contain \n characters). The following
180** routines take care of that.
181*/
182#if defined(_WIN32) || defined(WIN32)
183static void setBinaryMode(FILE *file, int isOutput){
184 if( isOutput ) fflush(file);
185 _setmode(_fileno(file), _O_BINARY);
186}
187static void setTextMode(FILE *file, int isOutput){
188 if( isOutput ) fflush(file);
189 _setmode(_fileno(file), _O_TEXT);
190}
191#else
192# define setBinaryMode(X,Y)
193# define setTextMode(X,Y)
194#endif
195
196
197/* True if the timer is enabled */
198static int enableTimer = 0;
199
200/* Return the current wall-clock time */
201static sqlite3_int64 timeOfDay(void){
202 static sqlite3_vfs *clockVfs = 0;
203 sqlite3_int64 t;
204 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
205 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
206 clockVfs->xCurrentTimeInt64(clockVfs, &t);
207 }else{
208 double r;
209 clockVfs->xCurrentTime(clockVfs, &r);
210 t = (sqlite3_int64)(r*86400000.0);
211 }
212 return t;
213}
214
215#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
216#include <sys/time.h>
217#include <sys/resource.h>
218
219/* VxWorks does not support getrusage() as far as we can determine */
220#if defined(_WRS_KERNEL) || defined(__RTP__)
221struct rusage {
222 struct timeval ru_utime; /* user CPU time used */
223 struct timeval ru_stime; /* system CPU time used */
224};
225#define getrusage(A,B) memset(B,0,sizeof(*B))
226#endif
227
228/* Saved resource information for the beginning of an operation */
229static struct rusage sBegin; /* CPU time at start */
230static sqlite3_int64 iBegin; /* Wall-clock time at start */
231
232/*
233** Begin timing an operation
234*/
235static void beginTimer(void){
236 if( enableTimer ){
237 getrusage(RUSAGE_SELF, &sBegin);
238 iBegin = timeOfDay();
239 }
240}
241
242/* Return the difference of two time_structs in seconds */
243static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
244 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
245 (double)(pEnd->tv_sec - pStart->tv_sec);
246}
247
248/*
249** Print the timing results.
250*/
251static void endTimer(void){
252 if( enableTimer ){
253 sqlite3_int64 iEnd = timeOfDay();
254 struct rusage sEnd;
255 getrusage(RUSAGE_SELF, &sEnd);
256 printf("Run Time: real %.3f user %f sys %f\n",
257 (iEnd - iBegin)*0.001,
258 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
259 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
260 }
261}
262
263#define BEGIN_TIMER beginTimer()
264#define END_TIMER endTimer()
265#define HAS_TIMER 1
266
267#elif (defined(_WIN32) || defined(WIN32))
268
269/* Saved resource information for the beginning of an operation */
270static HANDLE hProcess;
271static FILETIME ftKernelBegin;
272static FILETIME ftUserBegin;
273static sqlite3_int64 ftWallBegin;
274typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
275 LPFILETIME, LPFILETIME);
276static GETPROCTIMES getProcessTimesAddr = NULL;
277
278/*
279** Check to see if we have timer support. Return 1 if necessary
280** support found (or found previously).
281*/
282static int hasTimer(void){
283 if( getProcessTimesAddr ){
284 return 1;
285 } else {
286 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
287 ** versions. See if the version we are running on has it, and if it
288 ** does, save off a pointer to it and the current process handle.
289 */
290 hProcess = GetCurrentProcess();
291 if( hProcess ){
292 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
293 if( NULL != hinstLib ){
294 getProcessTimesAddr =
295 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
296 if( NULL != getProcessTimesAddr ){
297 return 1;
298 }
299 FreeLibrary(hinstLib);
300 }
301 }
302 }
303 return 0;
304}
305
306/*
307** Begin timing an operation
308*/
309static void beginTimer(void){
310 if( enableTimer && getProcessTimesAddr ){
311 FILETIME ftCreation, ftExit;
312 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
313 &ftKernelBegin,&ftUserBegin);
314 ftWallBegin = timeOfDay();
315 }
316}
317
318/* Return the difference of two FILETIME structs in seconds */
319static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
320 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
321 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
322 return (double) ((i64End - i64Start) / 10000000.0);
323}
324
325/*
326** Print the timing results.
327*/
328static void endTimer(void){
329 if( enableTimer && getProcessTimesAddr){
330 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
331 sqlite3_int64 ftWallEnd = timeOfDay();
332 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
333 printf("Run Time: real %.3f user %f sys %f\n",
334 (ftWallEnd - ftWallBegin)*0.001,
335 timeDiff(&ftUserBegin, &ftUserEnd),
336 timeDiff(&ftKernelBegin, &ftKernelEnd));
337 }
338}
339
340#define BEGIN_TIMER beginTimer()
341#define END_TIMER endTimer()
342#define HAS_TIMER hasTimer()
343
344#else
345#define BEGIN_TIMER
346#define END_TIMER
347#define HAS_TIMER 0
348#endif
349
350/*
351** Used to prevent warnings about unused parameters
352*/
353#define UNUSED_PARAMETER(x) (void)(x)
354
355/*
drh5af06982018-01-10 00:53:55 +0000356** Number of elements in an array
357*/
358#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
359
360/*
drh2ce15c32017-07-11 13:34:40 +0000361** If the following flag is set, then command execution stops
362** at an error if we are not interactive.
363*/
364static int bail_on_error = 0;
365
366/*
367** Threat stdin as an interactive input if the following variable
368** is true. Otherwise, assume stdin is connected to a file or pipe.
369*/
370static int stdin_is_interactive = 1;
371
372/*
373** On Windows systems we have to know if standard output is a console
374** in order to translate UTF-8 into MBCS. The following variable is
375** true if translation is required.
376*/
377static int stdout_is_console = 1;
378
379/*
380** The following is the open SQLite database. We make a pointer
381** to this database a static variable so that it can be accessed
382** by the SIGINT handler to interrupt database processing.
383*/
384static sqlite3 *globalDb = 0;
385
386/*
387** True if an interrupt (Control-C) has been received.
388*/
389static volatile int seenInterrupt = 0;
390
391/*
392** This is the name of our program. It is set in main(), used
393** in a number of other places, mostly for error messages.
394*/
395static char *Argv0;
396
397/*
398** Prompt strings. Initialized in main. Settable with
399** .prompt main continue
400*/
401static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
402static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
403
404/*
405** Render output like fprintf(). Except, if the output is going to the
406** console and if this is running on a Windows machine, translate the
407** output from UTF-8 into MBCS.
408*/
409#if defined(_WIN32) || defined(WIN32)
410void utf8_printf(FILE *out, const char *zFormat, ...){
411 va_list ap;
412 va_start(ap, zFormat);
413 if( stdout_is_console && (out==stdout || out==stderr) ){
414 char *z1 = sqlite3_vmprintf(zFormat, ap);
415 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
416 sqlite3_free(z1);
417 fputs(z2, out);
418 sqlite3_free(z2);
419 }else{
420 vfprintf(out, zFormat, ap);
421 }
422 va_end(ap);
423}
424#elif !defined(utf8_printf)
425# define utf8_printf fprintf
426#endif
427
428/*
429** Render output like fprintf(). This should not be used on anything that
430** includes string formatting (e.g. "%s").
431*/
432#if !defined(raw_printf)
433# define raw_printf fprintf
434#endif
435
436/*
437** Write I/O traces to the following stream.
438*/
439#ifdef SQLITE_ENABLE_IOTRACE
440static FILE *iotrace = 0;
441#endif
442
443/*
444** This routine works like printf in that its first argument is a
445** format string and subsequent arguments are values to be substituted
446** in place of % fields. The result of formatting this string
447** is written to iotrace.
448*/
449#ifdef SQLITE_ENABLE_IOTRACE
450static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
451 va_list ap;
452 char *z;
453 if( iotrace==0 ) return;
454 va_start(ap, zFormat);
455 z = sqlite3_vmprintf(zFormat, ap);
456 va_end(ap);
457 utf8_printf(iotrace, "%s", z);
458 sqlite3_free(z);
459}
460#endif
461
462/*
463** Output string zUtf to stream pOut as w characters. If w is negative,
464** then right-justify the text. W is the width in UTF-8 characters, not
465** in bytes. This is different from the %*.*s specification in printf
466** since with %*.*s the width is measured in bytes, not characters.
467*/
468static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
469 int i;
470 int n;
471 int aw = w<0 ? -w : w;
472 char zBuf[1000];
473 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
474 for(i=n=0; zUtf[i]; i++){
475 if( (zUtf[i]&0xc0)!=0x80 ){
476 n++;
477 if( n==aw ){
478 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
479 break;
480 }
481 }
482 }
483 if( n>=aw ){
484 utf8_printf(pOut, "%.*s", i, zUtf);
485 }else if( w<0 ){
486 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
487 }else{
488 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
489 }
490}
491
492
493/*
494** Determines if a string is a number of not.
495*/
496static int isNumber(const char *z, int *realnum){
497 if( *z=='-' || *z=='+' ) z++;
498 if( !IsDigit(*z) ){
499 return 0;
500 }
501 z++;
502 if( realnum ) *realnum = 0;
503 while( IsDigit(*z) ){ z++; }
504 if( *z=='.' ){
505 z++;
506 if( !IsDigit(*z) ) return 0;
507 while( IsDigit(*z) ){ z++; }
508 if( realnum ) *realnum = 1;
509 }
510 if( *z=='e' || *z=='E' ){
511 z++;
512 if( *z=='+' || *z=='-' ) z++;
513 if( !IsDigit(*z) ) return 0;
514 while( IsDigit(*z) ){ z++; }
515 if( realnum ) *realnum = 1;
516 }
517 return *z==0;
518}
519
520/*
521** Compute a string length that is limited to what can be stored in
522** lower 30 bits of a 32-bit signed integer.
523*/
524static int strlen30(const char *z){
525 const char *z2 = z;
526 while( *z2 ){ z2++; }
527 return 0x3fffffff & (int)(z2 - z);
528}
529
530/*
531** Return the length of a string in characters. Multibyte UTF8 characters
532** count as a single character.
533*/
534static int strlenChar(const char *z){
535 int n = 0;
536 while( *z ){
537 if( (0xc0&*(z++))!=0x80 ) n++;
538 }
539 return n;
540}
541
542/*
543** This routine reads a line of text from FILE in, stores
544** the text in memory obtained from malloc() and returns a pointer
545** to the text. NULL is returned at end of file, or if malloc()
546** fails.
547**
548** If zLine is not NULL then it is a malloced buffer returned from
549** a previous call to this routine that may be reused.
550*/
551static char *local_getline(char *zLine, FILE *in){
552 int nLine = zLine==0 ? 0 : 100;
553 int n = 0;
554
555 while( 1 ){
556 if( n+100>nLine ){
557 nLine = nLine*2 + 100;
558 zLine = realloc(zLine, nLine);
559 if( zLine==0 ) return 0;
560 }
561 if( fgets(&zLine[n], nLine - n, in)==0 ){
562 if( n==0 ){
563 free(zLine);
564 return 0;
565 }
566 zLine[n] = 0;
567 break;
568 }
569 while( zLine[n] ) n++;
570 if( n>0 && zLine[n-1]=='\n' ){
571 n--;
572 if( n>0 && zLine[n-1]=='\r' ) n--;
573 zLine[n] = 0;
574 break;
575 }
576 }
577#if defined(_WIN32) || defined(WIN32)
578 /* For interactive input on Windows systems, translate the
579 ** multi-byte characterset characters into UTF-8. */
580 if( stdin_is_interactive && in==stdin ){
581 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
582 if( zTrans ){
583 int nTrans = strlen30(zTrans)+1;
584 if( nTrans>nLine ){
585 zLine = realloc(zLine, nTrans);
586 if( zLine==0 ){
587 sqlite3_free(zTrans);
588 return 0;
589 }
590 }
591 memcpy(zLine, zTrans, nTrans);
592 sqlite3_free(zTrans);
593 }
594 }
595#endif /* defined(_WIN32) || defined(WIN32) */
596 return zLine;
597}
598
599/*
600** Retrieve a single line of input text.
601**
602** If in==0 then read from standard input and prompt before each line.
603** If isContinuation is true, then a continuation prompt is appropriate.
604** If isContinuation is zero, then the main prompt should be used.
605**
606** If zPrior is not NULL then it is a buffer from a prior call to this
607** routine that can be reused.
608**
609** The result is stored in space obtained from malloc() and must either
610** be freed by the caller or else passed back into this routine via the
611** zPrior argument for reuse.
612*/
613static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
614 char *zPrompt;
615 char *zResult;
616 if( in!=0 ){
617 zResult = local_getline(zPrior, in);
618 }else{
619 zPrompt = isContinuation ? continuePrompt : mainPrompt;
620#if SHELL_USE_LOCAL_GETLINE
621 printf("%s", zPrompt);
622 fflush(stdout);
623 zResult = local_getline(zPrior, stdin);
624#else
625 free(zPrior);
626 zResult = shell_readline(zPrompt);
627 if( zResult && *zResult ) shell_add_history(zResult);
628#endif
629 }
630 return zResult;
631}
drh5af06982018-01-10 00:53:55 +0000632
633
634/*
635** Return the value of a hexadecimal digit. Return -1 if the input
636** is not a hex digit.
637*/
638static int hexDigitValue(char c){
639 if( c>='0' && c<='9' ) return c - '0';
640 if( c>='a' && c<='f' ) return c - 'a' + 10;
641 if( c>='A' && c<='F' ) return c - 'A' + 10;
642 return -1;
643}
644
645/*
646** Interpret zArg as an integer value, possibly with suffixes.
647*/
648static sqlite3_int64 integerValue(const char *zArg){
649 sqlite3_int64 v = 0;
650 static const struct { char *zSuffix; int iMult; } aMult[] = {
651 { "KiB", 1024 },
652 { "MiB", 1024*1024 },
653 { "GiB", 1024*1024*1024 },
654 { "KB", 1000 },
655 { "MB", 1000000 },
656 { "GB", 1000000000 },
657 { "K", 1000 },
658 { "M", 1000000 },
659 { "G", 1000000000 },
660 };
661 int i;
662 int isNeg = 0;
663 if( zArg[0]=='-' ){
664 isNeg = 1;
665 zArg++;
666 }else if( zArg[0]=='+' ){
667 zArg++;
668 }
669 if( zArg[0]=='0' && zArg[1]=='x' ){
670 int x;
671 zArg += 2;
672 while( (x = hexDigitValue(zArg[0]))>=0 ){
673 v = (v<<4) + x;
674 zArg++;
675 }
676 }else{
677 while( IsDigit(zArg[0]) ){
678 v = v*10 + zArg[0] - '0';
679 zArg++;
680 }
681 }
682 for(i=0; i<ArraySize(aMult); i++){
683 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
684 v *= aMult[i].iMult;
685 break;
686 }
687 }
688 return isNeg? -v : v;
689}
690
drh2ce15c32017-07-11 13:34:40 +0000691/*
692** A variable length string to which one can append text.
693*/
694typedef struct ShellText ShellText;
695struct ShellText {
696 char *z;
697 int n;
698 int nAlloc;
699};
700
701/*
702** Initialize and destroy a ShellText object
703*/
704static void initText(ShellText *p){
705 memset(p, 0, sizeof(*p));
706}
707static void freeText(ShellText *p){
708 free(p->z);
709 initText(p);
710}
711
712/* zIn is either a pointer to a NULL-terminated string in memory obtained
713** from malloc(), or a NULL pointer. The string pointed to by zAppend is
714** added to zIn, and the result returned in memory obtained from malloc().
715** zIn, if it was not NULL, is freed.
716**
717** If the third argument, quote, is not '\0', then it is used as a
718** quote character for zAppend.
719*/
720static void appendText(ShellText *p, char const *zAppend, char quote){
721 int len;
722 int i;
723 int nAppend = strlen30(zAppend);
724
725 len = nAppend+p->n+1;
726 if( quote ){
727 len += 2;
728 for(i=0; i<nAppend; i++){
729 if( zAppend[i]==quote ) len++;
730 }
731 }
732
733 if( p->n+len>=p->nAlloc ){
734 p->nAlloc = p->nAlloc*2 + len + 20;
735 p->z = realloc(p->z, p->nAlloc);
736 if( p->z==0 ){
737 memset(p, 0, sizeof(*p));
738 return;
739 }
740 }
741
742 if( quote ){
743 char *zCsr = p->z+p->n;
744 *zCsr++ = quote;
745 for(i=0; i<nAppend; i++){
746 *zCsr++ = zAppend[i];
747 if( zAppend[i]==quote ) *zCsr++ = quote;
748 }
749 *zCsr++ = quote;
750 p->n = (int)(zCsr - p->z);
751 *zCsr = '\0';
752 }else{
753 memcpy(p->z+p->n, zAppend, nAppend);
754 p->n += nAppend;
755 p->z[p->n] = '\0';
756 }
757}
758
759/*
760** Attempt to determine if identifier zName needs to be quoted, either
761** because it contains non-alphanumeric characters, or because it is an
762** SQLite keyword. Be conservative in this estimate: When in doubt assume
763** that quoting is required.
764**
765** Return '"' if quoting is required. Return 0 if no quoting is required.
766*/
767static char quoteChar(const char *zName){
768 /* All SQLite keywords, in alphabetical order */
769 static const char *azKeywords[] = {
770 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
771 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
772 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
773 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
774 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
775 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
776 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
777 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
778 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
779 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
780 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
781 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
782 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
783 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
784 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
785 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
786 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
787 "WITH", "WITHOUT",
788 };
789 int i, lwr, upr, mid, c;
790 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
791 for(i=0; zName[i]; i++){
792 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
793 }
794 lwr = 0;
795 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
796 while( lwr<=upr ){
797 mid = (lwr+upr)/2;
798 c = sqlite3_stricmp(azKeywords[mid], zName);
799 if( c==0 ) return '"';
800 if( c<0 ){
801 lwr = mid+1;
802 }else{
803 upr = mid-1;
804 }
805 }
806 return 0;
807}
808
809/*
drh667a2a22018-01-02 00:04:37 +0000810** Construct a fake object name and column list to describe the structure
811** of the view, virtual table, or table valued function zSchema.zName.
drhceba7922018-01-01 21:28:25 +0000812*/
drh667a2a22018-01-02 00:04:37 +0000813static char *shellFakeSchema(
drhceba7922018-01-01 21:28:25 +0000814 sqlite3 *db, /* The database connection containing the vtab */
815 const char *zSchema, /* Schema of the database holding the vtab */
816 const char *zName /* The name of the virtual table */
817){
818 sqlite3_stmt *pStmt = 0;
819 char *zSql;
drh1d315cf2018-01-01 21:49:43 +0000820 ShellText s;
821 char cQuote;
822 char *zDiv = "(";
drh667a2a22018-01-02 00:04:37 +0000823 int nRow = 0;
drhceba7922018-01-01 21:28:25 +0000824
drh1d315cf2018-01-01 21:49:43 +0000825 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
826 zSchema ? zSchema : "main", zName);
drhceba7922018-01-01 21:28:25 +0000827 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
828 sqlite3_free(zSql);
drh1d315cf2018-01-01 21:49:43 +0000829 initText(&s);
830 if( zSchema ){
831 cQuote = quoteChar(zSchema);
832 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
833 appendText(&s, zSchema, cQuote);
834 appendText(&s, ".", 0);
drhceba7922018-01-01 21:28:25 +0000835 }
drh1d315cf2018-01-01 21:49:43 +0000836 cQuote = quoteChar(zName);
837 appendText(&s, zName, cQuote);
838 while( sqlite3_step(pStmt)==SQLITE_ROW ){
839 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
drh667a2a22018-01-02 00:04:37 +0000840 nRow++;
drh1d315cf2018-01-01 21:49:43 +0000841 appendText(&s, zDiv, 0);
842 zDiv = ",";
843 cQuote = quoteChar(zCol);
844 appendText(&s, zCol, cQuote);
845 }
846 appendText(&s, ")", 0);
drhceba7922018-01-01 21:28:25 +0000847 sqlite3_finalize(pStmt);
drh667a2a22018-01-02 00:04:37 +0000848 if( nRow==0 ){
849 freeText(&s);
850 s.z = 0;
851 }
drh1d315cf2018-01-01 21:49:43 +0000852 return s.z;
drhceba7922018-01-01 21:28:25 +0000853}
854
855/*
drh667a2a22018-01-02 00:04:37 +0000856** SQL function: shell_module_schema(X)
857**
858** Return a fake schema for the table-valued function or eponymous virtual
859** table X.
860*/
861static void shellModuleSchema(
862 sqlite3_context *pCtx,
863 int nVal,
864 sqlite3_value **apVal
865){
866 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
867 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
868 if( zFake ){
dandcfbff92018-01-08 17:05:32 +0000869 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
drh667a2a22018-01-02 00:04:37 +0000870 -1, sqlite3_free);
dandcfbff92018-01-08 17:05:32 +0000871 free(zFake);
drh667a2a22018-01-02 00:04:37 +0000872 }
873}
874
875/*
drh2ce15c32017-07-11 13:34:40 +0000876** SQL function: shell_add_schema(S,X)
877**
878** Add the schema name X to the CREATE statement in S and return the result.
879** Examples:
880**
881** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
882**
883** Also works on
884**
885** CREATE INDEX
886** CREATE UNIQUE INDEX
887** CREATE VIEW
888** CREATE TRIGGER
889** CREATE VIRTUAL TABLE
890**
891** This UDF is used by the .schema command to insert the schema name of
892** attached databases into the middle of the sqlite_master.sql field.
893*/
894static void shellAddSchemaName(
895 sqlite3_context *pCtx,
896 int nVal,
897 sqlite3_value **apVal
898){
899 static const char *aPrefix[] = {
900 "TABLE",
901 "INDEX",
902 "UNIQUE INDEX",
903 "VIEW",
904 "TRIGGER",
905 "VIRTUAL TABLE"
906 };
907 int i = 0;
908 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
909 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
drh667a2a22018-01-02 00:04:37 +0000910 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
drhceba7922018-01-01 21:28:25 +0000911 sqlite3 *db = sqlite3_context_db_handle(pCtx);
drh2ce15c32017-07-11 13:34:40 +0000912 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
drh89997982017-07-11 18:11:33 +0000913 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
drh2ce15c32017-07-11 13:34:40 +0000914 int n = strlen30(aPrefix[i]);
915 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
drhceba7922018-01-01 21:28:25 +0000916 char *z = 0;
drh667a2a22018-01-02 00:04:37 +0000917 char *zFake = 0;
drhceba7922018-01-01 21:28:25 +0000918 if( zSchema ){
919 char cQuote = quoteChar(zSchema);
920 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
921 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
922 }else{
923 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
924 }
drh2ce15c32017-07-11 13:34:40 +0000925 }
drh667a2a22018-01-02 00:04:37 +0000926 if( zName
927 && aPrefix[i][0]=='V'
928 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
929 ){
930 if( z==0 ){
dandcfbff92018-01-08 17:05:32 +0000931 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
drh667a2a22018-01-02 00:04:37 +0000932 }else{
dandcfbff92018-01-08 17:05:32 +0000933 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
drh667a2a22018-01-02 00:04:37 +0000934 }
dandcfbff92018-01-08 17:05:32 +0000935 free(zFake);
drhceba7922018-01-01 21:28:25 +0000936 }
937 if( z ){
938 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
939 return;
940 }
drh2ce15c32017-07-11 13:34:40 +0000941 }
942 }
943 }
944 sqlite3_result_value(pCtx, apVal[0]);
945}
946
947/*
948** The source code for several run-time loadable extensions is inserted
949** below by the ../tool/mkshellc.tcl script. Before processing that included
950** code, we need to override some macros to make the included program code
951** work here in the middle of this regular program.
952*/
953#define SQLITE_EXTENSION_INIT1
drh89997982017-07-11 18:11:33 +0000954#define SQLITE_EXTENSION_INIT2(X) (void)(X)
drh2ce15c32017-07-11 13:34:40 +0000955
mistachkinacae8c32018-01-05 20:08:46 +0000956#if defined(_WIN32) && defined(_MSC_VER)
drh03491a12018-01-07 21:58:17 +0000957INCLUDE test_windirent.h
mistachkindfdfd8c2018-01-04 22:46:08 +0000958INCLUDE test_windirent.c
959#define dirent DIRENT
mistachkindfdfd8c2018-01-04 22:46:08 +0000960#endif
drh2ce15c32017-07-11 13:34:40 +0000961INCLUDE ../ext/misc/shathree.c
962INCLUDE ../ext/misc/fileio.c
drh56eb09b2017-07-11 13:59:07 +0000963INCLUDE ../ext/misc/completion.c
drh8682e122018-01-07 20:38:10 +0000964INCLUDE ../ext/misc/appendvfs.c
dan72afc3c2017-12-05 18:32:40 +0000965#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +0000966INCLUDE ../ext/misc/zipfile.c
dand1b51d42017-12-16 19:11:26 +0000967INCLUDE ../ext/misc/sqlar.c
dan72afc3c2017-12-05 18:32:40 +0000968#endif
dan43efc182017-12-19 17:42:13 +0000969INCLUDE ../ext/expert/sqlite3expert.h
970INCLUDE ../ext/expert/sqlite3expert.c
drh2ce15c32017-07-11 13:34:40 +0000971
972#if defined(SQLITE_ENABLE_SESSION)
973/*
974** State information for a single open session
975*/
976typedef struct OpenSession OpenSession;
977struct OpenSession {
978 char *zName; /* Symbolic name for this session */
979 int nFilter; /* Number of xFilter rejection GLOB patterns */
980 char **azFilter; /* Array of xFilter rejection GLOB patterns */
981 sqlite3_session *p; /* The open session */
982};
983#endif
984
985/*
986** Shell output mode information from before ".explain on",
987** saved so that it can be restored by ".explain off"
988*/
989typedef struct SavedModeInfo SavedModeInfo;
990struct SavedModeInfo {
991 int valid; /* Is there legit data in here? */
992 int mode; /* Mode prior to ".explain on" */
993 int showHeader; /* The ".header" setting prior to ".explain on" */
994 int colWidth[100]; /* Column widths prior to ".explain on" */
995};
996
dan43efc182017-12-19 17:42:13 +0000997typedef struct ExpertInfo ExpertInfo;
998struct ExpertInfo {
999 sqlite3expert *pExpert;
1000 int bVerbose;
1001};
1002
drh2ce15c32017-07-11 13:34:40 +00001003/*
1004** State information about the database connection is contained in an
1005** instance of the following structure.
1006*/
1007typedef struct ShellState ShellState;
1008struct ShellState {
1009 sqlite3 *db; /* The database */
drh1fa6d9f2018-01-06 21:46:01 +00001010 u8 autoExplain; /* Automatically turn on .explain mode */
1011 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1012 u8 statsOn; /* True to display memory stats before each finalize */
1013 u8 scanstatsOn; /* True to display scan stats before each finalize */
1014 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
drh2ce15c32017-07-11 13:34:40 +00001015 int outCount; /* Revert to stdout when reaching zero */
1016 int cnt; /* Number of records displayed so far */
1017 FILE *out; /* Write results here */
1018 FILE *traceOut; /* Output for sqlite3_trace() */
1019 int nErr; /* Number of errors seen */
1020 int mode; /* An output mode setting */
1021 int cMode; /* temporary output mode for the current query */
1022 int normalMode; /* Output mode before ".explain on" */
1023 int writableSchema; /* True if PRAGMA writable_schema=ON */
1024 int showHeader; /* True to show column names in List or Column mode */
1025 int nCheck; /* Number of ".check" commands run */
1026 unsigned shellFlgs; /* Various flags */
1027 char *zDestTable; /* Name of destination table when MODE_Insert */
1028 char zTestcase[30]; /* Name of current test case */
1029 char colSeparator[20]; /* Column separator character for several modes */
1030 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
1031 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[] */
1044#if defined(SQLITE_ENABLE_SESSION)
1045 int nSession; /* Number of active sessions */
1046 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1047#endif
dan43efc182017-12-19 17:42:13 +00001048 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
drh2ce15c32017-07-11 13:34:40 +00001049};
1050
drh1fa6d9f2018-01-06 21:46:01 +00001051
drhada70452017-12-21 21:02:27 +00001052/* Allowed values for ShellState.autoEQP
1053*/
1054#define AUTOEQP_off 0
1055#define AUTOEQP_on 1
1056#define AUTOEQP_trigger 2
1057#define AUTOEQP_full 3
1058
drh1fa6d9f2018-01-06 21:46:01 +00001059/* Allowed values for ShellState.openMode
1060*/
1061#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1062#define SHELL_OPEN_NORMAL 1 /* Normal database file */
1063#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1064#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1065
drh2ce15c32017-07-11 13:34:40 +00001066/*
1067** These are the allowed shellFlgs values
1068*/
drhb2a0f752017-08-28 15:51:35 +00001069#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1070#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1071#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1072#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1073#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1074#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1075#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
drh2ce15c32017-07-11 13:34:40 +00001076
1077/*
1078** Macros for testing and setting shellFlgs
1079*/
1080#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1081#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1082#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1083
1084/*
1085** These are the allowed modes.
1086*/
1087#define MODE_Line 0 /* One column per line. Blank line between records */
1088#define MODE_Column 1 /* One record per line in neat columns */
1089#define MODE_List 2 /* One record per line with a separator */
1090#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1091#define MODE_Html 4 /* Generate an XHTML table */
1092#define MODE_Insert 5 /* Generate SQL "insert" statements */
1093#define MODE_Quote 6 /* Quote values as for SQL */
1094#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1095#define MODE_Csv 8 /* Quote strings, numbers are plain */
1096#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1097#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1098#define MODE_Pretty 11 /* Pretty-print schemas */
1099
1100static const char *modeDescr[] = {
1101 "line",
1102 "column",
1103 "list",
1104 "semi",
1105 "html",
1106 "insert",
1107 "quote",
1108 "tcl",
1109 "csv",
1110 "explain",
1111 "ascii",
1112 "prettyprint",
1113};
1114
1115/*
1116** These are the column/row/line separators used by the various
1117** import/export modes.
1118*/
1119#define SEP_Column "|"
1120#define SEP_Row "\n"
1121#define SEP_Tab "\t"
1122#define SEP_Space " "
1123#define SEP_Comma ","
1124#define SEP_CrLf "\r\n"
1125#define SEP_Unit "\x1F"
1126#define SEP_Record "\x1E"
1127
1128/*
drh2ce15c32017-07-11 13:34:40 +00001129** A callback for the sqlite3_log() interface.
1130*/
1131static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1132 ShellState *p = (ShellState*)pArg;
1133 if( p->pLog==0 ) return;
1134 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1135 fflush(p->pLog);
1136}
1137
1138/*
drh634c70f2018-01-10 16:50:18 +00001139** SQL function: shell_putsnl(X)
1140**
1141** Write the text X to the screen (or whatever output is being directed)
1142** adding a newline at the end, and then return X.
1143*/
1144static void shellPutsFunc(
1145 sqlite3_context *pCtx,
1146 int nVal,
1147 sqlite3_value **apVal
1148){
1149 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
1150 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1151 sqlite3_result_value(pCtx, apVal[0]);
1152}
1153
1154/*
drh2ce15c32017-07-11 13:34:40 +00001155** Output the given string as a hex-encoded blob (eg. X'1234' )
1156*/
1157static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1158 int i;
1159 char *zBlob = (char *)pBlob;
1160 raw_printf(out,"X'");
1161 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1162 raw_printf(out,"'");
1163}
1164
1165/*
1166** Find a string that is not found anywhere in z[]. Return a pointer
1167** to that string.
1168**
1169** Try to use zA and zB first. If both of those are already found in z[]
1170** then make up some string and store it in the buffer zBuf.
1171*/
1172static const char *unused_string(
1173 const char *z, /* Result must not appear anywhere in z */
1174 const char *zA, const char *zB, /* Try these first */
1175 char *zBuf /* Space to store a generated string */
1176){
1177 unsigned i = 0;
1178 if( strstr(z, zA)==0 ) return zA;
1179 if( strstr(z, zB)==0 ) return zB;
1180 do{
1181 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1182 }while( strstr(z,zBuf)!=0 );
1183 return zBuf;
1184}
1185
1186/*
1187** Output the given string as a quoted string using SQL quoting conventions.
1188**
1189** See also: output_quoted_escaped_string()
1190*/
1191static void output_quoted_string(FILE *out, const char *z){
1192 int i;
1193 char c;
1194 setBinaryMode(out, 1);
1195 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1196 if( c==0 ){
1197 utf8_printf(out,"'%s'",z);
1198 }else{
1199 raw_printf(out, "'");
1200 while( *z ){
1201 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1202 if( c=='\'' ) i++;
1203 if( i ){
1204 utf8_printf(out, "%.*s", i, z);
1205 z += i;
1206 }
1207 if( c=='\'' ){
1208 raw_printf(out, "'");
1209 continue;
1210 }
1211 if( c==0 ){
1212 break;
1213 }
1214 z++;
1215 }
1216 raw_printf(out, "'");
1217 }
1218 setTextMode(out, 1);
1219}
1220
1221/*
1222** Output the given string as a quoted string using SQL quoting conventions.
1223** Additionallly , escape the "\n" and "\r" characters so that they do not
1224** get corrupted by end-of-line translation facilities in some operating
1225** systems.
1226**
1227** This is like output_quoted_string() but with the addition of the \r\n
1228** escape mechanism.
1229*/
1230static void output_quoted_escaped_string(FILE *out, const char *z){
1231 int i;
1232 char c;
1233 setBinaryMode(out, 1);
1234 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1235 if( c==0 ){
1236 utf8_printf(out,"'%s'",z);
1237 }else{
1238 const char *zNL = 0;
1239 const char *zCR = 0;
1240 int nNL = 0;
1241 int nCR = 0;
1242 char zBuf1[20], zBuf2[20];
1243 for(i=0; z[i]; i++){
1244 if( z[i]=='\n' ) nNL++;
1245 if( z[i]=='\r' ) nCR++;
1246 }
1247 if( nNL ){
1248 raw_printf(out, "replace(");
1249 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1250 }
1251 if( nCR ){
1252 raw_printf(out, "replace(");
1253 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1254 }
1255 raw_printf(out, "'");
1256 while( *z ){
1257 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1258 if( c=='\'' ) i++;
1259 if( i ){
1260 utf8_printf(out, "%.*s", i, z);
1261 z += i;
1262 }
1263 if( c=='\'' ){
1264 raw_printf(out, "'");
1265 continue;
1266 }
1267 if( c==0 ){
1268 break;
1269 }
1270 z++;
1271 if( c=='\n' ){
1272 raw_printf(out, "%s", zNL);
1273 continue;
1274 }
1275 raw_printf(out, "%s", zCR);
1276 }
1277 raw_printf(out, "'");
1278 if( nCR ){
1279 raw_printf(out, ",'%s',char(13))", zCR);
1280 }
1281 if( nNL ){
1282 raw_printf(out, ",'%s',char(10))", zNL);
1283 }
1284 }
1285 setTextMode(out, 1);
1286}
1287
1288/*
1289** Output the given string as a quoted according to C or TCL quoting rules.
1290*/
1291static void output_c_string(FILE *out, const char *z){
1292 unsigned int c;
1293 fputc('"', out);
1294 while( (c = *(z++))!=0 ){
1295 if( c=='\\' ){
1296 fputc(c, out);
1297 fputc(c, out);
1298 }else if( c=='"' ){
1299 fputc('\\', out);
1300 fputc('"', out);
1301 }else if( c=='\t' ){
1302 fputc('\\', out);
1303 fputc('t', out);
1304 }else if( c=='\n' ){
1305 fputc('\\', out);
1306 fputc('n', out);
1307 }else if( c=='\r' ){
1308 fputc('\\', out);
1309 fputc('r', out);
1310 }else if( !isprint(c&0xff) ){
1311 raw_printf(out, "\\%03o", c&0xff);
1312 }else{
1313 fputc(c, out);
1314 }
1315 }
1316 fputc('"', out);
1317}
1318
1319/*
1320** Output the given string with characters that are special to
1321** HTML escaped.
1322*/
1323static void output_html_string(FILE *out, const char *z){
1324 int i;
1325 if( z==0 ) z = "";
1326 while( *z ){
1327 for(i=0; z[i]
1328 && z[i]!='<'
1329 && z[i]!='&'
1330 && z[i]!='>'
1331 && z[i]!='\"'
1332 && z[i]!='\'';
1333 i++){}
1334 if( i>0 ){
1335 utf8_printf(out,"%.*s",i,z);
1336 }
1337 if( z[i]=='<' ){
1338 raw_printf(out,"&lt;");
1339 }else if( z[i]=='&' ){
1340 raw_printf(out,"&amp;");
1341 }else if( z[i]=='>' ){
1342 raw_printf(out,"&gt;");
1343 }else if( z[i]=='\"' ){
1344 raw_printf(out,"&quot;");
1345 }else if( z[i]=='\'' ){
1346 raw_printf(out,"&#39;");
1347 }else{
1348 break;
1349 }
1350 z += i + 1;
1351 }
1352}
1353
1354/*
1355** If a field contains any character identified by a 1 in the following
1356** array, then the string must be quoted for CSV.
1357*/
1358static const char needCsvQuote[] = {
1359 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1360 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1361 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1362 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1363 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1364 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1365 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1366 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1367 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1368 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1369 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1370 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1371 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1372 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1373 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1374 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1375};
1376
1377/*
1378** Output a single term of CSV. Actually, p->colSeparator is used for
1379** the separator, which may or may not be a comma. p->nullValue is
1380** the null value. Strings are quoted if necessary. The separator
1381** is only issued if bSep is true.
1382*/
1383static void output_csv(ShellState *p, const char *z, int bSep){
1384 FILE *out = p->out;
1385 if( z==0 ){
1386 utf8_printf(out,"%s",p->nullValue);
1387 }else{
1388 int i;
1389 int nSep = strlen30(p->colSeparator);
1390 for(i=0; z[i]; i++){
1391 if( needCsvQuote[((unsigned char*)z)[i]]
1392 || (z[i]==p->colSeparator[0] &&
1393 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1394 i = 0;
1395 break;
1396 }
1397 }
1398 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001399 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1400 utf8_printf(out, "%s", zQuoted);
1401 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001402 }else{
1403 utf8_printf(out, "%s", z);
1404 }
1405 }
1406 if( bSep ){
1407 utf8_printf(p->out, "%s", p->colSeparator);
1408 }
1409}
1410
drh2ce15c32017-07-11 13:34:40 +00001411/*
1412** This routine runs when the user presses Ctrl-C
1413*/
1414static void interrupt_handler(int NotUsed){
1415 UNUSED_PARAMETER(NotUsed);
1416 seenInterrupt++;
1417 if( seenInterrupt>2 ) exit(1);
1418 if( globalDb ) sqlite3_interrupt(globalDb);
1419}
mistachkinb4bab902017-10-27 17:09:44 +00001420
1421#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1422/*
1423** This routine runs for console events (e.g. Ctrl-C) on Win32
1424*/
1425static BOOL WINAPI ConsoleCtrlHandler(
1426 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1427){
1428 if( dwCtrlType==CTRL_C_EVENT ){
1429 interrupt_handler(0);
1430 return TRUE;
1431 }
1432 return FALSE;
1433}
drh2ce15c32017-07-11 13:34:40 +00001434#endif
1435
1436#ifndef SQLITE_OMIT_AUTHORIZATION
1437/*
1438** When the ".auth ON" is set, the following authorizer callback is
1439** invoked. It always returns SQLITE_OK.
1440*/
1441static int shellAuth(
1442 void *pClientData,
1443 int op,
1444 const char *zA1,
1445 const char *zA2,
1446 const char *zA3,
1447 const char *zA4
1448){
1449 ShellState *p = (ShellState*)pClientData;
1450 static const char *azAction[] = { 0,
1451 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1452 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1453 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1454 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1455 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1456 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1457 "PRAGMA", "READ", "SELECT",
1458 "TRANSACTION", "UPDATE", "ATTACH",
1459 "DETACH", "ALTER_TABLE", "REINDEX",
1460 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1461 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1462 };
1463 int i;
1464 const char *az[4];
1465 az[0] = zA1;
1466 az[1] = zA2;
1467 az[2] = zA3;
1468 az[3] = zA4;
1469 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1470 for(i=0; i<4; i++){
1471 raw_printf(p->out, " ");
1472 if( az[i] ){
1473 output_c_string(p->out, az[i]);
1474 }else{
1475 raw_printf(p->out, "NULL");
1476 }
1477 }
1478 raw_printf(p->out, "\n");
1479 return SQLITE_OK;
1480}
1481#endif
1482
1483/*
1484** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1485**
1486** This routine converts some CREATE TABLE statements for shadow tables
1487** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1488*/
1489static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1490 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1491 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1492 }else{
1493 utf8_printf(out, "%s%s", z, zTail);
1494 }
1495}
1496static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1497 char c = z[n];
1498 z[n] = 0;
1499 printSchemaLine(out, z, zTail);
1500 z[n] = c;
1501}
1502
1503/*
drh11be81d2018-01-06 15:46:20 +00001504** Return true if string z[] has nothing but whitespace and comments to the
1505** end of the first line.
1506*/
1507static int wsToEol(const char *z){
1508 int i;
1509 for(i=0; z[i]; i++){
1510 if( z[i]=='\n' ) return 1;
1511 if( IsSpace(z[i]) ) continue;
1512 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1513 return 0;
1514 }
1515 return 1;
1516}
1517
1518
1519/*
drh2ce15c32017-07-11 13:34:40 +00001520** This is the callback routine that the shell
1521** invokes for each row of a query result.
1522*/
1523static int shell_callback(
1524 void *pArg,
1525 int nArg, /* Number of result columns */
1526 char **azArg, /* Text of each result column */
1527 char **azCol, /* Column names */
1528 int *aiType /* Column types */
1529){
1530 int i;
1531 ShellState *p = (ShellState*)pArg;
1532
drhb3c45232017-08-28 14:33:27 +00001533 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001534 switch( p->cMode ){
1535 case MODE_Line: {
1536 int w = 5;
1537 if( azArg==0 ) break;
1538 for(i=0; i<nArg; i++){
1539 int len = strlen30(azCol[i] ? azCol[i] : "");
1540 if( len>w ) w = len;
1541 }
1542 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1543 for(i=0; i<nArg; i++){
1544 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1545 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1546 }
1547 break;
1548 }
1549 case MODE_Explain:
1550 case MODE_Column: {
1551 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1552 const int *colWidth;
1553 int showHdr;
1554 char *rowSep;
1555 if( p->cMode==MODE_Column ){
1556 colWidth = p->colWidth;
1557 showHdr = p->showHeader;
1558 rowSep = p->rowSeparator;
1559 }else{
1560 colWidth = aExplainWidths;
1561 showHdr = 1;
1562 rowSep = SEP_Row;
1563 }
1564 if( p->cnt++==0 ){
1565 for(i=0; i<nArg; i++){
1566 int w, n;
1567 if( i<ArraySize(p->colWidth) ){
1568 w = colWidth[i];
1569 }else{
1570 w = 0;
1571 }
1572 if( w==0 ){
1573 w = strlenChar(azCol[i] ? azCol[i] : "");
1574 if( w<10 ) w = 10;
1575 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1576 if( w<n ) w = n;
1577 }
1578 if( i<ArraySize(p->actualWidth) ){
1579 p->actualWidth[i] = w;
1580 }
1581 if( showHdr ){
1582 utf8_width_print(p->out, w, azCol[i]);
1583 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1584 }
1585 }
1586 if( showHdr ){
1587 for(i=0; i<nArg; i++){
1588 int w;
1589 if( i<ArraySize(p->actualWidth) ){
1590 w = p->actualWidth[i];
1591 if( w<0 ) w = -w;
1592 }else{
1593 w = 10;
1594 }
1595 utf8_printf(p->out,"%-*.*s%s",w,w,
1596 "----------------------------------------------------------"
1597 "----------------------------------------------------------",
1598 i==nArg-1 ? rowSep : " ");
1599 }
1600 }
1601 }
1602 if( azArg==0 ) break;
1603 for(i=0; i<nArg; i++){
1604 int w;
1605 if( i<ArraySize(p->actualWidth) ){
1606 w = p->actualWidth[i];
1607 }else{
1608 w = 10;
1609 }
1610 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1611 w = strlenChar(azArg[i]);
1612 }
1613 if( i==1 && p->aiIndent && p->pStmt ){
1614 if( p->iIndent<p->nIndent ){
1615 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1616 }
1617 p->iIndent++;
1618 }
1619 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1620 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1621 }
1622 break;
1623 }
1624 case MODE_Semi: { /* .schema and .fullschema output */
1625 printSchemaLine(p->out, azArg[0], ";\n");
1626 break;
1627 }
1628 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1629 char *z;
1630 int j;
1631 int nParen = 0;
1632 char cEnd = 0;
1633 char c;
1634 int nLine = 0;
1635 assert( nArg==1 );
1636 if( azArg[0]==0 ) break;
1637 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1638 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1639 ){
1640 utf8_printf(p->out, "%s;\n", azArg[0]);
1641 break;
1642 }
1643 z = sqlite3_mprintf("%s", azArg[0]);
1644 j = 0;
1645 for(i=0; IsSpace(z[i]); i++){}
1646 for(; (c = z[i])!=0; i++){
1647 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001648 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001649 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1650 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1651 j--;
1652 }
1653 z[j++] = c;
1654 }
1655 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1656 z[j] = 0;
1657 if( strlen30(z)>=79 ){
drh11be81d2018-01-06 15:46:20 +00001658 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001659 if( c==cEnd ){
1660 cEnd = 0;
1661 }else if( c=='"' || c=='\'' || c=='`' ){
1662 cEnd = c;
1663 }else if( c=='[' ){
1664 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001665 }else if( c=='-' && z[i+1]=='-' ){
1666 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001667 }else if( c=='(' ){
1668 nParen++;
1669 }else if( c==')' ){
1670 nParen--;
1671 if( nLine>0 && nParen==0 && j>0 ){
1672 printSchemaLineN(p->out, z, j, "\n");
1673 j = 0;
1674 }
1675 }
1676 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001677 if( nParen==1 && cEnd==0
1678 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1679 ){
drh2ce15c32017-07-11 13:34:40 +00001680 if( c=='\n' ) j--;
1681 printSchemaLineN(p->out, z, j, "\n ");
1682 j = 0;
1683 nLine++;
1684 while( IsSpace(z[i+1]) ){ i++; }
1685 }
1686 }
1687 z[j] = 0;
1688 }
1689 printSchemaLine(p->out, z, ";\n");
1690 sqlite3_free(z);
1691 break;
1692 }
1693 case MODE_List: {
1694 if( p->cnt++==0 && p->showHeader ){
1695 for(i=0; i<nArg; i++){
1696 utf8_printf(p->out,"%s%s",azCol[i],
1697 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1698 }
1699 }
1700 if( azArg==0 ) break;
1701 for(i=0; i<nArg; i++){
1702 char *z = azArg[i];
1703 if( z==0 ) z = p->nullValue;
1704 utf8_printf(p->out, "%s", z);
1705 if( i<nArg-1 ){
1706 utf8_printf(p->out, "%s", p->colSeparator);
1707 }else{
1708 utf8_printf(p->out, "%s", p->rowSeparator);
1709 }
1710 }
1711 break;
1712 }
1713 case MODE_Html: {
1714 if( p->cnt++==0 && p->showHeader ){
1715 raw_printf(p->out,"<TR>");
1716 for(i=0; i<nArg; i++){
1717 raw_printf(p->out,"<TH>");
1718 output_html_string(p->out, azCol[i]);
1719 raw_printf(p->out,"</TH>\n");
1720 }
1721 raw_printf(p->out,"</TR>\n");
1722 }
1723 if( azArg==0 ) break;
1724 raw_printf(p->out,"<TR>");
1725 for(i=0; i<nArg; i++){
1726 raw_printf(p->out,"<TD>");
1727 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1728 raw_printf(p->out,"</TD>\n");
1729 }
1730 raw_printf(p->out,"</TR>\n");
1731 break;
1732 }
1733 case MODE_Tcl: {
1734 if( p->cnt++==0 && p->showHeader ){
1735 for(i=0; i<nArg; i++){
1736 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1737 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1738 }
1739 utf8_printf(p->out, "%s", p->rowSeparator);
1740 }
1741 if( azArg==0 ) break;
1742 for(i=0; i<nArg; i++){
1743 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1744 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1745 }
1746 utf8_printf(p->out, "%s", p->rowSeparator);
1747 break;
1748 }
1749 case MODE_Csv: {
1750 setBinaryMode(p->out, 1);
1751 if( p->cnt++==0 && p->showHeader ){
1752 for(i=0; i<nArg; i++){
1753 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1754 }
1755 utf8_printf(p->out, "%s", p->rowSeparator);
1756 }
1757 if( nArg>0 ){
1758 for(i=0; i<nArg; i++){
1759 output_csv(p, azArg[i], i<nArg-1);
1760 }
1761 utf8_printf(p->out, "%s", p->rowSeparator);
1762 }
1763 setTextMode(p->out, 1);
1764 break;
1765 }
1766 case MODE_Insert: {
1767 if( azArg==0 ) break;
1768 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
1769 if( p->showHeader ){
1770 raw_printf(p->out,"(");
1771 for(i=0; i<nArg; i++){
1772 if( i>0 ) raw_printf(p->out, ",");
1773 if( quoteChar(azCol[i]) ){
1774 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
1775 utf8_printf(p->out, "%s", z);
1776 sqlite3_free(z);
1777 }else{
1778 raw_printf(p->out, "%s", azCol[i]);
1779 }
1780 }
1781 raw_printf(p->out,")");
1782 }
1783 p->cnt++;
1784 for(i=0; i<nArg; i++){
1785 raw_printf(p->out, i>0 ? "," : " VALUES(");
1786 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1787 utf8_printf(p->out,"NULL");
1788 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1789 if( ShellHasFlag(p, SHFLG_Newlines) ){
1790 output_quoted_string(p->out, azArg[i]);
1791 }else{
1792 output_quoted_escaped_string(p->out, azArg[i]);
1793 }
1794 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1795 utf8_printf(p->out,"%s", azArg[i]);
1796 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1797 char z[50];
1798 double r = sqlite3_column_double(p->pStmt, i);
1799 sqlite3_snprintf(50,z,"%!.20g", r);
1800 raw_printf(p->out, "%s", z);
1801 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1802 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1803 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1804 output_hex_blob(p->out, pBlob, nBlob);
1805 }else if( isNumber(azArg[i], 0) ){
1806 utf8_printf(p->out,"%s", azArg[i]);
1807 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
1808 output_quoted_string(p->out, azArg[i]);
1809 }else{
1810 output_quoted_escaped_string(p->out, azArg[i]);
1811 }
1812 }
1813 raw_printf(p->out,");\n");
1814 break;
1815 }
1816 case MODE_Quote: {
1817 if( azArg==0 ) break;
1818 if( p->cnt==0 && p->showHeader ){
1819 for(i=0; i<nArg; i++){
1820 if( i>0 ) raw_printf(p->out, ",");
1821 output_quoted_string(p->out, azCol[i]);
1822 }
1823 raw_printf(p->out,"\n");
1824 }
1825 p->cnt++;
1826 for(i=0; i<nArg; i++){
1827 if( i>0 ) raw_printf(p->out, ",");
1828 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1829 utf8_printf(p->out,"NULL");
1830 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1831 output_quoted_string(p->out, azArg[i]);
1832 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1833 utf8_printf(p->out,"%s", azArg[i]);
1834 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1835 char z[50];
1836 double r = sqlite3_column_double(p->pStmt, i);
1837 sqlite3_snprintf(50,z,"%!.20g", r);
1838 raw_printf(p->out, "%s", z);
1839 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1840 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1841 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1842 output_hex_blob(p->out, pBlob, nBlob);
1843 }else if( isNumber(azArg[i], 0) ){
1844 utf8_printf(p->out,"%s", azArg[i]);
1845 }else{
1846 output_quoted_string(p->out, azArg[i]);
1847 }
1848 }
1849 raw_printf(p->out,"\n");
1850 break;
1851 }
1852 case MODE_Ascii: {
1853 if( p->cnt++==0 && p->showHeader ){
1854 for(i=0; i<nArg; i++){
1855 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1856 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
1857 }
1858 utf8_printf(p->out, "%s", p->rowSeparator);
1859 }
1860 if( azArg==0 ) break;
1861 for(i=0; i<nArg; i++){
1862 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1863 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
1864 }
1865 utf8_printf(p->out, "%s", p->rowSeparator);
1866 break;
1867 }
1868 }
1869 return 0;
1870}
1871
1872/*
1873** This is the callback routine that the SQLite library
1874** invokes for each row of a query result.
1875*/
1876static int callback(void *pArg, int nArg, char **azArg, char **azCol){
1877 /* since we don't have type info, call the shell_callback with a NULL value */
1878 return shell_callback(pArg, nArg, azArg, azCol, NULL);
1879}
1880
1881/*
1882** This is the callback routine from sqlite3_exec() that appends all
1883** output onto the end of a ShellText object.
1884*/
1885static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
1886 ShellText *p = (ShellText*)pArg;
1887 int i;
1888 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00001889 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001890 if( p->n ) appendText(p, "|", 0);
1891 for(i=0; i<nArg; i++){
1892 if( i ) appendText(p, ",", 0);
1893 if( azArg[i] ) appendText(p, azArg[i], 0);
1894 }
1895 return 0;
1896}
1897
1898/*
1899** Generate an appropriate SELFTEST table in the main database.
1900*/
1901static void createSelftestTable(ShellState *p){
1902 char *zErrMsg = 0;
1903 sqlite3_exec(p->db,
1904 "SAVEPOINT selftest_init;\n"
1905 "CREATE TABLE IF NOT EXISTS selftest(\n"
1906 " tno INTEGER PRIMARY KEY,\n" /* Test number */
1907 " op TEXT,\n" /* Operator: memo run */
1908 " cmd TEXT,\n" /* Command text */
1909 " ans TEXT\n" /* Desired answer */
1910 ");"
1911 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
1912 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
1913 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
1914 " 'memo','Tests generated by --init');\n"
1915 "INSERT INTO [_shell$self]\n"
1916 " SELECT 'run',\n"
1917 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
1918 "FROM sqlite_master ORDER BY 2'',224))',\n"
1919 " hex(sha3_query('SELECT type,name,tbl_name,sql "
1920 "FROM sqlite_master ORDER BY 2',224));\n"
1921 "INSERT INTO [_shell$self]\n"
1922 " SELECT 'run',"
1923 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
1924 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
1925 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
1926 " FROM (\n"
1927 " SELECT name FROM sqlite_master\n"
1928 " WHERE type='table'\n"
1929 " AND name<>'selftest'\n"
1930 " AND coalesce(rootpage,0)>0\n"
1931 " )\n"
1932 " ORDER BY name;\n"
1933 "INSERT INTO [_shell$self]\n"
1934 " VALUES('run','PRAGMA integrity_check','ok');\n"
1935 "INSERT INTO selftest(tno,op,cmd,ans)"
1936 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
1937 "DROP TABLE [_shell$self];"
1938 ,0,0,&zErrMsg);
1939 if( zErrMsg ){
1940 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
1941 sqlite3_free(zErrMsg);
1942 }
1943 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
1944}
1945
1946
1947/*
1948** Set the destination table field of the ShellState structure to
1949** the name of the table given. Escape any quote characters in the
1950** table name.
1951*/
1952static void set_table_name(ShellState *p, const char *zName){
1953 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00001954 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00001955 char *z;
1956
1957 if( p->zDestTable ){
1958 free(p->zDestTable);
1959 p->zDestTable = 0;
1960 }
1961 if( zName==0 ) return;
1962 cQuote = quoteChar(zName);
1963 n = strlen30(zName);
1964 if( cQuote ) n += n+2;
1965 z = p->zDestTable = malloc( n+1 );
1966 if( z==0 ){
1967 raw_printf(stderr,"Error: out of memory\n");
1968 exit(1);
1969 }
1970 n = 0;
1971 if( cQuote ) z[n++] = cQuote;
1972 for(i=0; zName[i]; i++){
1973 z[n++] = zName[i];
1974 if( zName[i]==cQuote ) z[n++] = cQuote;
1975 }
1976 if( cQuote ) z[n++] = cQuote;
1977 z[n] = 0;
1978}
1979
1980
1981/*
1982** Execute a query statement that will generate SQL output. Print
1983** the result columns, comma-separated, on a line and then add a
1984** semicolon terminator to the end of that line.
1985**
1986** If the number of columns is 1 and that column contains text "--"
1987** then write the semicolon on a separate line. That way, if a
1988** "--" comment occurs at the end of the statement, the comment
1989** won't consume the semicolon terminator.
1990*/
1991static int run_table_dump_query(
1992 ShellState *p, /* Query context */
1993 const char *zSelect, /* SELECT statement to extract content */
1994 const char *zFirstRow /* Print before first row, if not NULL */
1995){
1996 sqlite3_stmt *pSelect;
1997 int rc;
1998 int nResult;
1999 int i;
2000 const char *z;
2001 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2002 if( rc!=SQLITE_OK || !pSelect ){
2003 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2004 sqlite3_errmsg(p->db));
2005 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2006 return rc;
2007 }
2008 rc = sqlite3_step(pSelect);
2009 nResult = sqlite3_column_count(pSelect);
2010 while( rc==SQLITE_ROW ){
2011 if( zFirstRow ){
2012 utf8_printf(p->out, "%s", zFirstRow);
2013 zFirstRow = 0;
2014 }
2015 z = (const char*)sqlite3_column_text(pSelect, 0);
2016 utf8_printf(p->out, "%s", z);
2017 for(i=1; i<nResult; i++){
2018 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2019 }
2020 if( z==0 ) z = "";
2021 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2022 if( z[0] ){
2023 raw_printf(p->out, "\n;\n");
2024 }else{
2025 raw_printf(p->out, ";\n");
2026 }
2027 rc = sqlite3_step(pSelect);
2028 }
2029 rc = sqlite3_finalize(pSelect);
2030 if( rc!=SQLITE_OK ){
2031 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2032 sqlite3_errmsg(p->db));
2033 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2034 }
2035 return rc;
2036}
2037
2038/*
2039** Allocate space and save off current error string.
2040*/
2041static char *save_err_msg(
2042 sqlite3 *db /* Database to query */
2043){
2044 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2045 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2046 if( zErrMsg ){
2047 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2048 }
2049 return zErrMsg;
2050}
2051
2052#ifdef __linux__
2053/*
2054** Attempt to display I/O stats on Linux using /proc/PID/io
2055*/
2056static void displayLinuxIoStats(FILE *out){
2057 FILE *in;
2058 char z[200];
2059 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2060 in = fopen(z, "rb");
2061 if( in==0 ) return;
2062 while( fgets(z, sizeof(z), in)!=0 ){
2063 static const struct {
2064 const char *zPattern;
2065 const char *zDesc;
2066 } aTrans[] = {
2067 { "rchar: ", "Bytes received by read():" },
2068 { "wchar: ", "Bytes sent to write():" },
2069 { "syscr: ", "Read() system calls:" },
2070 { "syscw: ", "Write() system calls:" },
2071 { "read_bytes: ", "Bytes read from storage:" },
2072 { "write_bytes: ", "Bytes written to storage:" },
2073 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2074 };
2075 int i;
2076 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00002077 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00002078 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2079 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2080 break;
2081 }
2082 }
2083 }
2084 fclose(in);
2085}
2086#endif
2087
2088/*
2089** Display a single line of status using 64-bit values.
2090*/
2091static void displayStatLine(
2092 ShellState *p, /* The shell context */
2093 char *zLabel, /* Label for this one line */
2094 char *zFormat, /* Format for the result */
2095 int iStatusCtrl, /* Which status to display */
2096 int bReset /* True to reset the stats */
2097){
2098 sqlite3_int64 iCur = -1;
2099 sqlite3_int64 iHiwtr = -1;
2100 int i, nPercent;
2101 char zLine[200];
2102 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2103 for(i=0, nPercent=0; zFormat[i]; i++){
2104 if( zFormat[i]=='%' ) nPercent++;
2105 }
2106 if( nPercent>1 ){
2107 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2108 }else{
2109 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2110 }
2111 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2112}
2113
2114/*
2115** Display memory stats.
2116*/
2117static int display_stats(
2118 sqlite3 *db, /* Database to query */
2119 ShellState *pArg, /* Pointer to ShellState */
2120 int bReset /* True to reset the stats */
2121){
2122 int iCur;
2123 int iHiwtr;
2124
2125 if( pArg && pArg->out ){
2126 displayStatLine(pArg, "Memory Used:",
2127 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2128 displayStatLine(pArg, "Number of Outstanding Allocations:",
2129 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2130 if( pArg->shellFlgs & SHFLG_Pagecache ){
2131 displayStatLine(pArg, "Number of Pcache Pages Used:",
2132 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2133 }
2134 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2135 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
drh2ce15c32017-07-11 13:34:40 +00002136 displayStatLine(pArg, "Largest Allocation:",
2137 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2138 displayStatLine(pArg, "Largest Pcache Allocation:",
2139 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
drh2ce15c32017-07-11 13:34:40 +00002140#ifdef YYTRACKMAXSTACKDEPTH
2141 displayStatLine(pArg, "Deepest Parser Stack:",
2142 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2143#endif
2144 }
2145
2146 if( pArg && pArg->out && db ){
2147 if( pArg->shellFlgs & SHFLG_Lookaside ){
2148 iHiwtr = iCur = -1;
2149 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2150 &iCur, &iHiwtr, bReset);
2151 raw_printf(pArg->out,
2152 "Lookaside Slots Used: %d (max %d)\n",
2153 iCur, iHiwtr);
2154 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2155 &iCur, &iHiwtr, bReset);
2156 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2157 iHiwtr);
2158 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2159 &iCur, &iHiwtr, bReset);
2160 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2161 iHiwtr);
2162 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2163 &iCur, &iHiwtr, bReset);
2164 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2165 iHiwtr);
2166 }
2167 iHiwtr = iCur = -1;
2168 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2169 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2170 iCur);
2171 iHiwtr = iCur = -1;
2172 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2173 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2174 iHiwtr = iCur = -1;
2175 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2176 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2177 iHiwtr = iCur = -1;
2178 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2179 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2180 iHiwtr = iCur = -1;
2181 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2182 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2183 iCur);
2184 iHiwtr = iCur = -1;
2185 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2186 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2187 iCur);
2188 }
2189
2190 if( pArg && pArg->out && db && pArg->pStmt ){
2191 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2192 bReset);
2193 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2194 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2195 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2196 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2197 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2198 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2199 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2200 }
2201
2202#ifdef __linux__
2203 displayLinuxIoStats(pArg->out);
2204#endif
2205
2206 /* Do not remove this machine readable comment: extra-stats-output-here */
2207
2208 return 0;
2209}
2210
2211/*
2212** Display scan stats.
2213*/
2214static void display_scanstats(
2215 sqlite3 *db, /* Database to query */
2216 ShellState *pArg /* Pointer to ShellState */
2217){
2218#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2219 UNUSED_PARAMETER(db);
2220 UNUSED_PARAMETER(pArg);
2221#else
2222 int i, k, n, mx;
2223 raw_printf(pArg->out, "-------- scanstats --------\n");
2224 mx = 0;
2225 for(k=0; k<=mx; k++){
2226 double rEstLoop = 1.0;
2227 for(i=n=0; 1; i++){
2228 sqlite3_stmt *p = pArg->pStmt;
2229 sqlite3_int64 nLoop, nVisit;
2230 double rEst;
2231 int iSid;
2232 const char *zExplain;
2233 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2234 break;
2235 }
2236 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2237 if( iSid>mx ) mx = iSid;
2238 if( iSid!=k ) continue;
2239 if( n==0 ){
2240 rEstLoop = (double)nLoop;
2241 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2242 }
2243 n++;
2244 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2245 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2246 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2247 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2248 rEstLoop *= rEst;
2249 raw_printf(pArg->out,
2250 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2251 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2252 );
2253 }
2254 }
2255 raw_printf(pArg->out, "---------------------------\n");
2256#endif
2257}
2258
2259/*
2260** Parameter azArray points to a zero-terminated array of strings. zStr
2261** points to a single nul-terminated string. Return non-zero if zStr
2262** is equal, according to strcmp(), to any of the strings in the array.
2263** Otherwise, return zero.
2264*/
2265static int str_in_array(const char *zStr, const char **azArray){
2266 int i;
2267 for(i=0; azArray[i]; i++){
2268 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2269 }
2270 return 0;
2271}
2272
2273/*
2274** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2275** and populate the ShellState.aiIndent[] array with the number of
2276** spaces each opcode should be indented before it is output.
2277**
2278** The indenting rules are:
2279**
2280** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2281** all opcodes that occur between the p2 jump destination and the opcode
2282** itself by 2 spaces.
2283**
2284** * For each "Goto", if the jump destination is earlier in the program
2285** and ends on one of:
2286** Yield SeekGt SeekLt RowSetRead Rewind
2287** or if the P1 parameter is one instead of zero,
2288** then indent all opcodes between the earlier instruction
2289** and "Goto" by 2 spaces.
2290*/
2291static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2292 const char *zSql; /* The text of the SQL statement */
2293 const char *z; /* Used to check if this is an EXPLAIN */
2294 int *abYield = 0; /* True if op is an OP_Yield */
2295 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2296 int iOp; /* Index of operation in p->aiIndent[] */
2297
2298 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2299 "NextIfOpen", "PrevIfOpen", 0 };
2300 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2301 "Rewind", 0 };
2302 const char *azGoto[] = { "Goto", 0 };
2303
2304 /* Try to figure out if this is really an EXPLAIN statement. If this
2305 ** cannot be verified, return early. */
2306 if( sqlite3_column_count(pSql)!=8 ){
2307 p->cMode = p->mode;
2308 return;
2309 }
2310 zSql = sqlite3_sql(pSql);
2311 if( zSql==0 ) return;
2312 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2313 if( sqlite3_strnicmp(z, "explain", 7) ){
2314 p->cMode = p->mode;
2315 return;
2316 }
2317
2318 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2319 int i;
2320 int iAddr = sqlite3_column_int(pSql, 0);
2321 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2322
2323 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2324 ** p2 is an instruction address, set variable p2op to the index of that
2325 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2326 ** the current instruction is part of a sub-program generated by an
2327 ** SQL trigger or foreign key. */
2328 int p2 = sqlite3_column_int(pSql, 3);
2329 int p2op = (p2 + (iOp-iAddr));
2330
2331 /* Grow the p->aiIndent array as required */
2332 if( iOp>=nAlloc ){
2333 if( iOp==0 ){
2334 /* Do further verfication that this is explain output. Abort if
2335 ** it is not */
2336 static const char *explainCols[] = {
2337 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2338 int jj;
2339 for(jj=0; jj<ArraySize(explainCols); jj++){
2340 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2341 p->cMode = p->mode;
2342 sqlite3_reset(pSql);
2343 return;
2344 }
2345 }
2346 }
2347 nAlloc += 100;
2348 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2349 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2350 }
2351 abYield[iOp] = str_in_array(zOp, azYield);
2352 p->aiIndent[iOp] = 0;
2353 p->nIndent = iOp+1;
2354
2355 if( str_in_array(zOp, azNext) ){
2356 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2357 }
2358 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2359 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2360 ){
2361 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2362 }
2363 }
2364
2365 p->iIndent = 0;
2366 sqlite3_free(abYield);
2367 sqlite3_reset(pSql);
2368}
2369
2370/*
2371** Free the array allocated by explain_data_prepare().
2372*/
2373static void explain_data_delete(ShellState *p){
2374 sqlite3_free(p->aiIndent);
2375 p->aiIndent = 0;
2376 p->nIndent = 0;
2377 p->iIndent = 0;
2378}
2379
2380/*
2381** Disable and restore .wheretrace and .selecttrace settings.
2382*/
2383#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2384extern int sqlite3SelectTrace;
2385static int savedSelectTrace;
2386#endif
2387#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2388extern int sqlite3WhereTrace;
2389static int savedWhereTrace;
2390#endif
2391static void disable_debug_trace_modes(void){
2392#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2393 savedSelectTrace = sqlite3SelectTrace;
2394 sqlite3SelectTrace = 0;
2395#endif
2396#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2397 savedWhereTrace = sqlite3WhereTrace;
2398 sqlite3WhereTrace = 0;
2399#endif
2400}
2401static void restore_debug_trace_modes(void){
2402#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2403 sqlite3SelectTrace = savedSelectTrace;
2404#endif
2405#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2406 sqlite3WhereTrace = savedWhereTrace;
2407#endif
2408}
2409
2410/*
2411** Run a prepared statement
2412*/
2413static void exec_prepared_stmt(
2414 ShellState *pArg, /* Pointer to ShellState */
2415 sqlite3_stmt *pStmt, /* Statment to run */
2416 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2417){
2418 int rc;
2419
2420 /* perform the first step. this will tell us if we
2421 ** have a result set or not and how wide it is.
2422 */
2423 rc = sqlite3_step(pStmt);
2424 /* if we have a result set... */
2425 if( SQLITE_ROW == rc ){
2426 /* if we have a callback... */
2427 if( xCallback ){
2428 /* allocate space for col name ptr, value ptr, and type */
2429 int nCol = sqlite3_column_count(pStmt);
2430 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2431 if( !pData ){
2432 rc = SQLITE_NOMEM;
2433 }else{
2434 char **azCols = (char **)pData; /* Names of result columns */
2435 char **azVals = &azCols[nCol]; /* Results */
2436 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2437 int i, x;
2438 assert(sizeof(int) <= sizeof(char *));
2439 /* save off ptrs to column names */
2440 for(i=0; i<nCol; i++){
2441 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2442 }
2443 do{
2444 /* extract the data and data types */
2445 for(i=0; i<nCol; i++){
2446 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2447 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2448 azVals[i] = "";
2449 }else{
2450 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2451 }
2452 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2453 rc = SQLITE_NOMEM;
2454 break; /* from for */
2455 }
2456 } /* end for */
2457
2458 /* if data and types extracted successfully... */
2459 if( SQLITE_ROW == rc ){
2460 /* call the supplied callback with the result row data */
2461 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2462 rc = SQLITE_ABORT;
2463 }else{
2464 rc = sqlite3_step(pStmt);
2465 }
2466 }
2467 } while( SQLITE_ROW == rc );
2468 sqlite3_free(pData);
2469 }
2470 }else{
2471 do{
2472 rc = sqlite3_step(pStmt);
2473 } while( rc == SQLITE_ROW );
2474 }
2475 }
2476}
2477
dan6b046be2018-01-09 15:25:55 +00002478#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002479/*
dan43efc182017-12-19 17:42:13 +00002480** This function is called to process SQL if the previous shell command
2481** was ".expert". It passes the SQL in the second argument directly to
2482** the sqlite3expert object.
2483**
2484** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2485** code. In this case, (*pzErr) may be set to point to a buffer containing
2486** an English language error message. It is the responsibility of the
2487** caller to eventually free this buffer using sqlite3_free().
2488*/
2489static int expertHandleSQL(
2490 ShellState *pState,
2491 const char *zSql,
2492 char **pzErr
2493){
2494 assert( pState->expert.pExpert );
2495 assert( pzErr==0 || *pzErr==0 );
2496 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2497}
2498
2499/*
2500** This function is called either to silently clean up the object
2501** created by the ".expert" command (if bCancel==1), or to generate a
2502** report from it and then clean it up (if bCancel==0).
2503**
2504** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2505** code. In this case, (*pzErr) may be set to point to a buffer containing
2506** an English language error message. It is the responsibility of the
2507** caller to eventually free this buffer using sqlite3_free().
2508*/
2509static int expertFinish(
2510 ShellState *pState,
2511 int bCancel,
2512 char **pzErr
2513){
2514 int rc = SQLITE_OK;
2515 sqlite3expert *p = pState->expert.pExpert;
2516 assert( p );
2517 assert( bCancel || pzErr==0 || *pzErr==0 );
2518 if( bCancel==0 ){
2519 FILE *out = pState->out;
2520 int bVerbose = pState->expert.bVerbose;
2521
2522 rc = sqlite3_expert_analyze(p, pzErr);
2523 if( rc==SQLITE_OK ){
2524 int nQuery = sqlite3_expert_count(p);
2525 int i;
2526
2527 if( bVerbose ){
2528 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2529 raw_printf(out, "-- Candidates -----------------------------\n");
2530 raw_printf(out, "%s\n", zCand);
2531 }
2532 for(i=0; i<nQuery; i++){
2533 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2534 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2535 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2536 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2537 if( bVerbose ){
2538 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2539 raw_printf(out, "%s\n\n", zSql);
2540 }
2541 raw_printf(out, "%s\n", zIdx);
2542 raw_printf(out, "%s\n", zEQP);
2543 }
2544 }
2545 }
2546 sqlite3_expert_destroy(p);
2547 pState->expert.pExpert = 0;
2548 return rc;
2549}
2550
dan6b046be2018-01-09 15:25:55 +00002551/*
2552** Implementation of ".expert" dot command.
2553*/
2554static int expertDotCommand(
2555 ShellState *pState, /* Current shell tool state */
2556 char **azArg, /* Array of arguments passed to dot command */
2557 int nArg /* Number of entries in azArg[] */
2558){
2559 int rc = SQLITE_OK;
2560 char *zErr = 0;
2561 int i;
2562 int iSample = 0;
2563
2564 assert( pState->expert.pExpert==0 );
2565 memset(&pState->expert, 0, sizeof(ExpertInfo));
2566
2567 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2568 char *z = azArg[i];
2569 int n;
2570 if( z[0]=='-' && z[1]=='-' ) z++;
2571 n = strlen30(z);
2572 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2573 pState->expert.bVerbose = 1;
2574 }
2575 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2576 if( i==(nArg-1) ){
2577 raw_printf(stderr, "option requires an argument: %s\n", z);
2578 rc = SQLITE_ERROR;
2579 }else{
2580 iSample = (int)integerValue(azArg[++i]);
2581 if( iSample<0 || iSample>100 ){
2582 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2583 rc = SQLITE_ERROR;
2584 }
2585 }
2586 }
2587 else{
2588 raw_printf(stderr, "unknown option: %s\n", z);
2589 rc = SQLITE_ERROR;
2590 }
2591 }
2592
2593 if( rc==SQLITE_OK ){
2594 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2595 if( pState->expert.pExpert==0 ){
2596 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2597 rc = SQLITE_ERROR;
2598 }else{
2599 sqlite3_expert_config(
2600 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2601 );
2602 }
2603 }
2604
2605 return rc;
2606}
2607#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00002608
2609/*
drh2ce15c32017-07-11 13:34:40 +00002610** Execute a statement or set of statements. Print
2611** any result rows/columns depending on the current mode
2612** set via the supplied callback.
2613**
2614** This is very similar to SQLite's built-in sqlite3_exec()
2615** function except it takes a slightly different callback
2616** and callback data argument.
2617*/
2618static int shell_exec(
2619 sqlite3 *db, /* An open database */
2620 const char *zSql, /* SQL to be evaluated */
2621 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
2622 /* (not the same as sqlite3_exec) */
2623 ShellState *pArg, /* Pointer to ShellState */
2624 char **pzErrMsg /* Error msg written here */
2625){
2626 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2627 int rc = SQLITE_OK; /* Return Code */
2628 int rc2;
2629 const char *zLeftover; /* Tail of unprocessed SQL */
2630
2631 if( pzErrMsg ){
2632 *pzErrMsg = NULL;
2633 }
2634
dan6b046be2018-01-09 15:25:55 +00002635#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00002636 if( pArg->expert.pExpert ){
2637 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2638 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2639 }
dan6b046be2018-01-09 15:25:55 +00002640#endif
dan43efc182017-12-19 17:42:13 +00002641
drh2ce15c32017-07-11 13:34:40 +00002642 while( zSql[0] && (SQLITE_OK == rc) ){
2643 static const char *zStmtSql;
2644 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2645 if( SQLITE_OK != rc ){
2646 if( pzErrMsg ){
2647 *pzErrMsg = save_err_msg(db);
2648 }
2649 }else{
2650 if( !pStmt ){
2651 /* this happens for a comment or white-space */
2652 zSql = zLeftover;
2653 while( IsSpace(zSql[0]) ) zSql++;
2654 continue;
2655 }
2656 zStmtSql = sqlite3_sql(pStmt);
2657 if( zStmtSql==0 ) zStmtSql = "";
2658 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2659
2660 /* save off the prepared statment handle and reset row count */
2661 if( pArg ){
2662 pArg->pStmt = pStmt;
2663 pArg->cnt = 0;
2664 }
2665
2666 /* echo the sql statement if echo on */
2667 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2668 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2669 }
2670
2671 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2672 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2673 sqlite3_stmt *pExplain;
2674 char *zEQP;
drhada70452017-12-21 21:02:27 +00002675 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00002676 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00002677 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2678 if( pArg->autoEQP>=AUTOEQP_trigger ){
2679 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2680 }
drh2ce15c32017-07-11 13:34:40 +00002681 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2682 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2683 if( rc==SQLITE_OK ){
2684 while( sqlite3_step(pExplain)==SQLITE_ROW ){
2685 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2686 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2687 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
2688 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2689 }
2690 }
2691 sqlite3_finalize(pExplain);
2692 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00002693 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00002694 /* Also do an EXPLAIN for ".eqp full" mode */
2695 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2696 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2697 if( rc==SQLITE_OK ){
2698 pArg->cMode = MODE_Explain;
2699 explain_data_prepare(pArg, pExplain);
2700 exec_prepared_stmt(pArg, pExplain, xCallback);
2701 explain_data_delete(pArg);
2702 }
2703 sqlite3_finalize(pExplain);
2704 sqlite3_free(zEQP);
2705 }
drhada70452017-12-21 21:02:27 +00002706 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, triggerEQP, 0);
drh2ce15c32017-07-11 13:34:40 +00002707 restore_debug_trace_modes();
2708 }
2709
2710 if( pArg ){
2711 pArg->cMode = pArg->mode;
2712 if( pArg->autoExplain
2713 && sqlite3_column_count(pStmt)==8
2714 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2715 ){
2716 pArg->cMode = MODE_Explain;
2717 }
2718
2719 /* If the shell is currently in ".explain" mode, gather the extra
2720 ** data required to add indents to the output.*/
2721 if( pArg->cMode==MODE_Explain ){
2722 explain_data_prepare(pArg, pStmt);
2723 }
2724 }
2725
2726 exec_prepared_stmt(pArg, pStmt, xCallback);
2727 explain_data_delete(pArg);
2728
2729 /* print usage stats if stats on */
2730 if( pArg && pArg->statsOn ){
2731 display_stats(db, pArg, 0);
2732 }
2733
2734 /* print loop-counters if required */
2735 if( pArg && pArg->scanstatsOn ){
2736 display_scanstats(db, pArg);
2737 }
2738
2739 /* Finalize the statement just executed. If this fails, save a
2740 ** copy of the error message. Otherwise, set zSql to point to the
2741 ** next statement to execute. */
2742 rc2 = sqlite3_finalize(pStmt);
2743 if( rc!=SQLITE_NOMEM ) rc = rc2;
2744 if( rc==SQLITE_OK ){
2745 zSql = zLeftover;
2746 while( IsSpace(zSql[0]) ) zSql++;
2747 }else if( pzErrMsg ){
2748 *pzErrMsg = save_err_msg(db);
2749 }
2750
2751 /* clear saved stmt handle */
2752 if( pArg ){
2753 pArg->pStmt = NULL;
2754 }
2755 }
2756 } /* end while */
2757
2758 return rc;
2759}
2760
2761/*
2762** Release memory previously allocated by tableColumnList().
2763*/
2764static void freeColumnList(char **azCol){
2765 int i;
2766 for(i=1; azCol[i]; i++){
2767 sqlite3_free(azCol[i]);
2768 }
2769 /* azCol[0] is a static string */
2770 sqlite3_free(azCol);
2771}
2772
2773/*
2774** Return a list of pointers to strings which are the names of all
2775** columns in table zTab. The memory to hold the names is dynamically
2776** allocated and must be released by the caller using a subsequent call
2777** to freeColumnList().
2778**
2779** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2780** value that needs to be preserved, then azCol[0] is filled in with the
2781** name of the rowid column.
2782**
2783** The first regular column in the table is azCol[1]. The list is terminated
2784** by an entry with azCol[i]==0.
2785*/
2786static char **tableColumnList(ShellState *p, const char *zTab){
2787 char **azCol = 0;
2788 sqlite3_stmt *pStmt;
2789 char *zSql;
2790 int nCol = 0;
2791 int nAlloc = 0;
2792 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2793 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
2794 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
2795 int rc;
2796
2797 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2798 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2799 sqlite3_free(zSql);
2800 if( rc ) return 0;
2801 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2802 if( nCol>=nAlloc-2 ){
2803 nAlloc = nAlloc*2 + nCol + 10;
2804 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2805 if( azCol==0 ){
2806 raw_printf(stderr, "Error: out of memory\n");
2807 exit(1);
2808 }
2809 }
2810 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2811 if( sqlite3_column_int(pStmt, 5) ){
2812 nPK++;
2813 if( nPK==1
2814 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2815 "INTEGER")==0
2816 ){
2817 isIPK = 1;
2818 }else{
2819 isIPK = 0;
2820 }
2821 }
2822 }
2823 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00002824 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002825 azCol[0] = 0;
2826 azCol[nCol+1] = 0;
2827
2828 /* The decision of whether or not a rowid really needs to be preserved
2829 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2830 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2831 ** rowids on tables where the rowid is inaccessible because there are other
2832 ** columns in the table named "rowid", "_rowid_", and "oid".
2833 */
2834 if( preserveRowid && isIPK ){
2835 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2836 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2837 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2838 ** ROWID aliases. To distinguish these cases, check to see if
2839 ** there is a "pk" entry in "PRAGMA index_list". There will be
2840 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2841 */
2842 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2843 " WHERE origin='pk'", zTab);
2844 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2845 sqlite3_free(zSql);
2846 if( rc ){
2847 freeColumnList(azCol);
2848 return 0;
2849 }
2850 rc = sqlite3_step(pStmt);
2851 sqlite3_finalize(pStmt);
2852 preserveRowid = rc==SQLITE_ROW;
2853 }
2854 if( preserveRowid ){
2855 /* Only preserve the rowid if we can find a name to use for the
2856 ** rowid */
2857 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2858 int i, j;
2859 for(j=0; j<3; j++){
2860 for(i=1; i<=nCol; i++){
2861 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2862 }
2863 if( i>nCol ){
2864 /* At this point, we know that azRowid[j] is not the name of any
2865 ** ordinary column in the table. Verify that azRowid[j] is a valid
2866 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2867 ** tables will fail this last check */
2868 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2869 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2870 break;
2871 }
2872 }
2873 }
2874 return azCol;
2875}
2876
2877/*
2878** Toggle the reverse_unordered_selects setting.
2879*/
2880static void toggleSelectOrder(sqlite3 *db){
2881 sqlite3_stmt *pStmt = 0;
2882 int iSetting = 0;
2883 char zStmt[100];
2884 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2885 if( sqlite3_step(pStmt)==SQLITE_ROW ){
2886 iSetting = sqlite3_column_int(pStmt, 0);
2887 }
2888 sqlite3_finalize(pStmt);
2889 sqlite3_snprintf(sizeof(zStmt), zStmt,
2890 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2891 sqlite3_exec(db, zStmt, 0, 0, 0);
2892}
2893
2894/*
2895** This is a different callback routine used for dumping the database.
2896** Each row received by this callback consists of a table name,
2897** the table type ("index" or "table") and SQL to create the table.
2898** This routine should print text sufficient to recreate the table.
2899*/
2900static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
2901 int rc;
2902 const char *zTable;
2903 const char *zType;
2904 const char *zSql;
2905 ShellState *p = (ShellState *)pArg;
2906
2907 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00002908 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002909 zTable = azArg[0];
2910 zType = azArg[1];
2911 zSql = azArg[2];
2912
2913 if( strcmp(zTable, "sqlite_sequence")==0 ){
2914 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
2915 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2916 raw_printf(p->out, "ANALYZE sqlite_master;\n");
2917 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2918 return 0;
2919 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2920 char *zIns;
2921 if( !p->writableSchema ){
2922 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2923 p->writableSchema = 1;
2924 }
2925 zIns = sqlite3_mprintf(
2926 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2927 "VALUES('table','%q','%q',0,'%q');",
2928 zTable, zTable, zSql);
2929 utf8_printf(p->out, "%s\n", zIns);
2930 sqlite3_free(zIns);
2931 return 0;
2932 }else{
2933 printSchemaLine(p->out, zSql, ";\n");
2934 }
2935
2936 if( strcmp(zType, "table")==0 ){
2937 ShellText sSelect;
2938 ShellText sTable;
2939 char **azCol;
2940 int i;
2941 char *savedDestTable;
2942 int savedMode;
2943
2944 azCol = tableColumnList(p, zTable);
2945 if( azCol==0 ){
2946 p->nErr++;
2947 return 0;
2948 }
2949
2950 /* Always quote the table name, even if it appears to be pure ascii,
2951 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2952 initText(&sTable);
2953 appendText(&sTable, zTable, quoteChar(zTable));
2954 /* If preserving the rowid, add a column list after the table name.
2955 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2956 ** instead of the usual "INSERT INTO tab VALUES(...)".
2957 */
2958 if( azCol[0] ){
2959 appendText(&sTable, "(", 0);
2960 appendText(&sTable, azCol[0], 0);
2961 for(i=1; azCol[i]; i++){
2962 appendText(&sTable, ",", 0);
2963 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
2964 }
2965 appendText(&sTable, ")", 0);
2966 }
2967
2968 /* Build an appropriate SELECT statement */
2969 initText(&sSelect);
2970 appendText(&sSelect, "SELECT ", 0);
2971 if( azCol[0] ){
2972 appendText(&sSelect, azCol[0], 0);
2973 appendText(&sSelect, ",", 0);
2974 }
2975 for(i=1; azCol[i]; i++){
2976 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
2977 if( azCol[i+1] ){
2978 appendText(&sSelect, ",", 0);
2979 }
2980 }
2981 freeColumnList(azCol);
2982 appendText(&sSelect, " FROM ", 0);
2983 appendText(&sSelect, zTable, quoteChar(zTable));
2984
2985 savedDestTable = p->zDestTable;
2986 savedMode = p->mode;
2987 p->zDestTable = sTable.z;
2988 p->mode = p->cMode = MODE_Insert;
2989 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2990 if( (rc&0xff)==SQLITE_CORRUPT ){
2991 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2992 toggleSelectOrder(p->db);
2993 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2994 toggleSelectOrder(p->db);
2995 }
2996 p->zDestTable = savedDestTable;
2997 p->mode = savedMode;
2998 freeText(&sTable);
2999 freeText(&sSelect);
3000 if( rc ) p->nErr++;
3001 }
3002 return 0;
3003}
3004
3005/*
3006** Run zQuery. Use dump_callback() as the callback routine so that
3007** the contents of the query are output as SQL statements.
3008**
3009** If we get a SQLITE_CORRUPT error, rerun the query after appending
3010** "ORDER BY rowid DESC" to the end.
3011*/
3012static int run_schema_dump_query(
3013 ShellState *p,
3014 const char *zQuery
3015){
3016 int rc;
3017 char *zErr = 0;
3018 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3019 if( rc==SQLITE_CORRUPT ){
3020 char *zQ2;
3021 int len = strlen30(zQuery);
3022 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3023 if( zErr ){
3024 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3025 sqlite3_free(zErr);
3026 zErr = 0;
3027 }
3028 zQ2 = malloc( len+100 );
3029 if( zQ2==0 ) return rc;
3030 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3031 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3032 if( rc ){
3033 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3034 }else{
3035 rc = SQLITE_CORRUPT;
3036 }
3037 sqlite3_free(zErr);
3038 free(zQ2);
3039 }
3040 return rc;
3041}
3042
3043/*
3044** Text of a help message
3045*/
3046static char zHelp[] =
drhe37c0e12018-01-06 19:19:50 +00003047#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3048 ".archive ... Manage SQL archives: \".archive --help\" for details\n"
3049#endif
drh2ce15c32017-07-11 13:34:40 +00003050#ifndef SQLITE_OMIT_AUTHORIZATION
3051 ".auth ON|OFF Show authorizer callbacks\n"
3052#endif
3053 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
3054 ".bail on|off Stop after hitting an error. Default OFF\n"
3055 ".binary on|off Turn binary output on or off. Default OFF\n"
3056 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
3057 ".changes on|off Show number of rows changed by SQL\n"
3058 ".check GLOB Fail if output since .testcase does not match\n"
3059 ".clone NEWDB Clone data into NEWDB from the existing database\n"
3060 ".databases List names and files of attached databases\n"
3061 ".dbinfo ?DB? Show status information about the database\n"
3062 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
3063 " If TABLE specified, only dump tables matching\n"
3064 " LIKE pattern TABLE.\n"
3065 ".echo on|off Turn command echo on or off\n"
3066 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
3067 ".exit Exit this program\n"
dan2e1ea572017-12-21 18:55:24 +00003068 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
drh2ce15c32017-07-11 13:34:40 +00003069/* Because explain mode comes on automatically now, the ".explain" mode
3070** is removed from the help screen. It is still supported for legacy, however */
3071/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
3072 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3073 ".headers on|off Turn display of headers on or off\n"
3074 ".help Show this message\n"
3075 ".import FILE TABLE Import data from FILE into TABLE\n"
3076#ifndef SQLITE_OMIT_TEST_CONTROL
3077 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3078#endif
3079 ".indexes ?TABLE? Show names of all indexes\n"
3080 " If TABLE specified, only show indexes for tables\n"
3081 " matching LIKE pattern TABLE.\n"
3082#ifdef SQLITE_ENABLE_IOTRACE
3083 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3084#endif
3085 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
3086 ".lint OPTIONS Report potential schema issues. Options:\n"
3087 " fkey-indexes Find missing foreign key indexes\n"
3088#ifndef SQLITE_OMIT_LOAD_EXTENSION
3089 ".load FILE ?ENTRY? Load an extension library\n"
3090#endif
3091 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
3092 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
3093 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
3094 " csv Comma-separated values\n"
3095 " column Left-aligned columns. (See .width)\n"
3096 " html HTML <table> code\n"
3097 " insert SQL insert statements for TABLE\n"
3098 " line One value per line\n"
3099 " list Values delimited by \"|\"\n"
3100 " quote Escape answers as for SQL\n"
3101 " tabs Tab-separated values\n"
3102 " tcl TCL list elements\n"
3103 ".nullvalue STRING Use STRING in place of NULL values\n"
3104 ".once FILENAME Output for the next SQL command only to FILENAME\n"
3105 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3106 " The --new option starts with an empty file\n"
3107 ".output ?FILENAME? Send output to FILENAME or stdout\n"
3108 ".print STRING... Print literal STRING\n"
3109 ".prompt MAIN CONTINUE Replace the standard prompts\n"
3110 ".quit Exit this program\n"
3111 ".read FILENAME Execute SQL in FILENAME\n"
3112 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
3113 ".save FILE Write in-memory database into FILE\n"
3114 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3115 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3116 " Add --indent for pretty-printing\n"
3117 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
3118 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3119 " separator for both the output mode and .import\n"
3120#if defined(SQLITE_ENABLE_SESSION)
3121 ".session CMD ... Create or control sessions\n"
3122#endif
3123 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
3124 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
3125 ".show Show the current values for various settings\n"
3126 ".stats ?on|off? Show stats or turn stats on or off\n"
3127 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
3128 ".tables ?TABLE? List names of tables\n"
3129 " If TABLE specified, only list tables matching\n"
3130 " LIKE pattern TABLE.\n"
3131 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
3132 ".timeout MS Try opening locked tables for MS milliseconds\n"
3133 ".timer on|off Turn SQL timer on or off\n"
3134 ".trace FILE|off Output each SQL statement as it is run\n"
3135 ".vfsinfo ?AUX? Information about the top-level VFS\n"
3136 ".vfslist List all available VFSes\n"
3137 ".vfsname ?AUX? Print the name of the VFS stack\n"
3138 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
3139 " Negative values right-justify\n"
3140;
3141
3142#if defined(SQLITE_ENABLE_SESSION)
3143/*
3144** Print help information for the ".sessions" command
3145*/
3146void session_help(ShellState *p){
3147 raw_printf(p->out,
3148 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3149 "If ?NAME? is omitted, the first defined session is used.\n"
3150 "Subcommands:\n"
3151 " attach TABLE Attach TABLE\n"
3152 " changeset FILE Write a changeset into FILE\n"
3153 " close Close one session\n"
3154 " enable ?BOOLEAN? Set or query the enable bit\n"
3155 " filter GLOB... Reject tables matching GLOBs\n"
3156 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3157 " isempty Query whether the session is empty\n"
3158 " list List currently open session names\n"
3159 " open DB NAME Open a new session on DB\n"
3160 " patchset FILE Write a patchset into FILE\n"
3161 );
3162}
3163#endif
3164
3165
3166/* Forward reference */
3167static int process_input(ShellState *p, FILE *in);
3168
3169/*
3170** Read the content of file zName into memory obtained from sqlite3_malloc64()
3171** and return a pointer to the buffer. The caller is responsible for freeing
3172** the memory.
3173**
3174** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3175** read.
3176**
3177** For convenience, a nul-terminator byte is always appended to the data read
3178** from the file before the buffer is returned. This byte is not included in
3179** the final value of (*pnByte), if applicable.
3180**
3181** NULL is returned if any error is encountered. The final value of *pnByte
3182** is undefined in this case.
3183*/
3184static char *readFile(const char *zName, int *pnByte){
3185 FILE *in = fopen(zName, "rb");
3186 long nIn;
3187 size_t nRead;
3188 char *pBuf;
3189 if( in==0 ) return 0;
3190 fseek(in, 0, SEEK_END);
3191 nIn = ftell(in);
3192 rewind(in);
3193 pBuf = sqlite3_malloc64( nIn+1 );
3194 if( pBuf==0 ) return 0;
3195 nRead = fread(pBuf, nIn, 1, in);
3196 fclose(in);
3197 if( nRead!=1 ){
3198 sqlite3_free(pBuf);
3199 return 0;
3200 }
3201 pBuf[nIn] = 0;
3202 if( pnByte ) *pnByte = nIn;
3203 return pBuf;
3204}
3205
3206#if defined(SQLITE_ENABLE_SESSION)
3207/*
3208** Close a single OpenSession object and release all of its associated
3209** resources.
3210*/
3211static void session_close(OpenSession *pSession){
3212 int i;
3213 sqlite3session_delete(pSession->p);
3214 sqlite3_free(pSession->zName);
3215 for(i=0; i<pSession->nFilter; i++){
3216 sqlite3_free(pSession->azFilter[i]);
3217 }
3218 sqlite3_free(pSession->azFilter);
3219 memset(pSession, 0, sizeof(OpenSession));
3220}
3221#endif
3222
3223/*
3224** Close all OpenSession objects and release all associated resources.
3225*/
3226#if defined(SQLITE_ENABLE_SESSION)
3227static void session_close_all(ShellState *p){
3228 int i;
3229 for(i=0; i<p->nSession; i++){
3230 session_close(&p->aSession[i]);
3231 }
3232 p->nSession = 0;
3233}
3234#else
3235# define session_close_all(X)
3236#endif
3237
3238/*
3239** Implementation of the xFilter function for an open session. Omit
3240** any tables named by ".session filter" but let all other table through.
3241*/
3242#if defined(SQLITE_ENABLE_SESSION)
3243static int session_filter(void *pCtx, const char *zTab){
3244 OpenSession *pSession = (OpenSession*)pCtx;
3245 int i;
3246 for(i=0; i<pSession->nFilter; i++){
3247 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3248 }
3249 return 1;
3250}
3251#endif
3252
3253/*
drh1fa6d9f2018-01-06 21:46:01 +00003254** Try to deduce the type of file for zName based on its content. Return
3255** one of the SHELL_OPEN_* constants.
3256*/
3257static int deduceDatabaseType(const char *zName){
3258 FILE *f = fopen(zName, "rb");
3259 size_t n;
3260 int rc = SHELL_OPEN_UNSPEC;
3261 char zBuf[100];
3262 if( f==0 ) return SHELL_OPEN_NORMAL;
3263 fseek(f, -25, SEEK_END);
3264 n = fread(zBuf, 25, 1, f);
3265 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3266 rc = SHELL_OPEN_APPENDVFS;
3267 }else{
3268 fseek(f, -22, SEEK_END);
3269 n = fread(zBuf, 22, 1, f);
3270 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3271 && zBuf[3]==0x06 ){
3272 rc = SHELL_OPEN_ZIPFILE;
3273 }
3274 }
3275 fclose(f);
3276 return rc;
3277}
3278
3279/*
drh2ce15c32017-07-11 13:34:40 +00003280** Make sure the database is open. If it is not, then open it. If
3281** the database fails to open, print an error message and exit.
3282*/
3283static void open_db(ShellState *p, int keepAlive){
3284 if( p->db==0 ){
3285 sqlite3_initialize();
drh1fa6d9f2018-01-06 21:46:01 +00003286 if( p->openMode==SHELL_OPEN_UNSPEC && access(p->zDbFilename,0)==0 ){
3287 p->openMode = deduceDatabaseType(p->zDbFilename);
3288 }
3289 switch( p->openMode ){
3290 case SHELL_OPEN_APPENDVFS: {
3291 sqlite3_open_v2(p->zDbFilename, &p->db,
3292 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
3293 break;
3294 }
3295 case SHELL_OPEN_ZIPFILE: {
3296 sqlite3_open(":memory:", &p->db);
3297 break;
3298 }
3299 case SHELL_OPEN_UNSPEC:
3300 case SHELL_OPEN_NORMAL: {
3301 sqlite3_open(p->zDbFilename, &p->db);
3302 break;
3303 }
3304 }
drh2ce15c32017-07-11 13:34:40 +00003305 globalDb = p->db;
3306 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3307 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3308 p->zDbFilename, sqlite3_errmsg(p->db));
3309 if( keepAlive ) return;
3310 exit(1);
3311 }
3312#ifndef SQLITE_OMIT_LOAD_EXTENSION
3313 sqlite3_enable_load_extension(p->db, 1);
3314#endif
3315 sqlite3_fileio_init(p->db, 0, 0);
3316 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00003317 sqlite3_completion_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003318#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00003319 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00003320 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003321#endif
drhceba7922018-01-01 21:28:25 +00003322 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00003323 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00003324 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3325 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00003326 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
3327 shellPutsFunc, 0, 0);
drh1fa6d9f2018-01-06 21:46:01 +00003328 if( p->openMode==SHELL_OPEN_ZIPFILE ){
3329 char *zSql = sqlite3_mprintf(
3330 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
3331 sqlite3_exec(p->db, zSql, 0, 0, 0);
3332 sqlite3_free(zSql);
3333 }
drh2ce15c32017-07-11 13:34:40 +00003334 }
3335}
3336
drh56eb09b2017-07-11 13:59:07 +00003337#if HAVE_READLINE || HAVE_EDITLINE
3338/*
3339** Readline completion callbacks
3340*/
3341static char *readline_completion_generator(const char *text, int state){
3342 static sqlite3_stmt *pStmt = 0;
3343 char *zRet;
3344 if( state==0 ){
3345 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00003346 sqlite3_finalize(pStmt);
3347 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3348 " FROM completion(%Q) ORDER BY 1", text);
3349 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3350 sqlite3_free(zSql);
3351 }
3352 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00003353 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00003354 }else{
3355 sqlite3_finalize(pStmt);
3356 pStmt = 0;
3357 zRet = 0;
3358 }
3359 return zRet;
3360}
3361static char **readline_completion(const char *zText, int iStart, int iEnd){
3362 rl_attempted_completion_over = 1;
3363 return rl_completion_matches(zText, readline_completion_generator);
3364}
3365
3366#elif HAVE_LINENOISE
3367/*
3368** Linenoise completion callback
3369*/
3370static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00003371 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00003372 int i, iStart;
3373 sqlite3_stmt *pStmt = 0;
3374 char *zSql;
3375 char zBuf[1000];
3376
3377 if( nLine>sizeof(zBuf)-30 ) return;
3378 if( zLine[0]=='.' ) return;
3379 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
3380 if( i==nLine-1 ) return;
3381 iStart = i+1;
3382 memcpy(zBuf, zLine, iStart);
3383 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3384 " FROM completion(%Q,%Q) ORDER BY 1",
3385 &zLine[iStart], zLine);
3386 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3387 sqlite3_free(zSql);
3388 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3389 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3390 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
3391 int nCompletion = sqlite3_column_bytes(pStmt, 0);
3392 if( iStart+nCompletion < sizeof(zBuf)-1 ){
3393 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
3394 linenoiseAddCompletion(lc, zBuf);
3395 }
3396 }
3397 sqlite3_finalize(pStmt);
3398}
3399#endif
3400
drh2ce15c32017-07-11 13:34:40 +00003401/*
3402** Do C-language style dequoting.
3403**
3404** \a -> alarm
3405** \b -> backspace
3406** \t -> tab
3407** \n -> newline
3408** \v -> vertical tab
3409** \f -> form feed
3410** \r -> carriage return
3411** \s -> space
3412** \" -> "
3413** \' -> '
3414** \\ -> backslash
3415** \NNN -> ascii character NNN in octal
3416*/
3417static void resolve_backslashes(char *z){
3418 int i, j;
3419 char c;
3420 while( *z && *z!='\\' ) z++;
3421 for(i=j=0; (c = z[i])!=0; i++, j++){
3422 if( c=='\\' && z[i+1]!=0 ){
3423 c = z[++i];
3424 if( c=='a' ){
3425 c = '\a';
3426 }else if( c=='b' ){
3427 c = '\b';
3428 }else if( c=='t' ){
3429 c = '\t';
3430 }else if( c=='n' ){
3431 c = '\n';
3432 }else if( c=='v' ){
3433 c = '\v';
3434 }else if( c=='f' ){
3435 c = '\f';
3436 }else if( c=='r' ){
3437 c = '\r';
3438 }else if( c=='"' ){
3439 c = '"';
3440 }else if( c=='\'' ){
3441 c = '\'';
3442 }else if( c=='\\' ){
3443 c = '\\';
3444 }else if( c>='0' && c<='7' ){
3445 c -= '0';
3446 if( z[i+1]>='0' && z[i+1]<='7' ){
3447 i++;
3448 c = (c<<3) + z[i] - '0';
3449 if( z[i+1]>='0' && z[i+1]<='7' ){
3450 i++;
3451 c = (c<<3) + z[i] - '0';
3452 }
3453 }
3454 }
3455 }
3456 z[j] = c;
3457 }
3458 if( j<i ) z[j] = 0;
3459}
3460
3461/*
drh2ce15c32017-07-11 13:34:40 +00003462** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3463** for TRUE and FALSE. Return the integer value if appropriate.
3464*/
3465static int booleanValue(const char *zArg){
3466 int i;
3467 if( zArg[0]=='0' && zArg[1]=='x' ){
3468 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3469 }else{
3470 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3471 }
3472 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3473 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3474 return 1;
3475 }
3476 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3477 return 0;
3478 }
3479 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3480 zArg);
3481 return 0;
3482}
3483
3484/*
3485** Set or clear a shell flag according to a boolean value.
3486*/
3487static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3488 if( booleanValue(zArg) ){
3489 ShellSetFlag(p, mFlag);
3490 }else{
3491 ShellClearFlag(p, mFlag);
3492 }
3493}
3494
3495/*
3496** Close an output file, assuming it is not stderr or stdout
3497*/
3498static void output_file_close(FILE *f){
3499 if( f && f!=stdout && f!=stderr ) fclose(f);
3500}
3501
3502/*
3503** Try to open an output file. The names "stdout" and "stderr" are
3504** recognized and do the right thing. NULL is returned if the output
3505** filename is "off".
3506*/
3507static FILE *output_file_open(const char *zFile){
3508 FILE *f;
3509 if( strcmp(zFile,"stdout")==0 ){
3510 f = stdout;
3511 }else if( strcmp(zFile, "stderr")==0 ){
3512 f = stderr;
3513 }else if( strcmp(zFile, "off")==0 ){
3514 f = 0;
3515 }else{
3516 f = fopen(zFile, "wb");
3517 if( f==0 ){
3518 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3519 }
3520 }
3521 return f;
3522}
3523
3524#if !defined(SQLITE_UNTESTABLE)
3525#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3526/*
3527** A routine for handling output from sqlite3_trace().
3528*/
3529static int sql_trace_callback(
3530 unsigned mType,
3531 void *pArg,
3532 void *pP,
3533 void *pX
3534){
3535 FILE *f = (FILE*)pArg;
3536 UNUSED_PARAMETER(mType);
3537 UNUSED_PARAMETER(pP);
3538 if( f ){
3539 const char *z = (const char*)pX;
drhaf2770f2018-01-05 14:55:43 +00003540 int i = strlen30(z);
drh2ce15c32017-07-11 13:34:40 +00003541 while( i>0 && z[i-1]==';' ){ i--; }
3542 utf8_printf(f, "%.*s;\n", i, z);
3543 }
3544 return 0;
3545}
3546#endif
3547#endif
3548
3549/*
3550** A no-op routine that runs with the ".breakpoint" doc-command. This is
3551** a useful spot to set a debugger breakpoint.
3552*/
3553static void test_breakpoint(void){
3554 static int nCall = 0;
3555 nCall++;
3556}
3557
3558/*
3559** An object used to read a CSV and other files for import.
3560*/
3561typedef struct ImportCtx ImportCtx;
3562struct ImportCtx {
3563 const char *zFile; /* Name of the input file */
3564 FILE *in; /* Read the CSV text from this input stream */
3565 char *z; /* Accumulated text for a field */
3566 int n; /* Number of bytes in z */
3567 int nAlloc; /* Space allocated for z[] */
3568 int nLine; /* Current line number */
3569 int bNotFirst; /* True if one or more bytes already read */
3570 int cTerm; /* Character that terminated the most recent field */
3571 int cColSep; /* The column separator character. (Usually ",") */
3572 int cRowSep; /* The row separator character. (Usually "\n") */
3573};
3574
3575/* Append a single byte to z[] */
3576static void import_append_char(ImportCtx *p, int c){
3577 if( p->n+1>=p->nAlloc ){
3578 p->nAlloc += p->nAlloc + 100;
3579 p->z = sqlite3_realloc64(p->z, p->nAlloc);
3580 if( p->z==0 ){
3581 raw_printf(stderr, "out of memory\n");
3582 exit(1);
3583 }
3584 }
3585 p->z[p->n++] = (char)c;
3586}
3587
3588/* Read a single field of CSV text. Compatible with rfc4180 and extended
3589** with the option of having a separator other than ",".
3590**
3591** + Input comes from p->in.
3592** + Store results in p->z of length p->n. Space to hold p->z comes
3593** from sqlite3_malloc64().
3594** + Use p->cSep as the column separator. The default is ",".
3595** + Use p->rSep as the row separator. The default is "\n".
3596** + Keep track of the line number in p->nLine.
3597** + Store the character that terminates the field in p->cTerm. Store
3598** EOF on end-of-file.
3599** + Report syntax errors on stderr
3600*/
3601static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3602 int c;
3603 int cSep = p->cColSep;
3604 int rSep = p->cRowSep;
3605 p->n = 0;
3606 c = fgetc(p->in);
3607 if( c==EOF || seenInterrupt ){
3608 p->cTerm = EOF;
3609 return 0;
3610 }
3611 if( c=='"' ){
3612 int pc, ppc;
3613 int startLine = p->nLine;
3614 int cQuote = c;
3615 pc = ppc = 0;
3616 while( 1 ){
3617 c = fgetc(p->in);
3618 if( c==rSep ) p->nLine++;
3619 if( c==cQuote ){
3620 if( pc==cQuote ){
3621 pc = 0;
3622 continue;
3623 }
3624 }
3625 if( (c==cSep && pc==cQuote)
3626 || (c==rSep && pc==cQuote)
3627 || (c==rSep && pc=='\r' && ppc==cQuote)
3628 || (c==EOF && pc==cQuote)
3629 ){
3630 do{ p->n--; }while( p->z[p->n]!=cQuote );
3631 p->cTerm = c;
3632 break;
3633 }
3634 if( pc==cQuote && c!='\r' ){
3635 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3636 p->zFile, p->nLine, cQuote);
3637 }
3638 if( c==EOF ){
3639 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3640 p->zFile, startLine, cQuote);
3641 p->cTerm = c;
3642 break;
3643 }
3644 import_append_char(p, c);
3645 ppc = pc;
3646 pc = c;
3647 }
3648 }else{
3649 /* If this is the first field being parsed and it begins with the
3650 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3651 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3652 import_append_char(p, c);
3653 c = fgetc(p->in);
3654 if( (c&0xff)==0xbb ){
3655 import_append_char(p, c);
3656 c = fgetc(p->in);
3657 if( (c&0xff)==0xbf ){
3658 p->bNotFirst = 1;
3659 p->n = 0;
3660 return csv_read_one_field(p);
3661 }
3662 }
3663 }
3664 while( c!=EOF && c!=cSep && c!=rSep ){
3665 import_append_char(p, c);
3666 c = fgetc(p->in);
3667 }
3668 if( c==rSep ){
3669 p->nLine++;
3670 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3671 }
3672 p->cTerm = c;
3673 }
3674 if( p->z ) p->z[p->n] = 0;
3675 p->bNotFirst = 1;
3676 return p->z;
3677}
3678
3679/* Read a single field of ASCII delimited text.
3680**
3681** + Input comes from p->in.
3682** + Store results in p->z of length p->n. Space to hold p->z comes
3683** from sqlite3_malloc64().
3684** + Use p->cSep as the column separator. The default is "\x1F".
3685** + Use p->rSep as the row separator. The default is "\x1E".
3686** + Keep track of the row number in p->nLine.
3687** + Store the character that terminates the field in p->cTerm. Store
3688** EOF on end-of-file.
3689** + Report syntax errors on stderr
3690*/
3691static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3692 int c;
3693 int cSep = p->cColSep;
3694 int rSep = p->cRowSep;
3695 p->n = 0;
3696 c = fgetc(p->in);
3697 if( c==EOF || seenInterrupt ){
3698 p->cTerm = EOF;
3699 return 0;
3700 }
3701 while( c!=EOF && c!=cSep && c!=rSep ){
3702 import_append_char(p, c);
3703 c = fgetc(p->in);
3704 }
3705 if( c==rSep ){
3706 p->nLine++;
3707 }
3708 p->cTerm = c;
3709 if( p->z ) p->z[p->n] = 0;
3710 return p->z;
3711}
3712
3713/*
3714** Try to transfer data for table zTable. If an error is seen while
3715** moving forward, try to go backwards. The backwards movement won't
3716** work for WITHOUT ROWID tables.
3717*/
3718static void tryToCloneData(
3719 ShellState *p,
3720 sqlite3 *newDb,
3721 const char *zTable
3722){
3723 sqlite3_stmt *pQuery = 0;
3724 sqlite3_stmt *pInsert = 0;
3725 char *zQuery = 0;
3726 char *zInsert = 0;
3727 int rc;
3728 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00003729 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00003730 int k = 0;
3731 int cnt = 0;
3732 const int spinRate = 10000;
3733
3734 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3735 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3736 if( rc ){
3737 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3738 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3739 zQuery);
3740 goto end_data_xfer;
3741 }
3742 n = sqlite3_column_count(pQuery);
3743 zInsert = sqlite3_malloc64(200 + nTable + n*3);
3744 if( zInsert==0 ){
3745 raw_printf(stderr, "out of memory\n");
3746 goto end_data_xfer;
3747 }
3748 sqlite3_snprintf(200+nTable,zInsert,
3749 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00003750 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00003751 for(j=1; j<n; j++){
3752 memcpy(zInsert+i, ",?", 2);
3753 i += 2;
3754 }
3755 memcpy(zInsert+i, ");", 3);
3756 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3757 if( rc ){
3758 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3759 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3760 zQuery);
3761 goto end_data_xfer;
3762 }
3763 for(k=0; k<2; k++){
3764 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3765 for(i=0; i<n; i++){
3766 switch( sqlite3_column_type(pQuery, i) ){
3767 case SQLITE_NULL: {
3768 sqlite3_bind_null(pInsert, i+1);
3769 break;
3770 }
3771 case SQLITE_INTEGER: {
3772 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3773 break;
3774 }
3775 case SQLITE_FLOAT: {
3776 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3777 break;
3778 }
3779 case SQLITE_TEXT: {
3780 sqlite3_bind_text(pInsert, i+1,
3781 (const char*)sqlite3_column_text(pQuery,i),
3782 -1, SQLITE_STATIC);
3783 break;
3784 }
3785 case SQLITE_BLOB: {
3786 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3787 sqlite3_column_bytes(pQuery,i),
3788 SQLITE_STATIC);
3789 break;
3790 }
3791 }
3792 } /* End for */
3793 rc = sqlite3_step(pInsert);
3794 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3795 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3796 sqlite3_errmsg(newDb));
3797 }
3798 sqlite3_reset(pInsert);
3799 cnt++;
3800 if( (cnt%spinRate)==0 ){
3801 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3802 fflush(stdout);
3803 }
3804 } /* End while */
3805 if( rc==SQLITE_DONE ) break;
3806 sqlite3_finalize(pQuery);
3807 sqlite3_free(zQuery);
3808 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3809 zTable);
3810 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3811 if( rc ){
3812 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
3813 break;
3814 }
3815 } /* End for(k=0...) */
3816
3817end_data_xfer:
3818 sqlite3_finalize(pQuery);
3819 sqlite3_finalize(pInsert);
3820 sqlite3_free(zQuery);
3821 sqlite3_free(zInsert);
3822}
3823
3824
3825/*
3826** Try to transfer all rows of the schema that match zWhere. For
3827** each row, invoke xForEach() on the object defined by that row.
3828** If an error is encountered while moving forward through the
3829** sqlite_master table, try again moving backwards.
3830*/
3831static void tryToCloneSchema(
3832 ShellState *p,
3833 sqlite3 *newDb,
3834 const char *zWhere,
3835 void (*xForEach)(ShellState*,sqlite3*,const char*)
3836){
3837 sqlite3_stmt *pQuery = 0;
3838 char *zQuery = 0;
3839 int rc;
3840 const unsigned char *zName;
3841 const unsigned char *zSql;
3842 char *zErrMsg = 0;
3843
3844 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3845 " WHERE %s", zWhere);
3846 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3847 if( rc ){
3848 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3849 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3850 zQuery);
3851 goto end_schema_xfer;
3852 }
3853 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3854 zName = sqlite3_column_text(pQuery, 0);
3855 zSql = sqlite3_column_text(pQuery, 1);
3856 printf("%s... ", zName); fflush(stdout);
3857 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3858 if( zErrMsg ){
3859 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3860 sqlite3_free(zErrMsg);
3861 zErrMsg = 0;
3862 }
3863 if( xForEach ){
3864 xForEach(p, newDb, (const char*)zName);
3865 }
3866 printf("done\n");
3867 }
3868 if( rc!=SQLITE_DONE ){
3869 sqlite3_finalize(pQuery);
3870 sqlite3_free(zQuery);
3871 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3872 " WHERE %s ORDER BY rowid DESC", zWhere);
3873 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3874 if( rc ){
3875 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3876 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3877 zQuery);
3878 goto end_schema_xfer;
3879 }
3880 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3881 zName = sqlite3_column_text(pQuery, 0);
3882 zSql = sqlite3_column_text(pQuery, 1);
3883 printf("%s... ", zName); fflush(stdout);
3884 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3885 if( zErrMsg ){
3886 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3887 sqlite3_free(zErrMsg);
3888 zErrMsg = 0;
3889 }
3890 if( xForEach ){
3891 xForEach(p, newDb, (const char*)zName);
3892 }
3893 printf("done\n");
3894 }
3895 }
3896end_schema_xfer:
3897 sqlite3_finalize(pQuery);
3898 sqlite3_free(zQuery);
3899}
3900
3901/*
3902** Open a new database file named "zNewDb". Try to recover as much information
3903** as possible out of the main database (which might be corrupt) and write it
3904** into zNewDb.
3905*/
3906static void tryToClone(ShellState *p, const char *zNewDb){
3907 int rc;
3908 sqlite3 *newDb = 0;
3909 if( access(zNewDb,0)==0 ){
3910 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
3911 return;
3912 }
3913 rc = sqlite3_open(zNewDb, &newDb);
3914 if( rc ){
3915 utf8_printf(stderr, "Cannot create output database: %s\n",
3916 sqlite3_errmsg(newDb));
3917 }else{
3918 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
3919 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
3920 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3921 tryToCloneSchema(p, newDb, "type!='table'", 0);
3922 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
3923 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3924 }
3925 sqlite3_close(newDb);
3926}
3927
3928/*
3929** Change the output file back to stdout
3930*/
3931static void output_reset(ShellState *p){
3932 if( p->outfile[0]=='|' ){
3933#ifndef SQLITE_OMIT_POPEN
3934 pclose(p->out);
3935#endif
3936 }else{
3937 output_file_close(p->out);
3938 }
3939 p->outfile[0] = 0;
3940 p->out = stdout;
3941}
3942
3943/*
3944** Run an SQL command and return the single integer result.
3945*/
3946static int db_int(ShellState *p, const char *zSql){
3947 sqlite3_stmt *pStmt;
3948 int res = 0;
3949 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3950 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3951 res = sqlite3_column_int(pStmt,0);
3952 }
3953 sqlite3_finalize(pStmt);
3954 return res;
3955}
3956
3957/*
3958** Convert a 2-byte or 4-byte big-endian integer into a native integer
3959*/
3960static unsigned int get2byteInt(unsigned char *a){
3961 return (a[0]<<8) + a[1];
3962}
3963static unsigned int get4byteInt(unsigned char *a){
3964 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
3965}
3966
3967/*
3968** Implementation of the ".info" command.
3969**
3970** Return 1 on error, 2 to exit, and 0 otherwise.
3971*/
3972static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
3973 static const struct { const char *zName; int ofst; } aField[] = {
3974 { "file change counter:", 24 },
3975 { "database page count:", 28 },
3976 { "freelist page count:", 36 },
3977 { "schema cookie:", 40 },
3978 { "schema format:", 44 },
3979 { "default cache size:", 48 },
3980 { "autovacuum top root:", 52 },
3981 { "incremental vacuum:", 64 },
3982 { "text encoding:", 56 },
3983 { "user version:", 60 },
3984 { "application id:", 68 },
3985 { "software version:", 96 },
3986 };
3987 static const struct { const char *zName; const char *zSql; } aQuery[] = {
3988 { "number of tables:",
3989 "SELECT count(*) FROM %s WHERE type='table'" },
3990 { "number of indexes:",
3991 "SELECT count(*) FROM %s WHERE type='index'" },
3992 { "number of triggers:",
3993 "SELECT count(*) FROM %s WHERE type='trigger'" },
3994 { "number of views:",
3995 "SELECT count(*) FROM %s WHERE type='view'" },
3996 { "schema size:",
3997 "SELECT total(length(sql)) FROM %s" },
3998 };
drh2ce15c32017-07-11 13:34:40 +00003999 int i;
4000 char *zSchemaTab;
4001 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004002 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004003 unsigned char aHdr[100];
4004 open_db(p, 0);
4005 if( p->db==0 ) return 1;
drh512e6c32017-10-11 17:51:08 +00004006 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4007 -1, &pStmt, 0);
4008 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4009 if( sqlite3_step(pStmt)==SQLITE_ROW
4010 && sqlite3_column_bytes(pStmt,0)>100
4011 ){
4012 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4013 sqlite3_finalize(pStmt);
4014 }else{
drh2ce15c32017-07-11 13:34:40 +00004015 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004016 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004017 return 1;
4018 }
4019 i = get2byteInt(aHdr+16);
4020 if( i==1 ) i = 65536;
4021 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4022 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4023 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4024 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4025 for(i=0; i<ArraySize(aField); i++){
4026 int ofst = aField[i].ofst;
4027 unsigned int val = get4byteInt(aHdr + ofst);
4028 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4029 switch( ofst ){
4030 case 56: {
4031 if( val==1 ) raw_printf(p->out, " (utf8)");
4032 if( val==2 ) raw_printf(p->out, " (utf16le)");
4033 if( val==3 ) raw_printf(p->out, " (utf16be)");
4034 }
4035 }
4036 raw_printf(p->out, "\n");
4037 }
4038 if( zDb==0 ){
4039 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4040 }else if( strcmp(zDb,"temp")==0 ){
4041 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4042 }else{
4043 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4044 }
4045 for(i=0; i<ArraySize(aQuery); i++){
4046 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4047 int val = db_int(p, zSql);
4048 sqlite3_free(zSql);
4049 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4050 }
4051 sqlite3_free(zSchemaTab);
4052 return 0;
4053}
4054
4055/*
4056** Print the current sqlite3_errmsg() value to stderr and return 1.
4057*/
4058static int shellDatabaseError(sqlite3 *db){
4059 const char *zErr = sqlite3_errmsg(db);
4060 utf8_printf(stderr, "Error: %s\n", zErr);
4061 return 1;
4062}
4063
4064/*
4065** Print an out-of-memory message to stderr and return 1.
4066*/
4067static int shellNomemError(void){
4068 raw_printf(stderr, "Error: out of memory\n");
4069 return 1;
4070}
4071
4072/*
4073** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4074** if they match and FALSE (0) if they do not match.
4075**
4076** Globbing rules:
4077**
4078** '*' Matches any sequence of zero or more characters.
4079**
4080** '?' Matches exactly one character.
4081**
4082** [...] Matches one character from the enclosed list of
4083** characters.
4084**
4085** [^...] Matches one character not in the enclosed list.
4086**
4087** '#' Matches any sequence of one or more digits with an
4088** optional + or - sign in front
4089**
4090** ' ' Any span of whitespace matches any other span of
4091** whitespace.
4092**
4093** Extra whitespace at the end of z[] is ignored.
4094*/
4095static int testcase_glob(const char *zGlob, const char *z){
4096 int c, c2;
4097 int invert;
4098 int seen;
4099
4100 while( (c = (*(zGlob++)))!=0 ){
4101 if( IsSpace(c) ){
4102 if( !IsSpace(*z) ) return 0;
4103 while( IsSpace(*zGlob) ) zGlob++;
4104 while( IsSpace(*z) ) z++;
4105 }else if( c=='*' ){
4106 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4107 if( c=='?' && (*(z++))==0 ) return 0;
4108 }
4109 if( c==0 ){
4110 return 1;
4111 }else if( c=='[' ){
4112 while( *z && testcase_glob(zGlob-1,z)==0 ){
4113 z++;
4114 }
4115 return (*z)!=0;
4116 }
4117 while( (c2 = (*(z++)))!=0 ){
4118 while( c2!=c ){
4119 c2 = *(z++);
4120 if( c2==0 ) return 0;
4121 }
4122 if( testcase_glob(zGlob,z) ) return 1;
4123 }
4124 return 0;
4125 }else if( c=='?' ){
4126 if( (*(z++))==0 ) return 0;
4127 }else if( c=='[' ){
4128 int prior_c = 0;
4129 seen = 0;
4130 invert = 0;
4131 c = *(z++);
4132 if( c==0 ) return 0;
4133 c2 = *(zGlob++);
4134 if( c2=='^' ){
4135 invert = 1;
4136 c2 = *(zGlob++);
4137 }
4138 if( c2==']' ){
4139 if( c==']' ) seen = 1;
4140 c2 = *(zGlob++);
4141 }
4142 while( c2 && c2!=']' ){
4143 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4144 c2 = *(zGlob++);
4145 if( c>=prior_c && c<=c2 ) seen = 1;
4146 prior_c = 0;
4147 }else{
4148 if( c==c2 ){
4149 seen = 1;
4150 }
4151 prior_c = c2;
4152 }
4153 c2 = *(zGlob++);
4154 }
4155 if( c2==0 || (seen ^ invert)==0 ) return 0;
4156 }else if( c=='#' ){
4157 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4158 if( !IsDigit(z[0]) ) return 0;
4159 z++;
4160 while( IsDigit(z[0]) ){ z++; }
4161 }else{
4162 if( c!=(*(z++)) ) return 0;
4163 }
4164 }
4165 while( IsSpace(*z) ){ z++; }
4166 return *z==0;
4167}
4168
4169
4170/*
4171** Compare the string as a command-line option with either one or two
4172** initial "-" characters.
4173*/
4174static int optionMatch(const char *zStr, const char *zOpt){
4175 if( zStr[0]!='-' ) return 0;
4176 zStr++;
4177 if( zStr[0]=='-' ) zStr++;
4178 return strcmp(zStr, zOpt)==0;
4179}
4180
4181/*
4182** Delete a file.
4183*/
4184int shellDeleteFile(const char *zFilename){
4185 int rc;
4186#ifdef _WIN32
4187 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4188 rc = _wunlink(z);
4189 sqlite3_free(z);
4190#else
4191 rc = unlink(zFilename);
4192#endif
4193 return rc;
4194}
4195
4196
4197/*
4198** The implementation of SQL scalar function fkey_collate_clause(), used
4199** by the ".lint fkey-indexes" command. This scalar function is always
4200** called with four arguments - the parent table name, the parent column name,
4201** the child table name and the child column name.
4202**
4203** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4204**
4205** If either of the named tables or columns do not exist, this function
4206** returns an empty string. An empty string is also returned if both tables
4207** and columns exist but have the same default collation sequence. Or,
4208** if both exist but the default collation sequences are different, this
4209** function returns the string " COLLATE <parent-collation>", where
4210** <parent-collation> is the default collation sequence of the parent column.
4211*/
4212static void shellFkeyCollateClause(
4213 sqlite3_context *pCtx,
4214 int nVal,
4215 sqlite3_value **apVal
4216){
4217 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4218 const char *zParent;
4219 const char *zParentCol;
4220 const char *zParentSeq;
4221 const char *zChild;
4222 const char *zChildCol;
4223 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4224 int rc;
4225
4226 assert( nVal==4 );
4227 zParent = (const char*)sqlite3_value_text(apVal[0]);
4228 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4229 zChild = (const char*)sqlite3_value_text(apVal[2]);
4230 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4231
4232 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4233 rc = sqlite3_table_column_metadata(
4234 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4235 );
4236 if( rc==SQLITE_OK ){
4237 rc = sqlite3_table_column_metadata(
4238 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4239 );
4240 }
4241
4242 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4243 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4244 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4245 sqlite3_free(z);
4246 }
4247}
4248
4249
4250/*
4251** The implementation of dot-command ".lint fkey-indexes".
4252*/
4253static int lintFkeyIndexes(
4254 ShellState *pState, /* Current shell tool state */
4255 char **azArg, /* Array of arguments passed to dot command */
4256 int nArg /* Number of entries in azArg[] */
4257){
4258 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4259 FILE *out = pState->out; /* Stream to write non-error output to */
4260 int bVerbose = 0; /* If -verbose is present */
4261 int bGroupByParent = 0; /* If -groupbyparent is present */
4262 int i; /* To iterate through azArg[] */
4263 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4264 int rc; /* Return code */
4265 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4266
4267 /*
4268 ** This SELECT statement returns one row for each foreign key constraint
4269 ** in the schema of the main database. The column values are:
4270 **
4271 ** 0. The text of an SQL statement similar to:
4272 **
danf9679312017-12-01 18:40:18 +00004273 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00004274 **
danf9679312017-12-01 18:40:18 +00004275 ** This SELECT is similar to the one that the foreign keys implementation
4276 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00004277 ** be used to optimize this query, then it can also be used by the FK
4278 ** implementation to optimize DELETE or UPDATE statements on the parent
4279 ** table.
4280 **
4281 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4282 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4283 ** contains an index that can be used to optimize the query.
4284 **
4285 ** 2. Human readable text that describes the child table and columns. e.g.
4286 **
4287 ** "child_table(child_key1, child_key2)"
4288 **
4289 ** 3. Human readable text that describes the parent table and columns. e.g.
4290 **
4291 ** "parent_table(parent_key1, parent_key2)"
4292 **
4293 ** 4. A full CREATE INDEX statement for an index that could be used to
4294 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4295 **
4296 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4297 **
4298 ** 5. The name of the parent table.
4299 **
4300 ** These six values are used by the C logic below to generate the report.
4301 */
4302 const char *zSql =
4303 "SELECT "
danf9679312017-12-01 18:40:18 +00004304 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00004305 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4306 " || fkey_collate_clause("
4307 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4308 ", "
4309 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4310 " || group_concat('*=?', ' AND ') || ')'"
4311 ", "
4312 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4313 ", "
4314 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4315 ", "
4316 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4317 " || ' ON ' || quote(s.name) || '('"
4318 " || group_concat(quote(f.[from]) ||"
4319 " fkey_collate_clause("
4320 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4321 " || ');'"
4322 ", "
4323 " f.[table] "
4324 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4325 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4326 "GROUP BY s.name, f.id "
4327 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4328 ;
4329 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4330
4331 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00004332 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00004333 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4334 bVerbose = 1;
4335 }
4336 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4337 bGroupByParent = 1;
4338 zIndent = " ";
4339 }
4340 else{
4341 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4342 azArg[0], azArg[1]
4343 );
4344 return SQLITE_ERROR;
4345 }
4346 }
4347
4348 /* Register the fkey_collate_clause() SQL function */
4349 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4350 0, shellFkeyCollateClause, 0, 0
4351 );
4352
4353
4354 if( rc==SQLITE_OK ){
4355 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4356 }
4357 if( rc==SQLITE_OK ){
4358 sqlite3_bind_int(pSql, 1, bGroupByParent);
4359 }
4360
4361 if( rc==SQLITE_OK ){
4362 int rc2;
4363 char *zPrev = 0;
4364 while( SQLITE_ROW==sqlite3_step(pSql) ){
4365 int res = -1;
4366 sqlite3_stmt *pExplain = 0;
4367 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4368 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4369 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4370 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4371 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4372 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4373
4374 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4375 if( rc!=SQLITE_OK ) break;
4376 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4377 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4378 res = (
4379 0==sqlite3_strglob(zGlob, zPlan)
4380 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4381 );
4382 }
4383 rc = sqlite3_finalize(pExplain);
4384 if( rc!=SQLITE_OK ) break;
4385
4386 if( res<0 ){
4387 raw_printf(stderr, "Error: internal error");
4388 break;
4389 }else{
4390 if( bGroupByParent
4391 && (bVerbose || res==0)
4392 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4393 ){
4394 raw_printf(out, "-- Parent table %s\n", zParent);
4395 sqlite3_free(zPrev);
4396 zPrev = sqlite3_mprintf("%s", zParent);
4397 }
4398
4399 if( res==0 ){
4400 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4401 }else if( bVerbose ){
4402 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4403 zIndent, zFrom, zTarget
4404 );
4405 }
4406 }
4407 }
4408 sqlite3_free(zPrev);
4409
4410 if( rc!=SQLITE_OK ){
4411 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4412 }
4413
4414 rc2 = sqlite3_finalize(pSql);
4415 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4416 rc = rc2;
4417 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4418 }
4419 }else{
4420 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4421 }
4422
4423 return rc;
4424}
4425
4426/*
4427** Implementation of ".lint" dot command.
4428*/
4429static int lintDotCommand(
4430 ShellState *pState, /* Current shell tool state */
4431 char **azArg, /* Array of arguments passed to dot command */
4432 int nArg /* Number of entries in azArg[] */
4433){
4434 int n;
drhaf2770f2018-01-05 14:55:43 +00004435 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00004436 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4437 return lintFkeyIndexes(pState, azArg, nArg);
4438
4439 usage:
4440 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4441 raw_printf(stderr, "Where sub-commands are:\n");
4442 raw_printf(stderr, " fkey-indexes\n");
4443 return SQLITE_ERROR;
4444}
4445
drhe37c0e12018-01-06 19:19:50 +00004446#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4447/*********************************************************************************
4448** The ".archive" or ".ar" command.
4449*/
danfd0245d2017-12-07 15:44:29 +00004450static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00004451 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00004452 int *pRc,
4453 const char *zSql,
4454 sqlite3_stmt **ppStmt
4455){
4456 *ppStmt = 0;
4457 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004458 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00004459 if( rc!=SQLITE_OK ){
4460 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00004461 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00004462 );
4463 *pRc = rc;
4464 }
4465 }
4466}
4467
danac15e2d2017-12-14 19:15:07 +00004468static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00004469 sqlite3 *db,
4470 int *pRc,
danac15e2d2017-12-14 19:15:07 +00004471 sqlite3_stmt **ppStmt,
4472 const char *zFmt,
4473 ...
dan3f67ddf2017-12-13 20:04:53 +00004474){
danac15e2d2017-12-14 19:15:07 +00004475 *ppStmt = 0;
4476 if( *pRc==SQLITE_OK ){
4477 va_list ap;
4478 char *z;
4479 va_start(ap, zFmt);
4480 z = sqlite3_vmprintf(zFmt, ap);
dan3f67ddf2017-12-13 20:04:53 +00004481 if( z==0 ){
4482 *pRc = SQLITE_NOMEM;
4483 }else{
4484 shellPrepare(db, pRc, z, ppStmt);
4485 sqlite3_free(z);
4486 }
dan3f67ddf2017-12-13 20:04:53 +00004487 }
4488}
4489
danfd0245d2017-12-07 15:44:29 +00004490static void shellFinalize(
4491 int *pRc,
4492 sqlite3_stmt *pStmt
4493){
dan25c12182017-12-07 21:03:33 +00004494 if( pStmt ){
4495 sqlite3 *db = sqlite3_db_handle(pStmt);
4496 int rc = sqlite3_finalize(pStmt);
4497 if( *pRc==SQLITE_OK ){
4498 if( rc!=SQLITE_OK ){
4499 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4500 }
4501 *pRc = rc;
4502 }
4503 }
danfd0245d2017-12-07 15:44:29 +00004504}
4505
4506static void shellReset(
4507 int *pRc,
4508 sqlite3_stmt *pStmt
4509){
4510 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00004511 if( *pRc==SQLITE_OK ){
4512 if( rc!=SQLITE_OK ){
4513 sqlite3 *db = sqlite3_db_handle(pStmt);
4514 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4515 }
4516 *pRc = rc;
4517 }
danfd0245d2017-12-07 15:44:29 +00004518}
drhe37c0e12018-01-06 19:19:50 +00004519/*
dan88be0202017-12-09 17:58:02 +00004520** Structure representing a single ".ar" command.
4521*/
4522typedef struct ArCommand ArCommand;
4523struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00004524 u8 eCmd; /* An AR_CMD_* value */
4525 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00004526 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00004527 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00004528 u8 bAppend; /* True if --append */
drhb376b3d2018-01-10 13:11:51 +00004529 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00004530 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00004531 const char *zFile; /* --file argument, or NULL */
4532 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00004533 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00004534 ShellState *p; /* Shell state */
4535 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00004536};
4537
4538/*
4539** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4540*/
dan0d0547f2017-12-14 15:40:42 +00004541static int arUsage(FILE *f){
4542 raw_printf(f,
4543"\n"
4544"Usage: .ar [OPTION...] [FILE...]\n"
4545"The .ar command manages sqlar archives.\n"
4546"\n"
4547"Examples:\n"
4548" .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4549" .ar -tf archive.sar # List members of archive.sar\n"
4550" .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4551"\n"
4552"Each command line must feature exactly one command option:\n"
4553" -c, --create Create a new archive\n"
4554" -u, --update Update or add files to an existing archive\n"
4555" -t, --list List contents of archive\n"
4556" -x, --extract Extract files from archive\n"
4557"\n"
4558"And zero or more optional options:\n"
4559" -v, --verbose Print each filename as it is processed\n"
4560" -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
4561" -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
drhb376b3d2018-01-10 13:11:51 +00004562" -n, --dryrun Show the SQL that would have occurred\n"
drha5676c42018-01-10 15:17:34 +00004563" -a, --append Append the SQLAR to an existing file\n"
dan0d0547f2017-12-14 15:40:42 +00004564"\n"
4565"See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4566"\n"
4567);
4568 return SQLITE_ERROR;
4569}
4570
4571/*
4572** Print an error message for the .ar command to stderr and return
4573** SQLITE_ERROR.
4574*/
4575static int arErrorMsg(const char *zFmt, ...){
4576 va_list ap;
4577 char *z;
4578 va_start(ap, zFmt);
4579 z = sqlite3_vmprintf(zFmt, ap);
4580 va_end(ap);
4581 raw_printf(stderr, "Error: %s (try \".ar --help\")\n", z);
4582 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00004583 return SQLITE_ERROR;
4584}
4585
4586/*
4587** Values for ArCommand.eCmd.
4588*/
dand4b56e52017-12-12 20:04:59 +00004589#define AR_CMD_CREATE 1
4590#define AR_CMD_EXTRACT 2
4591#define AR_CMD_LIST 3
4592#define AR_CMD_UPDATE 4
dan0d0547f2017-12-14 15:40:42 +00004593#define AR_CMD_HELP 5
dand4b56e52017-12-12 20:04:59 +00004594
4595/*
4596** Other (non-command) switches.
4597*/
drhb376b3d2018-01-10 13:11:51 +00004598#define AR_SWITCH_VERBOSE 6
4599#define AR_SWITCH_FILE 7
4600#define AR_SWITCH_DIRECTORY 8
drha5676c42018-01-10 15:17:34 +00004601#define AR_SWITCH_APPEND 9
drhb376b3d2018-01-10 13:11:51 +00004602#define AR_SWITCH_DRYRUN 10
dand4b56e52017-12-12 20:04:59 +00004603
4604static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
4605 switch( eSwitch ){
4606 case AR_CMD_CREATE:
4607 case AR_CMD_EXTRACT:
4608 case AR_CMD_LIST:
4609 case AR_CMD_UPDATE:
dan0d0547f2017-12-14 15:40:42 +00004610 case AR_CMD_HELP:
4611 if( pAr->eCmd ){
4612 return arErrorMsg("multiple command options");
4613 }
dand4b56e52017-12-12 20:04:59 +00004614 pAr->eCmd = eSwitch;
4615 break;
4616
drhb376b3d2018-01-10 13:11:51 +00004617 case AR_SWITCH_DRYRUN:
4618 pAr->bDryRun = 1;
4619 break;
dand4b56e52017-12-12 20:04:59 +00004620 case AR_SWITCH_VERBOSE:
4621 pAr->bVerbose = 1;
4622 break;
drha5676c42018-01-10 15:17:34 +00004623 case AR_SWITCH_APPEND:
4624 pAr->bAppend = 1;
dan5a78b812017-12-27 18:54:11 +00004625 break;
dand4b56e52017-12-12 20:04:59 +00004626
4627 case AR_SWITCH_FILE:
4628 pAr->zFile = zArg;
4629 break;
4630 case AR_SWITCH_DIRECTORY:
4631 pAr->zDir = zArg;
4632 break;
4633 }
4634
4635 return SQLITE_OK;
4636}
dan88be0202017-12-09 17:58:02 +00004637
4638/*
4639** Parse the command line for an ".ar" command. The results are written into
4640** structure (*pAr). SQLITE_OK is returned if the command line is parsed
4641** successfully, otherwise an error message is written to stderr and
4642** SQLITE_ERROR returned.
4643*/
4644static int arParseCommand(
4645 char **azArg, /* Array of arguments passed to dot command */
4646 int nArg, /* Number of entries in azArg[] */
4647 ArCommand *pAr /* Populate this object */
4648){
dand4b56e52017-12-12 20:04:59 +00004649 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00004650 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00004651 char cShort;
4652 u8 eSwitch;
4653 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00004654 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00004655 { "create", 'c', AR_CMD_CREATE, 0 },
4656 { "extract", 'x', AR_CMD_EXTRACT, 0 },
4657 { "list", 't', AR_CMD_LIST, 0 },
4658 { "update", 'u', AR_CMD_UPDATE, 0 },
4659 { "help", 'h', AR_CMD_HELP, 0 },
4660 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
4661 { "file", 'f', AR_SWITCH_FILE, 1 },
4662 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drha5676c42018-01-10 15:17:34 +00004663 { "append", 'a', AR_SWITCH_APPEND, 0 },
drhb376b3d2018-01-10 13:11:51 +00004664 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00004665 };
4666 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
4667 struct ArSwitch *pEnd = &aSwitch[nSwitch];
4668
dan88be0202017-12-09 17:58:02 +00004669 if( nArg<=1 ){
dan0d0547f2017-12-14 15:40:42 +00004670 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00004671 }else{
4672 char *z = azArg[1];
4673 memset(pAr, 0, sizeof(ArCommand));
4674
4675 if( z[0]!='-' ){
4676 /* Traditional style [tar] invocation */
4677 int i;
4678 int iArg = 2;
4679 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00004680 const char *zArg = 0;
4681 struct ArSwitch *pOpt;
4682 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4683 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00004684 }
dan0d0547f2017-12-14 15:40:42 +00004685 if( pOpt==pEnd ){
4686 return arErrorMsg("unrecognized option: %c", z[i]);
4687 }
dand4b56e52017-12-12 20:04:59 +00004688 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00004689 if( iArg>=nArg ){
4690 return arErrorMsg("option requires an argument: %c",z[i]);
4691 }
dand4b56e52017-12-12 20:04:59 +00004692 zArg = azArg[iArg++];
4693 }
4694 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00004695 }
dan88be0202017-12-09 17:58:02 +00004696 pAr->nArg = nArg-iArg;
4697 if( pAr->nArg>0 ){
4698 pAr->azArg = &azArg[iArg];
4699 }
dand4b56e52017-12-12 20:04:59 +00004700 }else{
4701 /* Non-traditional invocation */
4702 int iArg;
4703 for(iArg=1; iArg<nArg; iArg++){
4704 int n;
4705 z = azArg[iArg];
4706 if( z[0]!='-' ){
4707 /* All remaining command line words are command arguments. */
4708 pAr->azArg = &azArg[iArg];
4709 pAr->nArg = nArg-iArg;
4710 break;
4711 }
drhaf2770f2018-01-05 14:55:43 +00004712 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00004713
4714 if( z[1]!='-' ){
4715 int i;
4716 /* One or more short options */
4717 for(i=1; i<n; i++){
4718 const char *zArg = 0;
4719 struct ArSwitch *pOpt;
4720 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4721 if( z[i]==pOpt->cShort ) break;
4722 }
dan0d0547f2017-12-14 15:40:42 +00004723 if( pOpt==pEnd ){
4724 return arErrorMsg("unrecognized option: %c\n", z[i]);
4725 }
dand4b56e52017-12-12 20:04:59 +00004726 if( pOpt->bArg ){
4727 if( i<(n-1) ){
4728 zArg = &z[i+1];
4729 i = n;
4730 }else{
dan0d0547f2017-12-14 15:40:42 +00004731 if( iArg>=(nArg-1) ){
4732 return arErrorMsg("option requires an argument: %c\n",z[i]);
4733 }
dand4b56e52017-12-12 20:04:59 +00004734 zArg = azArg[++iArg];
4735 }
4736 }
4737 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
4738 }
4739 }else if( z[2]=='\0' ){
4740 /* A -- option, indicating that all remaining command line words
4741 ** are command arguments. */
4742 pAr->azArg = &azArg[iArg+1];
4743 pAr->nArg = nArg-iArg-1;
4744 break;
4745 }else{
4746 /* A long option */
4747 const char *zArg = 0; /* Argument for option, if any */
4748 struct ArSwitch *pMatch = 0; /* Matching option */
4749 struct ArSwitch *pOpt; /* Iterator */
4750 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4751 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00004752 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00004753 if( pMatch ){
dan0d0547f2017-12-14 15:40:42 +00004754 return arErrorMsg("ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00004755 }else{
4756 pMatch = pOpt;
4757 }
4758 }
4759 }
4760
4761 if( pMatch==0 ){
dan0d0547f2017-12-14 15:40:42 +00004762 return arErrorMsg("unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00004763 }
4764 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00004765 if( iArg>=(nArg-1) ){
4766 return arErrorMsg("option requires an argument: %s", z);
4767 }
dand4b56e52017-12-12 20:04:59 +00004768 zArg = azArg[++iArg];
4769 }
4770 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
4771 }
4772 }
dan88be0202017-12-09 17:58:02 +00004773 }
4774 }
4775
4776 return SQLITE_OK;
4777}
4778
4779/*
dan3f67ddf2017-12-13 20:04:53 +00004780** This function assumes that all arguments within the ArCommand.azArg[]
4781** array refer to archive members, as for the --extract or --list commands.
4782** It checks that each of them are present. If any specified file is not
4783** present in the archive, an error is printed to stderr and an error
4784** code returned. Otherwise, if all specified arguments are present in
4785** the archive, SQLITE_OK is returned.
4786**
4787** This function strips any trailing '/' characters from each argument.
4788** This is consistent with the way the [tar] command seems to work on
4789** Linux.
4790*/
drhb376b3d2018-01-10 13:11:51 +00004791static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00004792 int rc = SQLITE_OK;
4793 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00004794 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00004795 sqlite3_stmt *pTest = 0;
4796
drhb376b3d2018-01-10 13:11:51 +00004797 shellPreparePrintf(pAr->db, &rc, &pTest,
4798 "SELECT name FROM %s WHERE name=$name",
4799 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00004800 );
drhb376b3d2018-01-10 13:11:51 +00004801 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00004802 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
4803 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00004804 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00004805 int bOk = 0;
4806 while( n>0 && z[n-1]=='/' ) n--;
4807 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00004808 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00004809 if( SQLITE_ROW==sqlite3_step(pTest) ){
4810 bOk = 1;
4811 }
4812 shellReset(&rc, pTest);
4813 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00004814 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00004815 rc = SQLITE_ERROR;
4816 }
4817 }
4818 shellFinalize(&rc, pTest);
4819 }
dan3f67ddf2017-12-13 20:04:53 +00004820 return rc;
4821}
4822
4823/*
4824** Format a WHERE clause that can be used against the "sqlar" table to
4825** identify all archive members that match the command arguments held
4826** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
4827** The caller is responsible for eventually calling sqlite3_free() on
4828** any non-NULL (*pzWhere) value.
4829*/
4830static void arWhereClause(
4831 int *pRc,
4832 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00004833 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00004834){
4835 char *zWhere = 0;
4836 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00004837 if( pAr->nArg==0 ){
4838 zWhere = sqlite3_mprintf("1");
4839 }else{
4840 int i;
4841 const char *zSep = "";
4842 for(i=0; i<pAr->nArg; i++){
4843 const char *z = pAr->azArg[i];
4844 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00004845 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
4846 zWhere, zSep, z, strlen30(z)+1, z
4847 );
danac15e2d2017-12-14 19:15:07 +00004848 if( zWhere==0 ){
4849 *pRc = SQLITE_NOMEM;
4850 break;
4851 }
4852 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00004853 }
dan3f67ddf2017-12-13 20:04:53 +00004854 }
4855 }
4856 *pzWhere = zWhere;
4857}
4858
4859/*
dan88be0202017-12-09 17:58:02 +00004860** Implementation of .ar "lisT" command.
4861*/
drhb376b3d2018-01-10 13:11:51 +00004862static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00004863 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00004864 const char *azCols[] = {
4865 "name",
drh410cad92018-01-10 17:19:16 +00004866 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00004867 };
dan5a78b812017-12-27 18:54:11 +00004868
dan3f67ddf2017-12-13 20:04:53 +00004869 char *zWhere = 0;
4870 sqlite3_stmt *pSql = 0;
4871 int rc;
4872
drhb376b3d2018-01-10 13:11:51 +00004873 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00004874 arWhereClause(&rc, pAr, &zWhere);
4875
drhb376b3d2018-01-10 13:11:51 +00004876 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
4877 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00004878 if( pAr->bDryRun ){
4879 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
4880 }else{
4881 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
4882 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00004883 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
4884 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00004885 sqlite3_column_int(pSql, 1),
4886 sqlite3_column_text(pSql, 2),
4887 sqlite3_column_text(pSql, 3)
4888 );
4889 }else{
4890 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
4891 }
danb5090e42017-12-27 21:13:21 +00004892 }
dan3f67ddf2017-12-13 20:04:53 +00004893 }
dan5a78b812017-12-27 18:54:11 +00004894 shellFinalize(&rc, pSql);
dan3f67ddf2017-12-13 20:04:53 +00004895 return rc;
dan88be0202017-12-09 17:58:02 +00004896}
4897
4898
danfd0245d2017-12-07 15:44:29 +00004899/*
4900** Implementation of .ar "eXtract" command.
4901*/
drhb376b3d2018-01-10 13:11:51 +00004902static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00004903 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00004904 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00004905 " ($dir || name),"
4906 " writefile(($dir || name), %s, mode, mtime) "
4907 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)";
dan5a78b812017-12-27 18:54:11 +00004908
4909 const char *azExtraArg[] = {
4910 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00004911 "data"
dan5a78b812017-12-27 18:54:11 +00004912 };
dan5a78b812017-12-27 18:54:11 +00004913
danfd0245d2017-12-07 15:44:29 +00004914 sqlite3_stmt *pSql = 0;
4915 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00004916 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00004917 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00004918 int i, j;
dan2ad09492017-12-09 18:28:22 +00004919
dan3f67ddf2017-12-13 20:04:53 +00004920 /* If arguments are specified, check that they actually exist within
4921 ** the archive before proceeding. And formulate a WHERE clause to
4922 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00004923 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00004924 arWhereClause(&rc, pAr, &zWhere);
4925
4926 if( rc==SQLITE_OK ){
4927 if( pAr->zDir ){
4928 zDir = sqlite3_mprintf("%s/", pAr->zDir);
4929 }else{
4930 zDir = sqlite3_mprintf("");
4931 }
4932 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00004933 }
danfd0245d2017-12-07 15:44:29 +00004934
drhb376b3d2018-01-10 13:11:51 +00004935 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
4936 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00004937 );
4938
dan2ad09492017-12-09 18:28:22 +00004939 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00004940 j = sqlite3_bind_parameter_index(pSql, "$dir");
4941 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00004942
danac15e2d2017-12-14 19:15:07 +00004943 /* Run the SELECT statement twice. The first time, writefile() is called
4944 ** for all archive members that should be extracted. The second time,
4945 ** only for the directories. This is because the timestamps for
4946 ** extracted directories must be reset after they are populated (as
4947 ** populating them changes the timestamp). */
4948 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00004949 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
4950 sqlite3_bind_int(pSql, j, i);
4951 if( pAr->bDryRun ){
4952 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
4953 }else{
4954 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
4955 if( i==0 && pAr->bVerbose ){
4956 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
4957 }
danac15e2d2017-12-14 19:15:07 +00004958 }
4959 }
4960 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00004961 }
danac15e2d2017-12-14 19:15:07 +00004962 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00004963 }
dan25c12182017-12-07 21:03:33 +00004964
dan2ad09492017-12-09 18:28:22 +00004965 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00004966 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00004967 return rc;
4968}
4969
drhb376b3d2018-01-10 13:11:51 +00004970/*
4971** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
4972*/
4973static int arExecSql(ArCommand *pAr, const char *zSql){
4974 int rc;
4975 if( pAr->bDryRun ){
4976 utf8_printf(pAr->p->out, "%s\n", zSql);
4977 rc = SQLITE_OK;
4978 }else{
drh410cad92018-01-10 17:19:16 +00004979 char *zErr = 0;
4980 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
4981 if( zErr ){
4982 utf8_printf(stdout, "ERROR: %s\n", zErr);
4983 sqlite3_free(zErr);
4984 }
drhb376b3d2018-01-10 13:11:51 +00004985 }
4986 return rc;
4987}
4988
dan1ad3f612017-12-11 20:22:02 +00004989
danfd0245d2017-12-07 15:44:29 +00004990/*
dan06741a32017-12-13 20:17:18 +00004991** Implementation of .ar "create" and "update" commands.
danfd0245d2017-12-07 15:44:29 +00004992**
4993** Create the "sqlar" table in the database if it does not already exist.
4994** Then add each file in the azFile[] array to the archive. Directories
4995** are added recursively. If argument bVerbose is non-zero, a message is
4996** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00004997**
4998** The create command is the same as update, except that it drops
4999** any existing "sqlar" table before beginning.
danfd0245d2017-12-07 15:44:29 +00005000*/
drhb376b3d2018-01-10 13:11:51 +00005001static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00005002 ArCommand *pAr, /* Command arguments and options */
drhb376b3d2018-01-10 13:11:51 +00005003 int bUpdate /* true for a --create. false for --update */
danfd0245d2017-12-07 15:44:29 +00005004){
dand4b56e52017-12-12 20:04:59 +00005005 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00005006 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5007 " name TEXT PRIMARY KEY, -- name of the file\n"
5008 " mode INT, -- access permissions\n"
5009 " mtime INT, -- last modification time\n"
5010 " sz INT, -- original file size\n"
5011 " data BLOB -- compressed content\n"
5012 ")";
dand4b56e52017-12-12 20:04:59 +00005013 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh634c70f2018-01-10 16:50:18 +00005014 const char *zInsertFmt =
5015 "REPLACE INTO sqlar(name,mode,mtime,sz,data)\n"
5016 " SELECT\n"
5017 " %s,\n"
5018 " mode,\n"
5019 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00005020 " CASE substr(lsmode(mode),1,1)\n"
5021 " WHEN '-' THEN length(data)\n"
5022 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00005023 " ELSE -1 END,\n"
drh410cad92018-01-10 17:19:16 +00005024 " CASE WHEN lsmode(mode) LIKE 'd%%' THEN NULL else data END\n"
drh634c70f2018-01-10 16:50:18 +00005025 " FROM fsdir(%Q,%Q)\n"
drh410cad92018-01-10 17:19:16 +00005026 " WHERE lsmode(mode) NOT LIKE '?%%';";
danfd0245d2017-12-07 15:44:29 +00005027 int i; /* For iterating through azFile[] */
5028 int rc; /* Return code */
5029
drhb376b3d2018-01-10 13:11:51 +00005030 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00005031 if( rc!=SQLITE_OK ) return rc;
dan06741a32017-12-13 20:17:18 +00005032 if( bUpdate==0 ){
drhb376b3d2018-01-10 13:11:51 +00005033 rc = arExecSql(pAr, zDrop);
dan06741a32017-12-13 20:17:18 +00005034 if( rc!=SQLITE_OK ) return rc;
5035 }
drhb376b3d2018-01-10 13:11:51 +00005036 rc = arExecSql(pAr, zCreate);
dan88be0202017-12-09 17:58:02 +00005037 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
drh634c70f2018-01-10 16:50:18 +00005038 char *zSql = sqlite3_mprintf(zInsertFmt,
5039 pAr->bVerbose ? "shell_putsnl(name)" : "name",
5040 pAr->azArg[i], pAr->zDir);
5041 rc = arExecSql(pAr, zSql);
5042 sqlite3_free(zSql);
danfd0245d2017-12-07 15:44:29 +00005043 }
danfd0245d2017-12-07 15:44:29 +00005044 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005045 arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
danfd0245d2017-12-07 15:44:29 +00005046 }else{
drhb376b3d2018-01-10 13:11:51 +00005047 rc = arExecSql(pAr, "RELEASE ar;");
danfd0245d2017-12-07 15:44:29 +00005048 }
danfd0245d2017-12-07 15:44:29 +00005049 return rc;
5050}
5051
5052/*
5053** Implementation of ".ar" dot command.
5054*/
5055static int arDotCommand(
5056 ShellState *pState, /* Current shell tool state */
5057 char **azArg, /* Array of arguments passed to dot command */
5058 int nArg /* Number of entries in azArg[] */
5059){
dan88be0202017-12-09 17:58:02 +00005060 ArCommand cmd;
5061 int rc;
drh34660642018-01-10 17:39:54 +00005062 memset(&cmd, 0, sizeof(cmd));
dan88be0202017-12-09 17:58:02 +00005063 rc = arParseCommand(azArg, nArg, &cmd);
5064 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00005065 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00005066 cmd.p = pState;
5067 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00005068 if( cmd.zFile ){
5069 eDbType = deduceDatabaseType(cmd.zFile);
5070 }else{
5071 eDbType = pState->openMode;
5072 }
5073 if( eDbType==SHELL_OPEN_ZIPFILE ){
5074 if( cmd.zFile==0 ){
5075 cmd.zSrcTable = sqlite3_mprintf("zip");
drha82c95b2018-01-10 14:00:00 +00005076 }else{
drha5676c42018-01-10 15:17:34 +00005077 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
drhb376b3d2018-01-10 13:11:51 +00005078 }
dan5a78b812017-12-27 18:54:11 +00005079 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
drhb376b3d2018-01-10 13:11:51 +00005080 utf8_printf(stderr, "zip archives are read-only\n");
drha5676c42018-01-10 15:17:34 +00005081 rc = SQLITE_ERROR;
5082 goto end_ar_command;
dan5a78b812017-12-27 18:54:11 +00005083 }
drha5676c42018-01-10 15:17:34 +00005084 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00005085 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00005086 int flags;
drha5676c42018-01-10 15:17:34 +00005087 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
dand4b56e52017-12-12 20:04:59 +00005088 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
5089 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
5090 }else{
5091 flags = SQLITE_OPEN_READONLY;
5092 }
drha82c95b2018-01-10 14:00:00 +00005093 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00005094 if( cmd.bDryRun ){
5095 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
5096 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
5097 }
5098 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
5099 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00005100 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005101 utf8_printf(stderr, "cannot open file: %s (%s)\n",
5102 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00005103 );
drha5676c42018-01-10 15:17:34 +00005104 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00005105 }
drhb376b3d2018-01-10 13:11:51 +00005106 sqlite3_fileio_init(cmd.db, 0, 0);
mistachkin3acaf4c2018-01-05 00:53:03 +00005107#ifdef SQLITE_HAVE_ZLIB
drhb376b3d2018-01-10 13:11:51 +00005108 sqlite3_sqlar_init(cmd.db, 0, 0);
mistachkin3acaf4c2018-01-05 00:53:03 +00005109#endif
drh34660642018-01-10 17:39:54 +00005110 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
5111 shellPutsFunc, 0, 0);
5112
dand4b56e52017-12-12 20:04:59 +00005113 }
drha5676c42018-01-10 15:17:34 +00005114 if( cmd.zSrcTable==0 ){
drh634c70f2018-01-10 16:50:18 +00005115 if( cmd.eCmd!=AR_CMD_CREATE
5116 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
5117 ){
drha5676c42018-01-10 15:17:34 +00005118 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
5119 rc = SQLITE_ERROR;
5120 goto end_ar_command;
5121 }
5122 cmd.zSrcTable = sqlite3_mprintf("sqlar");
5123 }
dand4b56e52017-12-12 20:04:59 +00005124
dan88be0202017-12-09 17:58:02 +00005125 switch( cmd.eCmd ){
5126 case AR_CMD_CREATE:
drhb376b3d2018-01-10 13:11:51 +00005127 rc = arCreateOrUpdateCommand(&cmd, 0);
dan88be0202017-12-09 17:58:02 +00005128 break;
danfd0245d2017-12-07 15:44:29 +00005129
dan88be0202017-12-09 17:58:02 +00005130 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00005131 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005132 break;
5133
5134 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00005135 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005136 break;
5137
dan0d0547f2017-12-14 15:40:42 +00005138 case AR_CMD_HELP:
5139 arUsage(pState->out);
5140 break;
5141
dan88be0202017-12-09 17:58:02 +00005142 default:
5143 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb376b3d2018-01-10 13:11:51 +00005144 rc = arCreateOrUpdateCommand(&cmd, 1);
dan88be0202017-12-09 17:58:02 +00005145 break;
danfd0245d2017-12-07 15:44:29 +00005146 }
5147 }
drha5676c42018-01-10 15:17:34 +00005148end_ar_command:
5149 if( cmd.db!=pState->db ){
5150 sqlite3_close(cmd.db);
5151 }
5152 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00005153
dan88be0202017-12-09 17:58:02 +00005154 return rc;
danfd0245d2017-12-07 15:44:29 +00005155}
drhe37c0e12018-01-06 19:19:50 +00005156/* End of the ".archive" or ".ar" command logic
5157**********************************************************************************/
5158#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00005159
drh2ce15c32017-07-11 13:34:40 +00005160
5161/*
5162** If an input line begins with "." then invoke this routine to
5163** process that line.
5164**
5165** Return 1 on error, 2 to exit, and 0 otherwise.
5166*/
5167static int do_meta_command(char *zLine, ShellState *p){
5168 int h = 1;
5169 int nArg = 0;
5170 int n, c;
5171 int rc = 0;
5172 char *azArg[50];
5173
dan6b046be2018-01-09 15:25:55 +00005174#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00005175 if( p->expert.pExpert ){
5176 expertFinish(p, 1, 0);
5177 }
dan6b046be2018-01-09 15:25:55 +00005178#endif
dan43efc182017-12-19 17:42:13 +00005179
drh2ce15c32017-07-11 13:34:40 +00005180 /* Parse the input line into tokens.
5181 */
5182 while( zLine[h] && nArg<ArraySize(azArg) ){
5183 while( IsSpace(zLine[h]) ){ h++; }
5184 if( zLine[h]==0 ) break;
5185 if( zLine[h]=='\'' || zLine[h]=='"' ){
5186 int delim = zLine[h++];
5187 azArg[nArg++] = &zLine[h];
5188 while( zLine[h] && zLine[h]!=delim ){
5189 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5190 h++;
5191 }
5192 if( zLine[h]==delim ){
5193 zLine[h++] = 0;
5194 }
5195 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5196 }else{
5197 azArg[nArg++] = &zLine[h];
5198 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5199 if( zLine[h] ) zLine[h++] = 0;
5200 resolve_backslashes(azArg[nArg-1]);
5201 }
5202 }
5203
5204 /* Process the input line.
5205 */
5206 if( nArg==0 ) return 0; /* no tokens, no error */
5207 n = strlen30(azArg[0]);
5208 c = azArg[0][0];
5209
5210#ifndef SQLITE_OMIT_AUTHORIZATION
5211 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5212 if( nArg!=2 ){
5213 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5214 rc = 1;
5215 goto meta_command_exit;
5216 }
5217 open_db(p, 0);
5218 if( booleanValue(azArg[1]) ){
5219 sqlite3_set_authorizer(p->db, shellAuth, p);
5220 }else{
5221 sqlite3_set_authorizer(p->db, 0, 0);
5222 }
5223 }else
5224#endif
5225
drhe37c0e12018-01-06 19:19:50 +00005226#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5227 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00005228 open_db(p, 0);
5229 rc = arDotCommand(p, azArg, nArg);
5230 }else
5231#endif
5232
drh2ce15c32017-07-11 13:34:40 +00005233 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5234 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5235 ){
5236 const char *zDestFile = 0;
5237 const char *zDb = 0;
5238 sqlite3 *pDest;
5239 sqlite3_backup *pBackup;
5240 int j;
5241 for(j=1; j<nArg; j++){
5242 const char *z = azArg[j];
5243 if( z[0]=='-' ){
5244 while( z[0]=='-' ) z++;
5245 /* No options to process at this time */
5246 {
5247 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
5248 return 1;
5249 }
5250 }else if( zDestFile==0 ){
5251 zDestFile = azArg[j];
5252 }else if( zDb==0 ){
5253 zDb = zDestFile;
5254 zDestFile = azArg[j];
5255 }else{
5256 raw_printf(stderr, "too many arguments to .backup\n");
5257 return 1;
5258 }
5259 }
5260 if( zDestFile==0 ){
5261 raw_printf(stderr, "missing FILENAME argument on .backup\n");
5262 return 1;
5263 }
5264 if( zDb==0 ) zDb = "main";
5265 rc = sqlite3_open(zDestFile, &pDest);
5266 if( rc!=SQLITE_OK ){
5267 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
5268 sqlite3_close(pDest);
5269 return 1;
5270 }
5271 open_db(p, 0);
5272 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5273 if( pBackup==0 ){
5274 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5275 sqlite3_close(pDest);
5276 return 1;
5277 }
5278 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5279 sqlite3_backup_finish(pBackup);
5280 if( rc==SQLITE_DONE ){
5281 rc = 0;
5282 }else{
5283 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5284 rc = 1;
5285 }
5286 sqlite3_close(pDest);
5287 }else
5288
5289 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5290 if( nArg==2 ){
5291 bail_on_error = booleanValue(azArg[1]);
5292 }else{
5293 raw_printf(stderr, "Usage: .bail on|off\n");
5294 rc = 1;
5295 }
5296 }else
5297
5298 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5299 if( nArg==2 ){
5300 if( booleanValue(azArg[1]) ){
5301 setBinaryMode(p->out, 1);
5302 }else{
5303 setTextMode(p->out, 1);
5304 }
5305 }else{
5306 raw_printf(stderr, "Usage: .binary on|off\n");
5307 rc = 1;
5308 }
5309 }else
5310
5311 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5312 if( nArg==2 ){
5313#if defined(_WIN32) || defined(WIN32)
5314 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5315 rc = !SetCurrentDirectoryW(z);
5316 sqlite3_free(z);
5317#else
5318 rc = chdir(azArg[1]);
5319#endif
5320 if( rc ){
5321 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5322 rc = 1;
5323 }
5324 }else{
5325 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5326 rc = 1;
5327 }
5328 }else
5329
5330 /* The undocumented ".breakpoint" command causes a call to the no-op
5331 ** routine named test_breakpoint().
5332 */
5333 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5334 test_breakpoint();
5335 }else
5336
5337 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5338 if( nArg==2 ){
5339 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
5340 }else{
5341 raw_printf(stderr, "Usage: .changes on|off\n");
5342 rc = 1;
5343 }
5344 }else
5345
5346 /* Cancel output redirection, if it is currently set (by .testcase)
5347 ** Then read the content of the testcase-out.txt file and compare against
5348 ** azArg[1]. If there are differences, report an error and exit.
5349 */
5350 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5351 char *zRes = 0;
5352 output_reset(p);
5353 if( nArg!=2 ){
5354 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
5355 rc = 2;
5356 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
5357 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5358 rc = 2;
5359 }else if( testcase_glob(azArg[1],zRes)==0 ){
5360 utf8_printf(stderr,
5361 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5362 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00005363 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00005364 }else{
5365 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
5366 p->nCheck++;
5367 }
5368 sqlite3_free(zRes);
5369 }else
5370
5371 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5372 if( nArg==2 ){
5373 tryToClone(p, azArg[1]);
5374 }else{
5375 raw_printf(stderr, "Usage: .clone FILENAME\n");
5376 rc = 1;
5377 }
5378 }else
5379
5380 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
5381 ShellState data;
5382 char *zErrMsg = 0;
5383 open_db(p, 0);
5384 memcpy(&data, p, sizeof(data));
5385 data.showHeader = 0;
5386 data.cMode = data.mode = MODE_List;
5387 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
5388 data.cnt = 0;
5389 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5390 callback, &data, &zErrMsg);
5391 if( zErrMsg ){
5392 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5393 sqlite3_free(zErrMsg);
5394 rc = 1;
5395 }
5396 }else
5397
5398 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
5399 rc = shell_dbinfo_command(p, nArg, azArg);
5400 }else
5401
5402 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
5403 const char *zLike = 0;
5404 int i;
5405 int savedShowHeader = p->showHeader;
5406 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
5407 for(i=1; i<nArg; i++){
5408 if( azArg[i][0]=='-' ){
5409 const char *z = azArg[i]+1;
5410 if( z[0]=='-' ) z++;
5411 if( strcmp(z,"preserve-rowids")==0 ){
5412#ifdef SQLITE_OMIT_VIRTUALTABLE
5413 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5414 " with SQLITE_OMIT_VIRTUALTABLE\n");
5415 rc = 1;
5416 goto meta_command_exit;
5417#else
5418 ShellSetFlag(p, SHFLG_PreserveRowid);
5419#endif
5420 }else
5421 if( strcmp(z,"newlines")==0 ){
5422 ShellSetFlag(p, SHFLG_Newlines);
5423 }else
5424 {
5425 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
5426 rc = 1;
5427 goto meta_command_exit;
5428 }
5429 }else if( zLike ){
5430 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
5431 "?--newlines? ?LIKE-PATTERN?\n");
5432 rc = 1;
5433 goto meta_command_exit;
5434 }else{
5435 zLike = azArg[i];
5436 }
5437 }
5438 open_db(p, 0);
5439 /* When playing back a "dump", the content might appear in an order
5440 ** which causes immediate foreign key constraints to be violated.
5441 ** So disable foreign-key constraint enforcement to prevent problems. */
5442 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
5443 raw_printf(p->out, "BEGIN TRANSACTION;\n");
5444 p->writableSchema = 0;
5445 p->showHeader = 0;
5446 /* Set writable_schema=ON since doing so forces SQLite to initialize
5447 ** as much of the schema as it can even if the sqlite_master table is
5448 ** corrupt. */
5449 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5450 p->nErr = 0;
5451 if( zLike==0 ){
5452 run_schema_dump_query(p,
5453 "SELECT name, type, sql FROM sqlite_master "
5454 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5455 );
5456 run_schema_dump_query(p,
5457 "SELECT name, type, sql FROM sqlite_master "
5458 "WHERE name=='sqlite_sequence'"
5459 );
5460 run_table_dump_query(p,
5461 "SELECT sql FROM sqlite_master "
5462 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5463 );
5464 }else{
5465 char *zSql;
5466 zSql = sqlite3_mprintf(
5467 "SELECT name, type, sql FROM sqlite_master "
5468 "WHERE tbl_name LIKE %Q AND type=='table'"
5469 " AND sql NOT NULL", zLike);
5470 run_schema_dump_query(p,zSql);
5471 sqlite3_free(zSql);
5472 zSql = sqlite3_mprintf(
5473 "SELECT sql FROM sqlite_master "
5474 "WHERE sql NOT NULL"
5475 " AND type IN ('index','trigger','view')"
5476 " AND tbl_name LIKE %Q", zLike);
5477 run_table_dump_query(p, zSql, 0);
5478 sqlite3_free(zSql);
5479 }
5480 if( p->writableSchema ){
5481 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
5482 p->writableSchema = 0;
5483 }
5484 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5485 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
5486 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5487 p->showHeader = savedShowHeader;
5488 }else
5489
5490 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5491 if( nArg==2 ){
5492 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
5493 }else{
5494 raw_printf(stderr, "Usage: .echo on|off\n");
5495 rc = 1;
5496 }
5497 }else
5498
5499 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5500 if( nArg==2 ){
5501 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00005502 p->autoEQP = AUTOEQP_full;
5503 }else if( strcmp(azArg[1],"trigger")==0 ){
5504 p->autoEQP = AUTOEQP_trigger;
drh2ce15c32017-07-11 13:34:40 +00005505 }else{
5506 p->autoEQP = booleanValue(azArg[1]);
5507 }
5508 }else{
drhada70452017-12-21 21:02:27 +00005509 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00005510 rc = 1;
5511 }
5512 }else
5513
5514 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
5515 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
5516 rc = 2;
5517 }else
5518
5519 /* The ".explain" command is automatic now. It is largely pointless. It
5520 ** retained purely for backwards compatibility */
5521 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
5522 int val = 1;
5523 if( nArg>=2 ){
5524 if( strcmp(azArg[1],"auto")==0 ){
5525 val = 99;
5526 }else{
5527 val = booleanValue(azArg[1]);
5528 }
5529 }
5530 if( val==1 && p->mode!=MODE_Explain ){
5531 p->normalMode = p->mode;
5532 p->mode = MODE_Explain;
5533 p->autoExplain = 0;
5534 }else if( val==0 ){
5535 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5536 p->autoExplain = 0;
5537 }else if( val==99 ){
5538 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5539 p->autoExplain = 1;
5540 }
5541 }else
5542
dan6b046be2018-01-09 15:25:55 +00005543#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00005544 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
5545 open_db(p, 0);
5546 expertDotCommand(p, azArg, nArg);
5547 }else
dan6b046be2018-01-09 15:25:55 +00005548#endif
dan43efc182017-12-19 17:42:13 +00005549
drh2ce15c32017-07-11 13:34:40 +00005550 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
5551 ShellState data;
5552 char *zErrMsg = 0;
5553 int doStats = 0;
5554 memcpy(&data, p, sizeof(data));
5555 data.showHeader = 0;
5556 data.cMode = data.mode = MODE_Semi;
5557 if( nArg==2 && optionMatch(azArg[1], "indent") ){
5558 data.cMode = data.mode = MODE_Pretty;
5559 nArg = 1;
5560 }
5561 if( nArg!=1 ){
5562 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
5563 rc = 1;
5564 goto meta_command_exit;
5565 }
5566 open_db(p, 0);
5567 rc = sqlite3_exec(p->db,
5568 "SELECT sql FROM"
5569 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5570 " FROM sqlite_master UNION ALL"
5571 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5572 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
5573 "ORDER BY rowid",
5574 callback, &data, &zErrMsg
5575 );
5576 if( rc==SQLITE_OK ){
5577 sqlite3_stmt *pStmt;
5578 rc = sqlite3_prepare_v2(p->db,
5579 "SELECT rowid FROM sqlite_master"
5580 " WHERE name GLOB 'sqlite_stat[134]'",
5581 -1, &pStmt, 0);
5582 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5583 sqlite3_finalize(pStmt);
5584 }
5585 if( doStats==0 ){
5586 raw_printf(p->out, "/* No STAT tables available */\n");
5587 }else{
5588 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5589 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5590 callback, &data, &zErrMsg);
5591 data.cMode = data.mode = MODE_Insert;
5592 data.zDestTable = "sqlite_stat1";
5593 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5594 shell_callback, &data,&zErrMsg);
5595 data.zDestTable = "sqlite_stat3";
5596 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5597 shell_callback, &data,&zErrMsg);
5598 data.zDestTable = "sqlite_stat4";
5599 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5600 shell_callback, &data, &zErrMsg);
5601 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5602 }
5603 }else
5604
5605 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5606 if( nArg==2 ){
5607 p->showHeader = booleanValue(azArg[1]);
5608 }else{
5609 raw_printf(stderr, "Usage: .headers on|off\n");
5610 rc = 1;
5611 }
5612 }else
5613
5614 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
5615 utf8_printf(p->out, "%s", zHelp);
5616 }else
5617
5618 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
5619 char *zTable; /* Insert data into this table */
5620 char *zFile; /* Name of file to extra content from */
5621 sqlite3_stmt *pStmt = NULL; /* A statement */
5622 int nCol; /* Number of columns in the table */
5623 int nByte; /* Number of bytes in an SQL string */
5624 int i, j; /* Loop counters */
5625 int needCommit; /* True to COMMIT or ROLLBACK at end */
5626 int nSep; /* Number of bytes in p->colSeparator[] */
5627 char *zSql; /* An SQL statement */
5628 ImportCtx sCtx; /* Reader context */
5629 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5630 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
5631
5632 if( nArg!=3 ){
5633 raw_printf(stderr, "Usage: .import FILE TABLE\n");
5634 goto meta_command_exit;
5635 }
5636 zFile = azArg[1];
5637 zTable = azArg[2];
5638 seenInterrupt = 0;
5639 memset(&sCtx, 0, sizeof(sCtx));
5640 open_db(p, 0);
5641 nSep = strlen30(p->colSeparator);
5642 if( nSep==0 ){
5643 raw_printf(stderr,
5644 "Error: non-null column separator required for import\n");
5645 return 1;
5646 }
5647 if( nSep>1 ){
5648 raw_printf(stderr, "Error: multi-character column separators not allowed"
5649 " for import\n");
5650 return 1;
5651 }
5652 nSep = strlen30(p->rowSeparator);
5653 if( nSep==0 ){
5654 raw_printf(stderr, "Error: non-null row separator required for import\n");
5655 return 1;
5656 }
5657 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5658 /* When importing CSV (only), if the row separator is set to the
5659 ** default output row separator, change it to the default input
5660 ** row separator. This avoids having to maintain different input
5661 ** and output row separators. */
5662 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5663 nSep = strlen30(p->rowSeparator);
5664 }
5665 if( nSep>1 ){
5666 raw_printf(stderr, "Error: multi-character row separators not allowed"
5667 " for import\n");
5668 return 1;
5669 }
5670 sCtx.zFile = zFile;
5671 sCtx.nLine = 1;
5672 if( sCtx.zFile[0]=='|' ){
5673#ifdef SQLITE_OMIT_POPEN
5674 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
5675 return 1;
5676#else
5677 sCtx.in = popen(sCtx.zFile+1, "r");
5678 sCtx.zFile = "<pipe>";
5679 xCloser = pclose;
5680#endif
5681 }else{
5682 sCtx.in = fopen(sCtx.zFile, "rb");
5683 xCloser = fclose;
5684 }
5685 if( p->mode==MODE_Ascii ){
5686 xRead = ascii_read_one_field;
5687 }else{
5688 xRead = csv_read_one_field;
5689 }
5690 if( sCtx.in==0 ){
5691 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5692 return 1;
5693 }
5694 sCtx.cColSep = p->colSeparator[0];
5695 sCtx.cRowSep = p->rowSeparator[0];
5696 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
5697 if( zSql==0 ){
5698 raw_printf(stderr, "Error: out of memory\n");
5699 xCloser(sCtx.in);
5700 return 1;
5701 }
5702 nByte = strlen30(zSql);
5703 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5704 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
5705 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
5706 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5707 char cSep = '(';
5708 while( xRead(&sCtx) ){
5709 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
5710 cSep = ',';
5711 if( sCtx.cTerm!=sCtx.cColSep ) break;
5712 }
5713 if( cSep=='(' ){
5714 sqlite3_free(zCreate);
5715 sqlite3_free(sCtx.z);
5716 xCloser(sCtx.in);
5717 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
5718 return 1;
5719 }
5720 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5721 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5722 sqlite3_free(zCreate);
5723 if( rc ){
5724 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
5725 sqlite3_errmsg(p->db));
5726 sqlite3_free(sCtx.z);
5727 xCloser(sCtx.in);
5728 return 1;
5729 }
5730 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5731 }
5732 sqlite3_free(zSql);
5733 if( rc ){
5734 if (pStmt) sqlite3_finalize(pStmt);
5735 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
5736 xCloser(sCtx.in);
5737 return 1;
5738 }
5739 nCol = sqlite3_column_count(pStmt);
5740 sqlite3_finalize(pStmt);
5741 pStmt = 0;
5742 if( nCol==0 ) return 0; /* no columns, no error */
5743 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
5744 if( zSql==0 ){
5745 raw_printf(stderr, "Error: out of memory\n");
5746 xCloser(sCtx.in);
5747 return 1;
5748 }
5749 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
5750 j = strlen30(zSql);
5751 for(i=1; i<nCol; i++){
5752 zSql[j++] = ',';
5753 zSql[j++] = '?';
5754 }
5755 zSql[j++] = ')';
5756 zSql[j] = 0;
5757 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5758 sqlite3_free(zSql);
5759 if( rc ){
5760 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5761 if (pStmt) sqlite3_finalize(pStmt);
5762 xCloser(sCtx.in);
5763 return 1;
5764 }
5765 needCommit = sqlite3_get_autocommit(p->db);
5766 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
5767 do{
5768 int startLine = sCtx.nLine;
5769 for(i=0; i<nCol; i++){
5770 char *z = xRead(&sCtx);
5771 /*
5772 ** Did we reach end-of-file before finding any columns?
5773 ** If so, stop instead of NULL filling the remaining columns.
5774 */
5775 if( z==0 && i==0 ) break;
5776 /*
5777 ** Did we reach end-of-file OR end-of-line before finding any
5778 ** columns in ASCII mode? If so, stop instead of NULL filling
5779 ** the remaining columns.
5780 */
5781 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
5782 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
5783 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
5784 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5785 "filling the rest with NULL\n",
5786 sCtx.zFile, startLine, nCol, i+1);
5787 i += 2;
5788 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
5789 }
5790 }
5791 if( sCtx.cTerm==sCtx.cColSep ){
5792 do{
5793 xRead(&sCtx);
5794 i++;
5795 }while( sCtx.cTerm==sCtx.cColSep );
5796 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5797 "extras ignored\n",
5798 sCtx.zFile, startLine, nCol, i);
5799 }
5800 if( i>=nCol ){
5801 sqlite3_step(pStmt);
5802 rc = sqlite3_reset(pStmt);
5803 if( rc!=SQLITE_OK ){
5804 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5805 startLine, sqlite3_errmsg(p->db));
5806 }
5807 }
5808 }while( sCtx.cTerm!=EOF );
5809
5810 xCloser(sCtx.in);
5811 sqlite3_free(sCtx.z);
5812 sqlite3_finalize(pStmt);
5813 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
5814 }else
5815
5816#ifndef SQLITE_UNTESTABLE
5817 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5818 char *zSql;
5819 char *zCollist = 0;
5820 sqlite3_stmt *pStmt;
5821 int tnum = 0;
5822 int i;
5823 if( nArg!=3 ){
5824 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5825 rc = 1;
5826 goto meta_command_exit;
5827 }
5828 open_db(p, 0);
5829 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5830 " WHERE name='%q' AND type='index'", azArg[1]);
5831 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5832 sqlite3_free(zSql);
5833 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5834 tnum = sqlite3_column_int(pStmt, 0);
5835 }
5836 sqlite3_finalize(pStmt);
5837 if( tnum==0 ){
5838 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5839 rc = 1;
5840 goto meta_command_exit;
5841 }
5842 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5843 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5844 sqlite3_free(zSql);
5845 i = 0;
5846 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5847 char zLabel[20];
5848 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
5849 i++;
5850 if( zCol==0 ){
5851 if( sqlite3_column_int(pStmt,1)==-1 ){
5852 zCol = "_ROWID_";
5853 }else{
5854 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5855 zCol = zLabel;
5856 }
5857 }
5858 if( zCollist==0 ){
5859 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5860 }else{
5861 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5862 }
5863 }
5864 sqlite3_finalize(pStmt);
5865 zSql = sqlite3_mprintf(
5866 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5867 azArg[2], zCollist, zCollist);
5868 sqlite3_free(zCollist);
5869 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5870 if( rc==SQLITE_OK ){
5871 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5872 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5873 if( rc ){
5874 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5875 }else{
5876 utf8_printf(stdout, "%s;\n", zSql);
5877 raw_printf(stdout,
5878 "WARNING: writing to an imposter table will corrupt the index!\n"
5879 );
5880 }
5881 }else{
5882 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
5883 rc = 1;
5884 }
5885 sqlite3_free(zSql);
5886 }else
5887#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5888
5889#ifdef SQLITE_ENABLE_IOTRACE
5890 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
5891 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
5892 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5893 iotrace = 0;
5894 if( nArg<2 ){
5895 sqlite3IoTrace = 0;
5896 }else if( strcmp(azArg[1], "-")==0 ){
5897 sqlite3IoTrace = iotracePrintf;
5898 iotrace = stdout;
5899 }else{
5900 iotrace = fopen(azArg[1], "w");
5901 if( iotrace==0 ){
5902 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
5903 sqlite3IoTrace = 0;
5904 rc = 1;
5905 }else{
5906 sqlite3IoTrace = iotracePrintf;
5907 }
5908 }
5909 }else
5910#endif
5911
5912 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5913 static const struct {
5914 const char *zLimitName; /* Name of a limit */
5915 int limitCode; /* Integer code for that limit */
5916 } aLimit[] = {
5917 { "length", SQLITE_LIMIT_LENGTH },
5918 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5919 { "column", SQLITE_LIMIT_COLUMN },
5920 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5921 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5922 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5923 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5924 { "attached", SQLITE_LIMIT_ATTACHED },
5925 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5926 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5927 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5928 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5929 };
5930 int i, n2;
5931 open_db(p, 0);
5932 if( nArg==1 ){
5933 for(i=0; i<ArraySize(aLimit); i++){
5934 printf("%20s %d\n", aLimit[i].zLimitName,
5935 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5936 }
5937 }else if( nArg>3 ){
5938 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
5939 rc = 1;
5940 goto meta_command_exit;
5941 }else{
5942 int iLimit = -1;
5943 n2 = strlen30(azArg[1]);
5944 for(i=0; i<ArraySize(aLimit); i++){
5945 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5946 if( iLimit<0 ){
5947 iLimit = i;
5948 }else{
5949 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
5950 rc = 1;
5951 goto meta_command_exit;
5952 }
5953 }
5954 }
5955 if( iLimit<0 ){
5956 utf8_printf(stderr, "unknown limit: \"%s\"\n"
5957 "enter \".limits\" with no arguments for a list.\n",
5958 azArg[1]);
5959 rc = 1;
5960 goto meta_command_exit;
5961 }
5962 if( nArg==3 ){
5963 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5964 (int)integerValue(azArg[2]));
5965 }
5966 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5967 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5968 }
5969 }else
5970
5971 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
5972 open_db(p, 0);
5973 lintDotCommand(p, azArg, nArg);
5974 }else
5975
5976#ifndef SQLITE_OMIT_LOAD_EXTENSION
5977 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
5978 const char *zFile, *zProc;
5979 char *zErrMsg = 0;
5980 if( nArg<2 ){
5981 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
5982 rc = 1;
5983 goto meta_command_exit;
5984 }
5985 zFile = azArg[1];
5986 zProc = nArg>=3 ? azArg[2] : 0;
5987 open_db(p, 0);
5988 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5989 if( rc!=SQLITE_OK ){
5990 utf8_printf(stderr, "Error: %s\n", zErrMsg);
5991 sqlite3_free(zErrMsg);
5992 rc = 1;
5993 }
5994 }else
5995#endif
5996
5997 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5998 if( nArg!=2 ){
5999 raw_printf(stderr, "Usage: .log FILENAME\n");
6000 rc = 1;
6001 }else{
6002 const char *zFile = azArg[1];
6003 output_file_close(p->pLog);
6004 p->pLog = output_file_open(zFile);
6005 }
6006 }else
6007
6008 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6009 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00006010 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00006011 int c2 = zMode[0];
6012 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
6013 p->mode = MODE_Line;
6014 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6015 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
6016 p->mode = MODE_Column;
6017 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6018 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
6019 p->mode = MODE_List;
6020 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6021 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6022 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
6023 p->mode = MODE_Html;
6024 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
6025 p->mode = MODE_Tcl;
6026 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
6027 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6028 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
6029 p->mode = MODE_Csv;
6030 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6031 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6032 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
6033 p->mode = MODE_List;
6034 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
6035 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
6036 p->mode = MODE_Insert;
6037 set_table_name(p, nArg>=3 ? azArg[2] : "table");
6038 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6039 p->mode = MODE_Quote;
6040 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6041 p->mode = MODE_Ascii;
6042 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6043 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
6044 }else if( nArg==1 ){
6045 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6046 }else{
6047 raw_printf(stderr, "Error: mode should be one of: "
6048 "ascii column csv html insert line list quote tabs tcl\n");
6049 rc = 1;
6050 }
6051 p->cMode = p->mode;
6052 }else
6053
6054 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6055 if( nArg==2 ){
6056 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6057 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
6058 }else{
6059 raw_printf(stderr, "Usage: .nullvalue STRING\n");
6060 rc = 1;
6061 }
6062 }else
6063
6064 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
6065 char *zNewFilename; /* Name of the database file to open */
6066 int iName = 1; /* Index in azArg[] of the filename */
6067 int newFlag = 0; /* True to delete file before opening */
6068 /* Close the existing database */
6069 session_close_all(p);
6070 sqlite3_close(p->db);
6071 p->db = 0;
6072 p->zDbFilename = 0;
6073 sqlite3_free(p->zFreeOnClose);
6074 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00006075 p->openMode = SHELL_OPEN_UNSPEC;
drh2ce15c32017-07-11 13:34:40 +00006076 /* Check for command-line arguments */
6077 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6078 const char *z = azArg[iName];
6079 if( optionMatch(z,"new") ){
6080 newFlag = 1;
drh1fa6d9f2018-01-06 21:46:01 +00006081#ifdef SQLITE_HAVE_ZIP
6082 }else if( optionMatch(z, "zip") ){
6083 p->openMode = SHELL_OPEN_ZIPFILE;
6084#endif
6085 }else if( optionMatch(z, "append") ){
6086 p->openMode = SHELL_OPEN_APPENDVFS;
drh2ce15c32017-07-11 13:34:40 +00006087 }else if( z[0]=='-' ){
6088 utf8_printf(stderr, "unknown option: %s\n", z);
6089 rc = 1;
6090 goto meta_command_exit;
6091 }
6092 }
6093 /* If a filename is specified, try to open it first */
6094 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
6095 if( zNewFilename ){
6096 if( newFlag ) shellDeleteFile(zNewFilename);
6097 p->zDbFilename = zNewFilename;
6098 open_db(p, 1);
6099 if( p->db==0 ){
6100 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6101 sqlite3_free(zNewFilename);
6102 }else{
6103 p->zFreeOnClose = zNewFilename;
6104 }
6105 }
6106 if( p->db==0 ){
6107 /* As a fall-back open a TEMP database */
6108 p->zDbFilename = 0;
6109 open_db(p, 0);
6110 }
6111 }else
6112
6113 if( c=='o'
6114 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
6115 ){
6116 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
6117 if( nArg>2 ){
6118 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
6119 rc = 1;
6120 goto meta_command_exit;
6121 }
6122 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6123 if( nArg<2 ){
6124 raw_printf(stderr, "Usage: .once FILE\n");
6125 rc = 1;
6126 goto meta_command_exit;
6127 }
6128 p->outCount = 2;
6129 }else{
6130 p->outCount = 0;
6131 }
6132 output_reset(p);
6133 if( zFile[0]=='|' ){
6134#ifdef SQLITE_OMIT_POPEN
6135 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6136 rc = 1;
6137 p->out = stdout;
6138#else
6139 p->out = popen(zFile + 1, "w");
6140 if( p->out==0 ){
6141 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
6142 p->out = stdout;
6143 rc = 1;
6144 }else{
6145 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6146 }
6147#endif
6148 }else{
6149 p->out = output_file_open(zFile);
6150 if( p->out==0 ){
6151 if( strcmp(zFile,"off")!=0 ){
6152 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
6153 }
6154 p->out = stdout;
6155 rc = 1;
6156 } else {
6157 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6158 }
6159 }
6160 }else
6161
6162 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6163 int i;
6164 for(i=1; i<nArg; i++){
6165 if( i>1 ) raw_printf(p->out, " ");
6166 utf8_printf(p->out, "%s", azArg[i]);
6167 }
6168 raw_printf(p->out, "\n");
6169 }else
6170
6171 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
6172 if( nArg >= 2) {
6173 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6174 }
6175 if( nArg >= 3) {
6176 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6177 }
6178 }else
6179
6180 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
6181 rc = 2;
6182 }else
6183
6184 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6185 FILE *alt;
6186 if( nArg!=2 ){
6187 raw_printf(stderr, "Usage: .read FILE\n");
6188 rc = 1;
6189 goto meta_command_exit;
6190 }
6191 alt = fopen(azArg[1], "rb");
6192 if( alt==0 ){
6193 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6194 rc = 1;
6195 }else{
6196 rc = process_input(p, alt);
6197 fclose(alt);
6198 }
6199 }else
6200
6201 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
6202 const char *zSrcFile;
6203 const char *zDb;
6204 sqlite3 *pSrc;
6205 sqlite3_backup *pBackup;
6206 int nTimeout = 0;
6207
6208 if( nArg==2 ){
6209 zSrcFile = azArg[1];
6210 zDb = "main";
6211 }else if( nArg==3 ){
6212 zSrcFile = azArg[2];
6213 zDb = azArg[1];
6214 }else{
6215 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
6216 rc = 1;
6217 goto meta_command_exit;
6218 }
6219 rc = sqlite3_open(zSrcFile, &pSrc);
6220 if( rc!=SQLITE_OK ){
6221 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
6222 sqlite3_close(pSrc);
6223 return 1;
6224 }
6225 open_db(p, 0);
6226 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6227 if( pBackup==0 ){
6228 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6229 sqlite3_close(pSrc);
6230 return 1;
6231 }
6232 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6233 || rc==SQLITE_BUSY ){
6234 if( rc==SQLITE_BUSY ){
6235 if( nTimeout++ >= 3 ) break;
6236 sqlite3_sleep(100);
6237 }
6238 }
6239 sqlite3_backup_finish(pBackup);
6240 if( rc==SQLITE_DONE ){
6241 rc = 0;
6242 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
6243 raw_printf(stderr, "Error: source database is busy\n");
6244 rc = 1;
6245 }else{
6246 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6247 rc = 1;
6248 }
6249 sqlite3_close(pSrc);
6250 }else
6251
6252
6253 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6254 if( nArg==2 ){
6255 p->scanstatsOn = booleanValue(azArg[1]);
6256#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6257 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
6258#endif
6259 }else{
6260 raw_printf(stderr, "Usage: .scanstats on|off\n");
6261 rc = 1;
6262 }
6263 }else
6264
6265 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
6266 ShellText sSelect;
6267 ShellState data;
6268 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00006269 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00006270 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00006271 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00006272 int bDebug = 0;
6273 int ii;
drh2ce15c32017-07-11 13:34:40 +00006274
6275 open_db(p, 0);
6276 memcpy(&data, p, sizeof(data));
6277 data.showHeader = 0;
6278 data.cMode = data.mode = MODE_Semi;
6279 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00006280 for(ii=1; ii<nArg; ii++){
6281 if( optionMatch(azArg[ii],"indent") ){
6282 data.cMode = data.mode = MODE_Pretty;
6283 }else if( optionMatch(azArg[ii],"debug") ){
6284 bDebug = 1;
6285 }else if( zName==0 ){
6286 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00006287 }else{
drhceba7922018-01-01 21:28:25 +00006288 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6289 rc = 1;
6290 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00006291 }
drh2ce15c32017-07-11 13:34:40 +00006292 }
drhceba7922018-01-01 21:28:25 +00006293 if( zName!=0 ){
drh667a2a22018-01-02 00:04:37 +00006294 int isMaster = sqlite3_strlike(zName, "sqlite_master", 0)==0;
6295 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master",0)==0 ){
drh2ce15c32017-07-11 13:34:40 +00006296 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00006297 new_argv[0] = sqlite3_mprintf(
6298 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00006299 " type text,\n"
6300 " name text,\n"
6301 " tbl_name text,\n"
6302 " rootpage integer,\n"
6303 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00006304 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00006305 new_argv[1] = 0;
6306 new_colv[0] = "sql";
6307 new_colv[1] = 0;
6308 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00006309 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00006310 }
drh2ce15c32017-07-11 13:34:40 +00006311 }
6312 if( zDiv ){
6313 sqlite3_stmt *pStmt = 0;
6314 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6315 -1, &pStmt, 0);
6316 if( rc ){
6317 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6318 sqlite3_finalize(pStmt);
6319 rc = 1;
6320 goto meta_command_exit;
6321 }
6322 appendText(&sSelect, "SELECT sql FROM", 0);
6323 iSchema = 0;
6324 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6325 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6326 char zScNum[30];
6327 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6328 appendText(&sSelect, zDiv, 0);
6329 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00006330 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
6331 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00006332 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00006333 }else{
drhceba7922018-01-01 21:28:25 +00006334 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00006335 }
drhceba7922018-01-01 21:28:25 +00006336 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6337 appendText(&sSelect, zScNum, 0);
6338 appendText(&sSelect, " AS snum, ", 0);
6339 appendText(&sSelect, zDb, '\'');
6340 appendText(&sSelect, " AS sname FROM ", 0);
6341 appendText(&sSelect, zDb, '"');
6342 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00006343 }
6344 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00006345#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00006346 if( zName ){
6347 appendText(&sSelect,
6348 " UNION ALL SELECT shell_module_schema(name),"
6349 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6350 }
drhcde7b772018-01-02 12:50:40 +00006351#endif
drh2ce15c32017-07-11 13:34:40 +00006352 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00006353 if( zName ){
6354 char *zQarg = sqlite3_mprintf("%Q", zName);
6355 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00006356 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6357 }else{
6358 appendText(&sSelect, "lower(tbl_name)", 0);
6359 }
drhceba7922018-01-01 21:28:25 +00006360 appendText(&sSelect, strchr(zName, '*') ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00006361 appendText(&sSelect, zQarg, 0);
6362 appendText(&sSelect, " AND ", 0);
6363 sqlite3_free(zQarg);
6364 }
6365 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6366 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00006367 if( bDebug ){
6368 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
6369 }else{
6370 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6371 }
drh2ce15c32017-07-11 13:34:40 +00006372 freeText(&sSelect);
6373 }
6374 if( zErrMsg ){
6375 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6376 sqlite3_free(zErrMsg);
6377 rc = 1;
6378 }else if( rc != SQLITE_OK ){
6379 raw_printf(stderr,"Error: querying schema information\n");
6380 rc = 1;
6381 }else{
6382 rc = 0;
6383 }
6384 }else
6385
6386#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6387 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
6388 sqlite3SelectTrace = (int)integerValue(azArg[1]);
6389 }else
6390#endif
6391
6392#if defined(SQLITE_ENABLE_SESSION)
6393 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
6394 OpenSession *pSession = &p->aSession[0];
6395 char **azCmd = &azArg[1];
6396 int iSes = 0;
6397 int nCmd = nArg - 1;
6398 int i;
6399 if( nArg<=1 ) goto session_syntax_error;
6400 open_db(p, 0);
6401 if( nArg>=3 ){
6402 for(iSes=0; iSes<p->nSession; iSes++){
6403 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
6404 }
6405 if( iSes<p->nSession ){
6406 pSession = &p->aSession[iSes];
6407 azCmd++;
6408 nCmd--;
6409 }else{
6410 pSession = &p->aSession[0];
6411 iSes = 0;
6412 }
6413 }
6414
6415 /* .session attach TABLE
6416 ** Invoke the sqlite3session_attach() interface to attach a particular
6417 ** table so that it is never filtered.
6418 */
6419 if( strcmp(azCmd[0],"attach")==0 ){
6420 if( nCmd!=2 ) goto session_syntax_error;
6421 if( pSession->p==0 ){
6422 session_not_open:
6423 raw_printf(stderr, "ERROR: No sessions are open\n");
6424 }else{
6425 rc = sqlite3session_attach(pSession->p, azCmd[1]);
6426 if( rc ){
6427 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
6428 rc = 0;
6429 }
6430 }
6431 }else
6432
6433 /* .session changeset FILE
6434 ** .session patchset FILE
6435 ** Write a changeset or patchset into a file. The file is overwritten.
6436 */
6437 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
6438 FILE *out = 0;
6439 if( nCmd!=2 ) goto session_syntax_error;
6440 if( pSession->p==0 ) goto session_not_open;
6441 out = fopen(azCmd[1], "wb");
6442 if( out==0 ){
6443 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
6444 }else{
6445 int szChng;
6446 void *pChng;
6447 if( azCmd[0][0]=='c' ){
6448 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
6449 }else{
6450 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
6451 }
6452 if( rc ){
6453 printf("Error: error code %d\n", rc);
6454 rc = 0;
6455 }
6456 if( pChng
6457 && fwrite(pChng, szChng, 1, out)!=1 ){
6458 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
6459 szChng);
6460 }
6461 sqlite3_free(pChng);
6462 fclose(out);
6463 }
6464 }else
6465
6466 /* .session close
6467 ** Close the identified session
6468 */
6469 if( strcmp(azCmd[0], "close")==0 ){
6470 if( nCmd!=1 ) goto session_syntax_error;
6471 if( p->nSession ){
6472 session_close(pSession);
6473 p->aSession[iSes] = p->aSession[--p->nSession];
6474 }
6475 }else
6476
6477 /* .session enable ?BOOLEAN?
6478 ** Query or set the enable flag
6479 */
6480 if( strcmp(azCmd[0], "enable")==0 ){
6481 int ii;
6482 if( nCmd>2 ) goto session_syntax_error;
6483 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6484 if( p->nSession ){
6485 ii = sqlite3session_enable(pSession->p, ii);
6486 utf8_printf(p->out, "session %s enable flag = %d\n",
6487 pSession->zName, ii);
6488 }
6489 }else
6490
6491 /* .session filter GLOB ....
6492 ** Set a list of GLOB patterns of table names to be excluded.
6493 */
6494 if( strcmp(azCmd[0], "filter")==0 ){
6495 int ii, nByte;
6496 if( nCmd<2 ) goto session_syntax_error;
6497 if( p->nSession ){
6498 for(ii=0; ii<pSession->nFilter; ii++){
6499 sqlite3_free(pSession->azFilter[ii]);
6500 }
6501 sqlite3_free(pSession->azFilter);
6502 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6503 pSession->azFilter = sqlite3_malloc( nByte );
6504 if( pSession->azFilter==0 ){
6505 raw_printf(stderr, "Error: out or memory\n");
6506 exit(1);
6507 }
6508 for(ii=1; ii<nCmd; ii++){
6509 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
6510 }
6511 pSession->nFilter = ii-1;
6512 }
6513 }else
6514
6515 /* .session indirect ?BOOLEAN?
6516 ** Query or set the indirect flag
6517 */
6518 if( strcmp(azCmd[0], "indirect")==0 ){
6519 int ii;
6520 if( nCmd>2 ) goto session_syntax_error;
6521 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6522 if( p->nSession ){
6523 ii = sqlite3session_indirect(pSession->p, ii);
6524 utf8_printf(p->out, "session %s indirect flag = %d\n",
6525 pSession->zName, ii);
6526 }
6527 }else
6528
6529 /* .session isempty
6530 ** Determine if the session is empty
6531 */
6532 if( strcmp(azCmd[0], "isempty")==0 ){
6533 int ii;
6534 if( nCmd!=1 ) goto session_syntax_error;
6535 if( p->nSession ){
6536 ii = sqlite3session_isempty(pSession->p);
6537 utf8_printf(p->out, "session %s isempty flag = %d\n",
6538 pSession->zName, ii);
6539 }
6540 }else
6541
6542 /* .session list
6543 ** List all currently open sessions
6544 */
6545 if( strcmp(azCmd[0],"list")==0 ){
6546 for(i=0; i<p->nSession; i++){
6547 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
6548 }
6549 }else
6550
6551 /* .session open DB NAME
6552 ** Open a new session called NAME on the attached database DB.
6553 ** DB is normally "main".
6554 */
6555 if( strcmp(azCmd[0],"open")==0 ){
6556 char *zName;
6557 if( nCmd!=3 ) goto session_syntax_error;
6558 zName = azCmd[2];
6559 if( zName[0]==0 ) goto session_syntax_error;
6560 for(i=0; i<p->nSession; i++){
6561 if( strcmp(p->aSession[i].zName,zName)==0 ){
6562 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
6563 goto meta_command_exit;
6564 }
6565 }
6566 if( p->nSession>=ArraySize(p->aSession) ){
6567 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
6568 goto meta_command_exit;
6569 }
6570 pSession = &p->aSession[p->nSession];
6571 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
6572 if( rc ){
6573 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
6574 rc = 0;
6575 goto meta_command_exit;
6576 }
6577 pSession->nFilter = 0;
6578 sqlite3session_table_filter(pSession->p, session_filter, pSession);
6579 p->nSession++;
6580 pSession->zName = sqlite3_mprintf("%s", zName);
6581 }else
6582 /* If no command name matches, show a syntax error */
6583 session_syntax_error:
6584 session_help(p);
6585 }else
6586#endif
6587
6588#ifdef SQLITE_DEBUG
6589 /* Undocumented commands for internal testing. Subject to change
6590 ** without notice. */
6591 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
6592 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
6593 int i, v;
6594 for(i=1; i<nArg; i++){
6595 v = booleanValue(azArg[i]);
6596 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
6597 }
6598 }
6599 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
6600 int i; sqlite3_int64 v;
6601 for(i=1; i<nArg; i++){
6602 char zBuf[200];
6603 v = integerValue(azArg[i]);
6604 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
6605 utf8_printf(p->out, "%s", zBuf);
6606 }
6607 }
6608 }else
6609#endif
6610
6611 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6612 int bIsInit = 0; /* True to initialize the SELFTEST table */
6613 int bVerbose = 0; /* Verbose output */
6614 int bSelftestExists; /* True if SELFTEST already exists */
6615 int i, k; /* Loop counters */
6616 int nTest = 0; /* Number of tests runs */
6617 int nErr = 0; /* Number of errors seen */
6618 ShellText str; /* Answer for a query */
6619 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
6620
6621 open_db(p,0);
6622 for(i=1; i<nArg; i++){
6623 const char *z = azArg[i];
6624 if( z[0]=='-' && z[1]=='-' ) z++;
6625 if( strcmp(z,"-init")==0 ){
6626 bIsInit = 1;
6627 }else
6628 if( strcmp(z,"-v")==0 ){
6629 bVerbose++;
6630 }else
6631 {
6632 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6633 azArg[i], azArg[0]);
6634 raw_printf(stderr, "Should be one of: --init -v\n");
6635 rc = 1;
6636 goto meta_command_exit;
6637 }
6638 }
6639 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6640 != SQLITE_OK ){
6641 bSelftestExists = 0;
6642 }else{
6643 bSelftestExists = 1;
6644 }
6645 if( bIsInit ){
6646 createSelftestTable(p);
6647 bSelftestExists = 1;
6648 }
6649 initText(&str);
6650 appendText(&str, "x", 0);
6651 for(k=bSelftestExists; k>=0; k--){
6652 if( k==1 ){
6653 rc = sqlite3_prepare_v2(p->db,
6654 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6655 -1, &pStmt, 0);
6656 }else{
6657 rc = sqlite3_prepare_v2(p->db,
6658 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6659 " (1,'run','PRAGMA integrity_check','ok')",
6660 -1, &pStmt, 0);
6661 }
6662 if( rc ){
6663 raw_printf(stderr, "Error querying the selftest table\n");
6664 rc = 1;
6665 sqlite3_finalize(pStmt);
6666 goto meta_command_exit;
6667 }
6668 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6669 int tno = sqlite3_column_int(pStmt, 0);
6670 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6671 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6672 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
6673
6674 k = 0;
6675 if( bVerbose>0 ){
6676 char *zQuote = sqlite3_mprintf("%q", zSql);
6677 printf("%d: %s %s\n", tno, zOp, zSql);
6678 sqlite3_free(zQuote);
6679 }
6680 if( strcmp(zOp,"memo")==0 ){
6681 utf8_printf(p->out, "%s\n", zSql);
6682 }else
6683 if( strcmp(zOp,"run")==0 ){
6684 char *zErrMsg = 0;
6685 str.n = 0;
6686 str.z[0] = 0;
6687 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6688 nTest++;
6689 if( bVerbose ){
6690 utf8_printf(p->out, "Result: %s\n", str.z);
6691 }
6692 if( rc || zErrMsg ){
6693 nErr++;
6694 rc = 1;
6695 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6696 sqlite3_free(zErrMsg);
6697 }else if( strcmp(zAns,str.z)!=0 ){
6698 nErr++;
6699 rc = 1;
6700 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6701 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6702 }
6703 }else
6704 {
6705 utf8_printf(stderr,
6706 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
6707 rc = 1;
6708 break;
6709 }
6710 } /* End loop over rows of content from SELFTEST */
6711 sqlite3_finalize(pStmt);
6712 } /* End loop over k */
6713 freeText(&str);
6714 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6715 }else
6716
6717 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
6718 if( nArg<2 || nArg>3 ){
6719 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
6720 rc = 1;
6721 }
6722 if( nArg>=2 ){
6723 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
6724 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
6725 }
6726 if( nArg>=3 ){
6727 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6728 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
6729 }
6730 }else
6731
6732 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6733 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6734 int i; /* Loop counter */
6735 int bSchema = 0; /* Also hash the schema */
6736 int bSeparate = 0; /* Hash each table separately */
6737 int iSize = 224; /* Hash algorithm to use */
6738 int bDebug = 0; /* Only show the query that would have run */
6739 sqlite3_stmt *pStmt; /* For querying tables names */
6740 char *zSql; /* SQL to be run */
6741 char *zSep; /* Separator */
6742 ShellText sSql; /* Complete SQL for the query to run the hash */
6743 ShellText sQuery; /* Set of queries used to read all content */
6744 open_db(p, 0);
6745 for(i=1; i<nArg; i++){
6746 const char *z = azArg[i];
6747 if( z[0]=='-' ){
6748 z++;
6749 if( z[0]=='-' ) z++;
6750 if( strcmp(z,"schema")==0 ){
6751 bSchema = 1;
6752 }else
6753 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6754 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
6755 ){
6756 iSize = atoi(&z[5]);
6757 }else
6758 if( strcmp(z,"debug")==0 ){
6759 bDebug = 1;
6760 }else
6761 {
6762 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6763 azArg[i], azArg[0]);
6764 raw_printf(stderr, "Should be one of: --schema"
6765 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6766 rc = 1;
6767 goto meta_command_exit;
6768 }
6769 }else if( zLike ){
6770 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6771 rc = 1;
6772 goto meta_command_exit;
6773 }else{
6774 zLike = z;
6775 bSeparate = 1;
6776 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
6777 }
6778 }
6779 if( bSchema ){
6780 zSql = "SELECT lower(name) FROM sqlite_master"
6781 " WHERE type='table' AND coalesce(rootpage,0)>1"
6782 " UNION ALL SELECT 'sqlite_master'"
6783 " ORDER BY 1 collate nocase";
6784 }else{
6785 zSql = "SELECT lower(name) FROM sqlite_master"
6786 " WHERE type='table' AND coalesce(rootpage,0)>1"
6787 " AND name NOT LIKE 'sqlite_%'"
6788 " ORDER BY 1 collate nocase";
6789 }
6790 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6791 initText(&sQuery);
6792 initText(&sSql);
6793 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6794 zSep = "VALUES(";
6795 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6796 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6797 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6798 if( strncmp(zTab, "sqlite_",7)!=0 ){
6799 appendText(&sQuery,"SELECT * FROM ", 0);
6800 appendText(&sQuery,zTab,'"');
6801 appendText(&sQuery," NOT INDEXED;", 0);
6802 }else if( strcmp(zTab, "sqlite_master")==0 ){
6803 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6804 " ORDER BY name;", 0);
6805 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6806 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6807 " ORDER BY name;", 0);
6808 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6809 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6810 " ORDER BY tbl,idx;", 0);
6811 }else if( strcmp(zTab, "sqlite_stat3")==0
6812 || strcmp(zTab, "sqlite_stat4")==0 ){
6813 appendText(&sQuery, "SELECT * FROM ", 0);
6814 appendText(&sQuery, zTab, 0);
6815 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6816 }
6817 appendText(&sSql, zSep, 0);
6818 appendText(&sSql, sQuery.z, '\'');
6819 sQuery.n = 0;
6820 appendText(&sSql, ",", 0);
6821 appendText(&sSql, zTab, '\'');
6822 zSep = "),(";
6823 }
6824 sqlite3_finalize(pStmt);
6825 if( bSeparate ){
6826 zSql = sqlite3_mprintf(
6827 "%s))"
6828 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6829 " FROM [sha3sum$query]",
6830 sSql.z, iSize);
6831 }else{
6832 zSql = sqlite3_mprintf(
6833 "%s))"
6834 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6835 " FROM [sha3sum$query]",
6836 sSql.z, iSize);
6837 }
6838 freeText(&sQuery);
6839 freeText(&sSql);
6840 if( bDebug ){
6841 utf8_printf(p->out, "%s\n", zSql);
6842 }else{
6843 shell_exec(p->db, zSql, shell_callback, p, 0);
6844 }
6845 sqlite3_free(zSql);
6846 }else
6847
6848 if( c=='s'
6849 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
6850 ){
6851 char *zCmd;
6852 int i, x;
6853 if( nArg<2 ){
6854 raw_printf(stderr, "Usage: .system COMMAND\n");
6855 rc = 1;
6856 goto meta_command_exit;
6857 }
6858 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
6859 for(i=2; i<nArg; i++){
6860 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6861 zCmd, azArg[i]);
6862 }
6863 x = system(zCmd);
6864 sqlite3_free(zCmd);
6865 if( x ) raw_printf(stderr, "System command returns %d\n", x);
6866 }else
6867
6868 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00006869 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00006870 int i;
6871 if( nArg!=1 ){
6872 raw_printf(stderr, "Usage: .show\n");
6873 rc = 1;
6874 goto meta_command_exit;
6875 }
6876 utf8_printf(p->out, "%12.12s: %s\n","echo",
6877 azBool[ShellHasFlag(p, SHFLG_Echo)]);
6878 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
6879 utf8_printf(p->out, "%12.12s: %s\n","explain",
6880 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
6881 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
6882 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6883 utf8_printf(p->out, "%12.12s: ", "nullvalue");
6884 output_c_string(p->out, p->nullValue);
6885 raw_printf(p->out, "\n");
6886 utf8_printf(p->out,"%12.12s: %s\n","output",
6887 strlen30(p->outfile) ? p->outfile : "stdout");
6888 utf8_printf(p->out,"%12.12s: ", "colseparator");
6889 output_c_string(p->out, p->colSeparator);
6890 raw_printf(p->out, "\n");
6891 utf8_printf(p->out,"%12.12s: ", "rowseparator");
6892 output_c_string(p->out, p->rowSeparator);
6893 raw_printf(p->out, "\n");
6894 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
6895 utf8_printf(p->out, "%12.12s: ", "width");
6896 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
6897 raw_printf(p->out, "%d ", p->colWidth[i]);
6898 }
6899 raw_printf(p->out, "\n");
6900 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6901 p->zDbFilename ? p->zDbFilename : "");
6902 }else
6903
6904 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6905 if( nArg==2 ){
6906 p->statsOn = booleanValue(azArg[1]);
6907 }else if( nArg==1 ){
6908 display_stats(p->db, p, 0);
6909 }else{
6910 raw_printf(stderr, "Usage: .stats ?on|off?\n");
6911 rc = 1;
6912 }
6913 }else
6914
6915 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6916 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6917 || strncmp(azArg[0], "indexes", n)==0) )
6918 ){
6919 sqlite3_stmt *pStmt;
6920 char **azResult;
6921 int nRow, nAlloc;
6922 int ii;
6923 ShellText s;
6924 initText(&s);
6925 open_db(p, 0);
6926 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
6927 if( rc ) return shellDatabaseError(p->db);
6928
6929 if( nArg>2 && c=='i' ){
6930 /* It is an historical accident that the .indexes command shows an error
6931 ** when called with the wrong number of arguments whereas the .tables
6932 ** command does not. */
6933 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6934 rc = 1;
6935 goto meta_command_exit;
6936 }
6937 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
6938 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
6939 if( zDbName==0 ) continue;
6940 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
6941 if( sqlite3_stricmp(zDbName, "main")==0 ){
6942 appendText(&s, "SELECT name FROM ", 0);
6943 }else{
6944 appendText(&s, "SELECT ", 0);
6945 appendText(&s, zDbName, '\'');
6946 appendText(&s, "||'.'||name FROM ", 0);
6947 }
6948 appendText(&s, zDbName, '"');
6949 appendText(&s, ".sqlite_master ", 0);
6950 if( c=='t' ){
6951 appendText(&s," WHERE type IN ('table','view')"
6952 " AND name NOT LIKE 'sqlite_%'"
6953 " AND name LIKE ?1", 0);
6954 }else{
6955 appendText(&s," WHERE type='index'"
6956 " AND tbl_name LIKE ?1", 0);
6957 }
6958 }
6959 rc = sqlite3_finalize(pStmt);
6960 appendText(&s, " ORDER BY 1", 0);
6961 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
6962 freeText(&s);
6963 if( rc ) return shellDatabaseError(p->db);
6964
6965 /* Run the SQL statement prepared by the above block. Store the results
6966 ** as an array of nul-terminated strings in azResult[]. */
6967 nRow = nAlloc = 0;
6968 azResult = 0;
6969 if( nArg>1 ){
6970 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
6971 }else{
6972 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6973 }
6974 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6975 if( nRow>=nAlloc ){
6976 char **azNew;
6977 int n2 = nAlloc*2 + 10;
6978 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
6979 if( azNew==0 ){
6980 rc = shellNomemError();
6981 break;
6982 }
6983 nAlloc = n2;
6984 azResult = azNew;
6985 }
6986 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
6987 if( 0==azResult[nRow] ){
6988 rc = shellNomemError();
6989 break;
6990 }
6991 nRow++;
6992 }
6993 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6994 rc = shellDatabaseError(p->db);
6995 }
6996
6997 /* Pretty-print the contents of array azResult[] to the output */
6998 if( rc==0 && nRow>0 ){
6999 int len, maxlen = 0;
7000 int i, j;
7001 int nPrintCol, nPrintRow;
7002 for(i=0; i<nRow; i++){
7003 len = strlen30(azResult[i]);
7004 if( len>maxlen ) maxlen = len;
7005 }
7006 nPrintCol = 80/(maxlen+2);
7007 if( nPrintCol<1 ) nPrintCol = 1;
7008 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
7009 for(i=0; i<nPrintRow; i++){
7010 for(j=i; j<nRow; j+=nPrintRow){
7011 char *zSp = j<nPrintRow ? "" : " ";
7012 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
7013 azResult[j] ? azResult[j]:"");
7014 }
7015 raw_printf(p->out, "\n");
7016 }
7017 }
7018
7019 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
7020 sqlite3_free(azResult);
7021 }else
7022
7023 /* Begin redirecting output to the file "testcase-out.txt" */
7024 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
7025 output_reset(p);
7026 p->out = output_file_open("testcase-out.txt");
7027 if( p->out==0 ){
7028 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
7029 }
7030 if( nArg>=2 ){
7031 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
7032 }else{
7033 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
7034 }
7035 }else
7036
7037#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00007038 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007039 static const struct {
7040 const char *zCtrlName; /* Name of a test-control option */
7041 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00007042 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00007043 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00007044 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
7045 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
7046 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7047 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7048 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
7049 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7050 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
7051#ifdef SQLITE_N_KEYWORD
7052 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD, "IDENTIFIER" },
7053#endif
7054 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
7055 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
7056 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00007057#ifdef YYCOVERAGE
7058 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
7059#endif
drhef302e82017-11-15 19:14:08 +00007060 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
7061 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
7062 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
7063 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
7064 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00007065 };
7066 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00007067 int iCtrl = -1;
7068 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7069 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00007070 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00007071 const char *zCmd = 0;
7072
drh2ce15c32017-07-11 13:34:40 +00007073 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00007074 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00007075
7076 /* The argument can optionally begin with "-" or "--" */
7077 if( zCmd[0]=='-' && zCmd[1] ){
7078 zCmd++;
7079 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7080 }
7081
7082 /* --help lists all test-controls */
7083 if( strcmp(zCmd,"help")==0 ){
7084 utf8_printf(p->out, "Available test-controls:\n");
7085 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00007086 utf8_printf(p->out, " .testctrl %s %s\n",
7087 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00007088 }
7089 rc = 1;
7090 goto meta_command_exit;
7091 }
drh2ce15c32017-07-11 13:34:40 +00007092
7093 /* convert testctrl text option to value. allow any unique prefix
7094 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00007095 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00007096 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00007097 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007098 if( testctrl<0 ){
7099 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00007100 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00007101 }else{
drh35f51a42017-11-15 17:07:22 +00007102 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
7103 "Use \".testctrl --help\" for help\n", zCmd);
7104 rc = 1;
7105 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00007106 }
7107 }
7108 }
drhef302e82017-11-15 19:14:08 +00007109 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00007110 utf8_printf(stderr,"Error: unknown test-control: %s\n"
7111 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00007112 }else{
7113 switch(testctrl){
7114
7115 /* sqlite3_test_control(int, db, int) */
7116 case SQLITE_TESTCTRL_OPTIMIZATIONS:
7117 case SQLITE_TESTCTRL_RESERVE:
7118 if( nArg==3 ){
7119 int opt = (int)strtol(azArg[2], 0, 0);
7120 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00007121 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007122 }
7123 break;
7124
7125 /* sqlite3_test_control(int) */
7126 case SQLITE_TESTCTRL_PRNG_SAVE:
7127 case SQLITE_TESTCTRL_PRNG_RESTORE:
7128 case SQLITE_TESTCTRL_PRNG_RESET:
7129 case SQLITE_TESTCTRL_BYTEORDER:
7130 if( nArg==2 ){
7131 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00007132 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00007133 }
7134 break;
7135
7136 /* sqlite3_test_control(int, uint) */
7137 case SQLITE_TESTCTRL_PENDING_BYTE:
7138 if( nArg==3 ){
7139 unsigned int opt = (unsigned int)integerValue(azArg[2]);
7140 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007141 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007142 }
7143 break;
7144
7145 /* sqlite3_test_control(int, int) */
7146 case SQLITE_TESTCTRL_ASSERT:
7147 case SQLITE_TESTCTRL_ALWAYS:
drhef302e82017-11-15 19:14:08 +00007148 if( nArg==3 ){
7149 int opt = booleanValue(azArg[2]);
7150 rc2 = sqlite3_test_control(testctrl, opt);
7151 isOk = 1;
7152 }
7153 break;
7154
7155 /* sqlite3_test_control(int, int) */
7156 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00007157 case SQLITE_TESTCTRL_NEVER_CORRUPT:
7158 if( nArg==3 ){
7159 int opt = booleanValue(azArg[2]);
7160 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007161 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007162 }
7163 break;
7164
7165 /* sqlite3_test_control(int, char *) */
7166#ifdef SQLITE_N_KEYWORD
7167 case SQLITE_TESTCTRL_ISKEYWORD:
7168 if( nArg==3 ){
7169 const char *opt = azArg[2];
7170 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007171 isOk = 1;
drh2ce15c32017-07-11 13:34:40 +00007172 }
7173 break;
7174#endif
7175
7176 case SQLITE_TESTCTRL_IMPOSTER:
7177 if( nArg==5 ){
7178 rc2 = sqlite3_test_control(testctrl, p->db,
7179 azArg[2],
7180 integerValue(azArg[3]),
7181 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00007182 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007183 }
7184 break;
drh0d9de992017-12-26 18:04:23 +00007185
7186#ifdef YYCOVERAGE
7187 case SQLITE_TESTCTRL_PARSER_COVERAGE:
7188 if( nArg==2 ){
7189 sqlite3_test_control(testctrl, p->out);
7190 isOk = 3;
7191 }
7192#endif
drh2ce15c32017-07-11 13:34:40 +00007193 }
7194 }
drhef302e82017-11-15 19:14:08 +00007195 if( isOk==0 && iCtrl>=0 ){
7196 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
7197 rc = 1;
7198 }else if( isOk==1 ){
7199 raw_printf(p->out, "%d\n", rc2);
7200 }else if( isOk==2 ){
7201 raw_printf(p->out, "0x%08x\n", rc2);
7202 }
drh2ce15c32017-07-11 13:34:40 +00007203 }else
7204#endif /* !defined(SQLITE_UNTESTABLE) */
7205
7206 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
7207 open_db(p, 0);
7208 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
7209 }else
7210
7211 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7212 if( nArg==2 ){
7213 enableTimer = booleanValue(azArg[1]);
7214 if( enableTimer && !HAS_TIMER ){
7215 raw_printf(stderr, "Error: timer not available on this system.\n");
7216 enableTimer = 0;
7217 }
7218 }else{
7219 raw_printf(stderr, "Usage: .timer on|off\n");
7220 rc = 1;
7221 }
7222 }else
7223
7224 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
7225 open_db(p, 0);
7226 if( nArg!=2 ){
7227 raw_printf(stderr, "Usage: .trace FILE|off\n");
7228 rc = 1;
7229 goto meta_command_exit;
7230 }
7231 output_file_close(p->traceOut);
7232 p->traceOut = output_file_open(azArg[1]);
7233#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7234 if( p->traceOut==0 ){
7235 sqlite3_trace_v2(p->db, 0, 0, 0);
7236 }else{
7237 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
7238 }
7239#endif
7240 }else
7241
7242#if SQLITE_USER_AUTHENTICATION
7243 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7244 if( nArg<2 ){
7245 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
7246 rc = 1;
7247 goto meta_command_exit;
7248 }
7249 open_db(p, 0);
7250 if( strcmp(azArg[1],"login")==0 ){
7251 if( nArg!=4 ){
7252 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
7253 rc = 1;
7254 goto meta_command_exit;
7255 }
drhaf2770f2018-01-05 14:55:43 +00007256 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00007257 if( rc ){
7258 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
7259 rc = 1;
7260 }
7261 }else if( strcmp(azArg[1],"add")==0 ){
7262 if( nArg!=5 ){
7263 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
7264 rc = 1;
7265 goto meta_command_exit;
7266 }
drhaf2770f2018-01-05 14:55:43 +00007267 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007268 booleanValue(azArg[4]));
7269 if( rc ){
7270 raw_printf(stderr, "User-Add failed: %d\n", rc);
7271 rc = 1;
7272 }
7273 }else if( strcmp(azArg[1],"edit")==0 ){
7274 if( nArg!=5 ){
7275 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
7276 rc = 1;
7277 goto meta_command_exit;
7278 }
drhaf2770f2018-01-05 14:55:43 +00007279 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007280 booleanValue(azArg[4]));
7281 if( rc ){
7282 raw_printf(stderr, "User-Edit failed: %d\n", rc);
7283 rc = 1;
7284 }
7285 }else if( strcmp(azArg[1],"delete")==0 ){
7286 if( nArg!=3 ){
7287 raw_printf(stderr, "Usage: .user delete USER\n");
7288 rc = 1;
7289 goto meta_command_exit;
7290 }
7291 rc = sqlite3_user_delete(p->db, azArg[2]);
7292 if( rc ){
7293 raw_printf(stderr, "User-Delete failed: %d\n", rc);
7294 rc = 1;
7295 }
7296 }else{
7297 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
7298 rc = 1;
7299 goto meta_command_exit;
7300 }
7301 }else
7302#endif /* SQLITE_USER_AUTHENTICATION */
7303
7304 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
7305 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
7306 sqlite3_libversion(), sqlite3_sourceid());
7307 }else
7308
7309 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7310 const char *zDbName = nArg==2 ? azArg[1] : "main";
7311 sqlite3_vfs *pVfs = 0;
7312 if( p->db ){
7313 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7314 if( pVfs ){
7315 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7316 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7317 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7318 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7319 }
7320 }
7321 }else
7322
7323 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7324 sqlite3_vfs *pVfs;
7325 sqlite3_vfs *pCurrent = 0;
7326 if( p->db ){
7327 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7328 }
7329 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7330 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7331 pVfs==pCurrent ? " <--- CURRENT" : "");
7332 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7333 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7334 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7335 if( pVfs->pNext ){
7336 raw_printf(p->out, "-----------------------------------\n");
7337 }
7338 }
7339 }else
7340
7341 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7342 const char *zDbName = nArg==2 ? azArg[1] : "main";
7343 char *zVfsName = 0;
7344 if( p->db ){
7345 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7346 if( zVfsName ){
7347 utf8_printf(p->out, "%s\n", zVfsName);
7348 sqlite3_free(zVfsName);
7349 }
7350 }
7351 }else
7352
7353#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7354 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
7355 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
7356 }else
7357#endif
7358
7359 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
7360 int j;
7361 assert( nArg<=ArraySize(azArg) );
7362 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
7363 p->colWidth[j-1] = (int)integerValue(azArg[j]);
7364 }
7365 }else
7366
7367 {
7368 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
7369 " \"%s\". Enter \".help\" for help\n", azArg[0]);
7370 rc = 1;
7371 }
7372
7373meta_command_exit:
7374 if( p->outCount ){
7375 p->outCount--;
7376 if( p->outCount==0 ) output_reset(p);
7377 }
7378 return rc;
7379}
7380
7381/*
7382** Return TRUE if a semicolon occurs anywhere in the first N characters
7383** of string z[].
7384*/
7385static int line_contains_semicolon(const char *z, int N){
7386 int i;
7387 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
7388 return 0;
7389}
7390
7391/*
7392** Test to see if a line consists entirely of whitespace.
7393*/
7394static int _all_whitespace(const char *z){
7395 for(; *z; z++){
7396 if( IsSpace(z[0]) ) continue;
7397 if( *z=='/' && z[1]=='*' ){
7398 z += 2;
7399 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
7400 if( *z==0 ) return 0;
7401 z++;
7402 continue;
7403 }
7404 if( *z=='-' && z[1]=='-' ){
7405 z += 2;
7406 while( *z && *z!='\n' ){ z++; }
7407 if( *z==0 ) return 1;
7408 continue;
7409 }
7410 return 0;
7411 }
7412 return 1;
7413}
7414
7415/*
7416** Return TRUE if the line typed in is an SQL command terminator other
7417** than a semi-colon. The SQL Server style "go" command is understood
7418** as is the Oracle "/".
7419*/
7420static int line_is_command_terminator(const char *zLine){
7421 while( IsSpace(zLine[0]) ){ zLine++; };
7422 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
7423 return 1; /* Oracle */
7424 }
7425 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
7426 && _all_whitespace(&zLine[2]) ){
7427 return 1; /* SQL Server */
7428 }
7429 return 0;
7430}
7431
7432/*
7433** Return true if zSql is a complete SQL statement. Return false if it
7434** ends in the middle of a string literal or C-style comment.
7435*/
7436static int line_is_complete(char *zSql, int nSql){
7437 int rc;
7438 if( zSql==0 ) return 1;
7439 zSql[nSql] = ';';
7440 zSql[nSql+1] = 0;
7441 rc = sqlite3_complete(zSql);
7442 zSql[nSql] = 0;
7443 return rc;
7444}
7445
7446/*
7447** Run a single line of SQL
7448*/
7449static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
7450 int rc;
7451 char *zErrMsg = 0;
7452
7453 open_db(p, 0);
7454 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
7455 BEGIN_TIMER;
7456 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
7457 END_TIMER;
7458 if( rc || zErrMsg ){
7459 char zPrefix[100];
7460 if( in!=0 || !stdin_is_interactive ){
7461 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
7462 "Error: near line %d:", startline);
7463 }else{
7464 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
7465 }
7466 if( zErrMsg!=0 ){
7467 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
7468 sqlite3_free(zErrMsg);
7469 zErrMsg = 0;
7470 }else{
7471 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
7472 }
7473 return 1;
7474 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
7475 raw_printf(p->out, "changes: %3d total_changes: %d\n",
7476 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
7477 }
7478 return 0;
7479}
7480
7481
7482/*
7483** Read input from *in and process it. If *in==0 then input
7484** is interactive - the user is typing it it. Otherwise, input
7485** is coming from a file or device. A prompt is issued and history
7486** is saved only if input is interactive. An interrupt signal will
7487** cause this routine to exit immediately, unless input is interactive.
7488**
7489** Return the number of errors.
7490*/
7491static int process_input(ShellState *p, FILE *in){
7492 char *zLine = 0; /* A single input line */
7493 char *zSql = 0; /* Accumulated SQL text */
7494 int nLine; /* Length of current line */
7495 int nSql = 0; /* Bytes of zSql[] used */
7496 int nAlloc = 0; /* Allocated zSql[] space */
7497 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
7498 int rc; /* Error code */
7499 int errCnt = 0; /* Number of errors seen */
7500 int lineno = 0; /* Current line number */
7501 int startline = 0; /* Line number for start of current input */
7502
7503 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
7504 fflush(p->out);
7505 zLine = one_input_line(in, zLine, nSql>0);
7506 if( zLine==0 ){
7507 /* End of input */
7508 if( in==0 && stdin_is_interactive ) printf("\n");
7509 break;
7510 }
7511 if( seenInterrupt ){
7512 if( in!=0 ) break;
7513 seenInterrupt = 0;
7514 }
7515 lineno++;
7516 if( nSql==0 && _all_whitespace(zLine) ){
7517 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7518 continue;
7519 }
7520 if( zLine && zLine[0]=='.' && nSql==0 ){
7521 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7522 rc = do_meta_command(zLine, p);
7523 if( rc==2 ){ /* exit requested */
7524 break;
7525 }else if( rc ){
7526 errCnt++;
7527 }
7528 continue;
7529 }
7530 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
7531 memcpy(zLine,";",2);
7532 }
7533 nLine = strlen30(zLine);
7534 if( nSql+nLine+2>=nAlloc ){
7535 nAlloc = nSql+nLine+100;
7536 zSql = realloc(zSql, nAlloc);
7537 if( zSql==0 ){
7538 raw_printf(stderr, "Error: out of memory\n");
7539 exit(1);
7540 }
7541 }
7542 nSqlPrior = nSql;
7543 if( nSql==0 ){
7544 int i;
7545 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
7546 assert( nAlloc>0 && zSql!=0 );
7547 memcpy(zSql, zLine+i, nLine+1-i);
7548 startline = lineno;
7549 nSql = nLine-i;
7550 }else{
7551 zSql[nSql++] = '\n';
7552 memcpy(zSql+nSql, zLine, nLine+1);
7553 nSql += nLine;
7554 }
7555 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
7556 && sqlite3_complete(zSql) ){
7557 errCnt += runOneSqlLine(p, zSql, in, startline);
7558 nSql = 0;
7559 if( p->outCount ){
7560 output_reset(p);
7561 p->outCount = 0;
7562 }
7563 }else if( nSql && _all_whitespace(zSql) ){
7564 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
7565 nSql = 0;
7566 }
7567 }
7568 if( nSql && !_all_whitespace(zSql) ){
7569 runOneSqlLine(p, zSql, in, startline);
7570 }
7571 free(zSql);
7572 free(zLine);
7573 return errCnt>0;
7574}
7575
7576/*
7577** Return a pathname which is the user's home directory. A
7578** 0 return indicates an error of some kind.
7579*/
7580static char *find_home_dir(int clearFlag){
7581 static char *home_dir = NULL;
7582 if( clearFlag ){
7583 free(home_dir);
7584 home_dir = 0;
7585 return 0;
7586 }
7587 if( home_dir ) return home_dir;
7588
7589#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7590 && !defined(__RTP__) && !defined(_WRS_KERNEL)
7591 {
7592 struct passwd *pwent;
7593 uid_t uid = getuid();
7594 if( (pwent=getpwuid(uid)) != NULL) {
7595 home_dir = pwent->pw_dir;
7596 }
7597 }
7598#endif
7599
7600#if defined(_WIN32_WCE)
7601 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7602 */
7603 home_dir = "/";
7604#else
7605
7606#if defined(_WIN32) || defined(WIN32)
7607 if (!home_dir) {
7608 home_dir = getenv("USERPROFILE");
7609 }
7610#endif
7611
7612 if (!home_dir) {
7613 home_dir = getenv("HOME");
7614 }
7615
7616#if defined(_WIN32) || defined(WIN32)
7617 if (!home_dir) {
7618 char *zDrive, *zPath;
7619 int n;
7620 zDrive = getenv("HOMEDRIVE");
7621 zPath = getenv("HOMEPATH");
7622 if( zDrive && zPath ){
7623 n = strlen30(zDrive) + strlen30(zPath) + 1;
7624 home_dir = malloc( n );
7625 if( home_dir==0 ) return 0;
7626 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7627 return home_dir;
7628 }
7629 home_dir = "c:\\";
7630 }
7631#endif
7632
7633#endif /* !_WIN32_WCE */
7634
7635 if( home_dir ){
7636 int n = strlen30(home_dir) + 1;
7637 char *z = malloc( n );
7638 if( z ) memcpy(z, home_dir, n);
7639 home_dir = z;
7640 }
7641
7642 return home_dir;
7643}
7644
7645/*
7646** Read input from the file given by sqliterc_override. Or if that
7647** parameter is NULL, take input from ~/.sqliterc
7648**
7649** Returns the number of errors.
7650*/
7651static void process_sqliterc(
7652 ShellState *p, /* Configuration data */
7653 const char *sqliterc_override /* Name of config file. NULL to use default */
7654){
7655 char *home_dir = NULL;
7656 const char *sqliterc = sqliterc_override;
7657 char *zBuf = 0;
7658 FILE *in = NULL;
7659
7660 if (sqliterc == NULL) {
7661 home_dir = find_home_dir(0);
7662 if( home_dir==0 ){
7663 raw_printf(stderr, "-- warning: cannot find home directory;"
7664 " cannot read ~/.sqliterc\n");
7665 return;
7666 }
7667 sqlite3_initialize();
7668 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7669 sqliterc = zBuf;
7670 }
7671 in = fopen(sqliterc,"rb");
7672 if( in ){
7673 if( stdin_is_interactive ){
7674 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
7675 }
7676 process_input(p,in);
7677 fclose(in);
7678 }
7679 sqlite3_free(zBuf);
7680}
7681
7682/*
7683** Show available command line options
7684*/
7685static const char zOptions[] =
7686 " -ascii set output mode to 'ascii'\n"
7687 " -bail stop after hitting an error\n"
7688 " -batch force batch I/O\n"
7689 " -column set output mode to 'column'\n"
7690 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
7691 " -csv set output mode to 'csv'\n"
7692 " -echo print commands before execution\n"
7693 " -init FILENAME read/process named file\n"
7694 " -[no]header turn headers on or off\n"
7695#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7696 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7697#endif
7698 " -help show this message\n"
7699 " -html set output mode to HTML\n"
7700 " -interactive force interactive I/O\n"
7701 " -line set output mode to 'line'\n"
7702 " -list set output mode to 'list'\n"
7703 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
7704 " -mmap N default mmap size set to N\n"
7705#ifdef SQLITE_ENABLE_MULTIPLEX
7706 " -multiplex enable the multiplexor VFS\n"
7707#endif
7708 " -newline SEP set output row separator. Default: '\\n'\n"
7709 " -nullvalue TEXT set text string for NULL values. Default ''\n"
7710 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7711 " -quote set output mode to 'quote'\n"
drh2ce15c32017-07-11 13:34:40 +00007712 " -separator SEP set output column separator. Default: '|'\n"
7713 " -stats print memory stats before each finalize\n"
7714 " -version show SQLite version\n"
7715 " -vfs NAME use NAME as the default VFS\n"
7716#ifdef SQLITE_ENABLE_VFSTRACE
7717 " -vfstrace enable tracing of all VFS calls\n"
7718#endif
7719;
7720static void usage(int showDetail){
7721 utf8_printf(stderr,
7722 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
7723 "FILENAME is the name of an SQLite database. A new database is created\n"
7724 "if the file does not previously exist.\n", Argv0);
7725 if( showDetail ){
7726 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
7727 }else{
7728 raw_printf(stderr, "Use the -help option for additional information\n");
7729 }
7730 exit(1);
7731}
7732
7733/*
7734** Initialize the state information in data
7735*/
7736static void main_init(ShellState *data) {
7737 memset(data, 0, sizeof(*data));
7738 data->normalMode = data->cMode = data->mode = MODE_List;
7739 data->autoExplain = 1;
7740 memcpy(data->colSeparator,SEP_Column, 2);
7741 memcpy(data->rowSeparator,SEP_Row, 2);
7742 data->showHeader = 0;
7743 data->shellFlgs = SHFLG_Lookaside;
7744 sqlite3_config(SQLITE_CONFIG_URI, 1);
7745 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
7746 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
7747 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7748 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
7749}
7750
7751/*
7752** Output text to the console in a font that attracts extra attention.
7753*/
7754#ifdef _WIN32
7755static void printBold(const char *zText){
7756 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7757 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7758 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7759 SetConsoleTextAttribute(out,
7760 FOREGROUND_RED|FOREGROUND_INTENSITY
7761 );
7762 printf("%s", zText);
7763 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
7764}
7765#else
7766static void printBold(const char *zText){
7767 printf("\033[1m%s\033[0m", zText);
7768}
7769#endif
7770
7771/*
7772** Get the argument to an --option. Throw an error and die if no argument
7773** is available.
7774*/
7775static char *cmdline_option_value(int argc, char **argv, int i){
7776 if( i==argc ){
7777 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
7778 argv[0], argv[argc-1]);
7779 exit(1);
7780 }
7781 return argv[i];
7782}
7783
7784#ifndef SQLITE_SHELL_IS_UTF8
7785# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7786# define SQLITE_SHELL_IS_UTF8 (0)
7787# else
7788# define SQLITE_SHELL_IS_UTF8 (1)
7789# endif
7790#endif
7791
7792#if SQLITE_SHELL_IS_UTF8
7793int SQLITE_CDECL main(int argc, char **argv){
7794#else
7795int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
7796 char **argv;
7797#endif
7798 char *zErrMsg = 0;
7799 ShellState data;
7800 const char *zInitFile = 0;
7801 int i;
7802 int rc = 0;
7803 int warnInmemoryDb = 0;
7804 int readStdin = 1;
7805 int nCmd = 0;
7806 char **azCmd = 0;
7807
7808 setBinaryMode(stdin, 0);
7809 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
7810 stdin_is_interactive = isatty(0);
7811 stdout_is_console = isatty(1);
7812
7813#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00007814 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00007815 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
7816 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7817 exit(1);
7818 }
7819#endif
7820 main_init(&data);
7821#if !SQLITE_SHELL_IS_UTF8
7822 sqlite3_initialize();
7823 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7824 if( argv==0 ){
7825 raw_printf(stderr, "out of memory\n");
7826 exit(1);
7827 }
7828 for(i=0; i<argc; i++){
7829 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7830 if( argv[i]==0 ){
7831 raw_printf(stderr, "out of memory\n");
7832 exit(1);
7833 }
7834 }
7835#endif
7836 assert( argc>=1 && argv && argv[0] );
7837 Argv0 = argv[0];
7838
7839 /* Make sure we have a valid signal handler early, before anything
7840 ** else is done.
7841 */
7842#ifdef SIGINT
7843 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00007844#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
7845 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00007846#endif
7847
7848#ifdef SQLITE_SHELL_DBNAME_PROC
7849 {
7850 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7851 ** of a C-function that will provide the name of the database file. Use
7852 ** this compile-time option to embed this shell program in larger
7853 ** applications. */
7854 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7855 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7856 warnInmemoryDb = 0;
7857 }
7858#endif
7859
7860 /* Do an initial pass through the command-line argument to locate
7861 ** the name of the database file, the name of the initialization file,
7862 ** the size of the alternative malloc heap,
7863 ** and the first command to execute.
7864 */
7865 for(i=1; i<argc; i++){
7866 char *z;
7867 z = argv[i];
7868 if( z[0]!='-' ){
7869 if( data.zDbFilename==0 ){
7870 data.zDbFilename = z;
7871 }else{
7872 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7873 ** mean that nothing is read from stdin */
7874 readStdin = 0;
7875 nCmd++;
7876 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7877 if( azCmd==0 ){
7878 raw_printf(stderr, "out of memory\n");
7879 exit(1);
7880 }
7881 azCmd[nCmd-1] = z;
7882 }
7883 }
7884 if( z[1]=='-' ) z++;
7885 if( strcmp(z,"-separator")==0
7886 || strcmp(z,"-nullvalue")==0
7887 || strcmp(z,"-newline")==0
7888 || strcmp(z,"-cmd")==0
7889 ){
7890 (void)cmdline_option_value(argc, argv, ++i);
7891 }else if( strcmp(z,"-init")==0 ){
7892 zInitFile = cmdline_option_value(argc, argv, ++i);
7893 }else if( strcmp(z,"-batch")==0 ){
7894 /* Need to check for batch mode here to so we can avoid printing
7895 ** informational messages (like from process_sqliterc) before
7896 ** we do the actual processing of arguments later in a second pass.
7897 */
7898 stdin_is_interactive = 0;
7899 }else if( strcmp(z,"-heap")==0 ){
7900#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7901 const char *zSize;
7902 sqlite3_int64 szHeap;
7903
7904 zSize = cmdline_option_value(argc, argv, ++i);
7905 szHeap = integerValue(zSize);
7906 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
7907 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
7908#else
7909 (void)cmdline_option_value(argc, argv, ++i);
7910#endif
drh2ce15c32017-07-11 13:34:40 +00007911 }else if( strcmp(z,"-pagecache")==0 ){
7912 int n, sz;
7913 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7914 if( sz>70000 ) sz = 70000;
7915 if( sz<0 ) sz = 0;
7916 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7917 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7918 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
7919 data.shellFlgs |= SHFLG_Pagecache;
7920 }else if( strcmp(z,"-lookaside")==0 ){
7921 int n, sz;
7922 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7923 if( sz<0 ) sz = 0;
7924 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7925 if( n<0 ) n = 0;
7926 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7927 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
7928#ifdef SQLITE_ENABLE_VFSTRACE
7929 }else if( strcmp(z,"-vfstrace")==0 ){
7930 extern int vfstrace_register(
7931 const char *zTraceName,
7932 const char *zOldVfsName,
7933 int (*xOut)(const char*,void*),
7934 void *pOutArg,
7935 int makeDefault
7936 );
7937 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
7938#endif
7939#ifdef SQLITE_ENABLE_MULTIPLEX
7940 }else if( strcmp(z,"-multiplex")==0 ){
7941 extern int sqlite3_multiple_initialize(const char*,int);
7942 sqlite3_multiplex_initialize(0, 1);
7943#endif
7944 }else if( strcmp(z,"-mmap")==0 ){
7945 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7946 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
7947 }else if( strcmp(z,"-vfs")==0 ){
7948 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
7949 if( pVfs ){
7950 sqlite3_vfs_register(pVfs, 1);
7951 }else{
7952 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
7953 exit(1);
7954 }
drh8682e122018-01-07 20:38:10 +00007955#ifdef SQLITE_HAVE_ZIP
7956 }else if( strcmp(z,"-zip")==0 ){
7957 data.openMode = SHELL_OPEN_ZIPFILE;
7958#endif
7959 }else if( strcmp(z,"-append")==0 ){
7960 data.openMode = SHELL_OPEN_APPENDVFS;
drh2ce15c32017-07-11 13:34:40 +00007961 }
7962 }
7963 if( data.zDbFilename==0 ){
7964#ifndef SQLITE_OMIT_MEMORYDB
7965 data.zDbFilename = ":memory:";
7966 warnInmemoryDb = argc==1;
7967#else
7968 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
7969 return 1;
7970#endif
7971 }
7972 data.out = stdout;
drh8682e122018-01-07 20:38:10 +00007973 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +00007974
7975 /* Go ahead and open the database file if it already exists. If the
7976 ** file does not exist, delay opening it. This prevents empty database
7977 ** files from being created if a user mistypes the database name argument
7978 ** to the sqlite command-line tool.
7979 */
7980 if( access(data.zDbFilename, 0)==0 ){
7981 open_db(&data, 0);
7982 }
7983
7984 /* Process the initialization file if there is one. If no -init option
7985 ** is given on the command line, look for a file named ~/.sqliterc and
7986 ** try to process it.
7987 */
7988 process_sqliterc(&data,zInitFile);
7989
7990 /* Make a second pass through the command-line argument and set
7991 ** options. This second pass is delayed until after the initialization
7992 ** file is processed so that the command-line arguments will override
7993 ** settings in the initialization file.
7994 */
7995 for(i=1; i<argc; i++){
7996 char *z = argv[i];
7997 if( z[0]!='-' ) continue;
7998 if( z[1]=='-' ){ z++; }
7999 if( strcmp(z,"-init")==0 ){
8000 i++;
8001 }else if( strcmp(z,"-html")==0 ){
8002 data.mode = MODE_Html;
8003 }else if( strcmp(z,"-list")==0 ){
8004 data.mode = MODE_List;
8005 }else if( strcmp(z,"-quote")==0 ){
8006 data.mode = MODE_Quote;
8007 }else if( strcmp(z,"-line")==0 ){
8008 data.mode = MODE_Line;
8009 }else if( strcmp(z,"-column")==0 ){
8010 data.mode = MODE_Column;
8011 }else if( strcmp(z,"-csv")==0 ){
8012 data.mode = MODE_Csv;
8013 memcpy(data.colSeparator,",",2);
drh1fa6d9f2018-01-06 21:46:01 +00008014#ifdef SQLITE_HAVE_ZIP
8015 }else if( strcmp(z,"-zip")==0 ){
8016 data.openMode = SHELL_OPEN_ZIPFILE;
8017#endif
8018 }else if( strcmp(z,"-append")==0 ){
8019 data.openMode = SHELL_OPEN_APPENDVFS;
drh2ce15c32017-07-11 13:34:40 +00008020 }else if( strcmp(z,"-ascii")==0 ){
8021 data.mode = MODE_Ascii;
8022 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8023 SEP_Unit);
8024 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8025 SEP_Record);
8026 }else if( strcmp(z,"-separator")==0 ){
8027 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8028 "%s",cmdline_option_value(argc,argv,++i));
8029 }else if( strcmp(z,"-newline")==0 ){
8030 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8031 "%s",cmdline_option_value(argc,argv,++i));
8032 }else if( strcmp(z,"-nullvalue")==0 ){
8033 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
8034 "%s",cmdline_option_value(argc,argv,++i));
8035 }else if( strcmp(z,"-header")==0 ){
8036 data.showHeader = 1;
8037 }else if( strcmp(z,"-noheader")==0 ){
8038 data.showHeader = 0;
8039 }else if( strcmp(z,"-echo")==0 ){
8040 ShellSetFlag(&data, SHFLG_Echo);
8041 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +00008042 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +00008043 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +00008044 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +00008045 }else if( strcmp(z,"-stats")==0 ){
8046 data.statsOn = 1;
8047 }else if( strcmp(z,"-scanstats")==0 ){
8048 data.scanstatsOn = 1;
8049 }else if( strcmp(z,"-backslash")==0 ){
8050 /* Undocumented command-line option: -backslash
8051 ** Causes C-style backslash escapes to be evaluated in SQL statements
8052 ** prior to sending the SQL into SQLite. Useful for injecting
8053 ** crazy bytes in the middle of SQL statements for testing and debugging.
8054 */
8055 ShellSetFlag(&data, SHFLG_Backslash);
8056 }else if( strcmp(z,"-bail")==0 ){
8057 bail_on_error = 1;
8058 }else if( strcmp(z,"-version")==0 ){
8059 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8060 return 0;
8061 }else if( strcmp(z,"-interactive")==0 ){
8062 stdin_is_interactive = 1;
8063 }else if( strcmp(z,"-batch")==0 ){
8064 stdin_is_interactive = 0;
8065 }else if( strcmp(z,"-heap")==0 ){
8066 i++;
drh2ce15c32017-07-11 13:34:40 +00008067 }else if( strcmp(z,"-pagecache")==0 ){
8068 i+=2;
8069 }else if( strcmp(z,"-lookaside")==0 ){
8070 i+=2;
8071 }else if( strcmp(z,"-mmap")==0 ){
8072 i++;
8073 }else if( strcmp(z,"-vfs")==0 ){
8074 i++;
8075#ifdef SQLITE_ENABLE_VFSTRACE
8076 }else if( strcmp(z,"-vfstrace")==0 ){
8077 i++;
8078#endif
8079#ifdef SQLITE_ENABLE_MULTIPLEX
8080 }else if( strcmp(z,"-multiplex")==0 ){
8081 i++;
8082#endif
8083 }else if( strcmp(z,"-help")==0 ){
8084 usage(1);
8085 }else if( strcmp(z,"-cmd")==0 ){
8086 /* Run commands that follow -cmd first and separately from commands
8087 ** that simply appear on the command-line. This seems goofy. It would
8088 ** be better if all commands ran in the order that they appear. But
8089 ** we retain the goofy behavior for historical compatibility. */
8090 if( i==argc-1 ) break;
8091 z = cmdline_option_value(argc,argv,++i);
8092 if( z[0]=='.' ){
8093 rc = do_meta_command(z, &data);
8094 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
8095 }else{
8096 open_db(&data, 0);
8097 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
8098 if( zErrMsg!=0 ){
8099 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8100 if( bail_on_error ) return rc!=0 ? rc : 1;
8101 }else if( rc!=0 ){
8102 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
8103 if( bail_on_error ) return rc;
8104 }
8105 }
8106 }else{
8107 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
8108 raw_printf(stderr,"Use -help for a list of options.\n");
8109 return 1;
8110 }
8111 data.cMode = data.mode;
8112 }
8113
8114 if( !readStdin ){
8115 /* Run all arguments that do not begin with '-' as if they were separate
8116 ** command-line inputs, except for the argToSkip argument which contains
8117 ** the database filename.
8118 */
8119 for(i=0; i<nCmd; i++){
8120 if( azCmd[i][0]=='.' ){
8121 rc = do_meta_command(azCmd[i], &data);
8122 if( rc ) return rc==2 ? 0 : rc;
8123 }else{
8124 open_db(&data, 0);
8125 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
8126 if( zErrMsg!=0 ){
8127 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8128 return rc!=0 ? rc : 1;
8129 }else if( rc!=0 ){
8130 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
8131 return rc;
8132 }
8133 }
8134 }
8135 free(azCmd);
8136 }else{
8137 /* Run commands received from standard input
8138 */
8139 if( stdin_is_interactive ){
8140 char *zHome;
8141 char *zHistory = 0;
8142 int nHistory;
8143 printf(
8144 "SQLite version %s %.19s\n" /*extra-version-info*/
8145 "Enter \".help\" for usage hints.\n",
8146 sqlite3_libversion(), sqlite3_sourceid()
8147 );
8148 if( warnInmemoryDb ){
8149 printf("Connected to a ");
8150 printBold("transient in-memory database");
8151 printf(".\nUse \".open FILENAME\" to reopen on a "
8152 "persistent database.\n");
8153 }
8154 zHome = find_home_dir(0);
8155 if( zHome ){
8156 nHistory = strlen30(zHome) + 20;
8157 if( (zHistory = malloc(nHistory))!=0 ){
8158 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8159 }
8160 }
8161 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +00008162#if HAVE_READLINE || HAVE_EDITLINE
8163 rl_attempted_completion_function = readline_completion;
8164#elif HAVE_LINENOISE
8165 linenoiseSetCompletionCallback(linenoise_completion);
8166#endif
drh2ce15c32017-07-11 13:34:40 +00008167 rc = process_input(&data, 0);
8168 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +00008169 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +00008170 shell_write_history(zHistory);
8171 free(zHistory);
8172 }
8173 }else{
8174 rc = process_input(&data, stdin);
8175 }
8176 }
8177 set_table_name(&data, 0);
8178 if( data.db ){
8179 session_close_all(&data);
8180 sqlite3_close(data.db);
8181 }
8182 sqlite3_free(data.zFreeOnClose);
8183 find_home_dir(1);
8184#if !SQLITE_SHELL_IS_UTF8
8185 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
8186 sqlite3_free(argv);
8187#endif
8188 return rc;
8189}