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