blob: f7389f3097866540b20c96db017536489cca3f0c [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);
drhb9685182018-01-17 13:15:23 +0000868 UNUSED_PARAMETER(nVal);
drh667a2a22018-01-02 00:04:37 +0000869 if( zFake ){
dandcfbff92018-01-08 17:05:32 +0000870 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
drh667a2a22018-01-02 00:04:37 +0000871 -1, sqlite3_free);
dandcfbff92018-01-08 17:05:32 +0000872 free(zFake);
drh667a2a22018-01-02 00:04:37 +0000873 }
874}
875
876/*
drh2ce15c32017-07-11 13:34:40 +0000877** SQL function: shell_add_schema(S,X)
878**
879** Add the schema name X to the CREATE statement in S and return the result.
880** Examples:
881**
882** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
883**
884** Also works on
885**
886** CREATE INDEX
887** CREATE UNIQUE INDEX
888** CREATE VIEW
889** CREATE TRIGGER
890** CREATE VIRTUAL TABLE
891**
892** This UDF is used by the .schema command to insert the schema name of
893** attached databases into the middle of the sqlite_master.sql field.
894*/
895static void shellAddSchemaName(
896 sqlite3_context *pCtx,
897 int nVal,
898 sqlite3_value **apVal
899){
900 static const char *aPrefix[] = {
901 "TABLE",
902 "INDEX",
903 "UNIQUE INDEX",
904 "VIEW",
905 "TRIGGER",
906 "VIRTUAL TABLE"
907 };
908 int i = 0;
909 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
910 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
drh667a2a22018-01-02 00:04:37 +0000911 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
drhceba7922018-01-01 21:28:25 +0000912 sqlite3 *db = sqlite3_context_db_handle(pCtx);
drhb9685182018-01-17 13:15:23 +0000913 UNUSED_PARAMETER(nVal);
drh2ce15c32017-07-11 13:34:40 +0000914 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
drh89997982017-07-11 18:11:33 +0000915 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
drh2ce15c32017-07-11 13:34:40 +0000916 int n = strlen30(aPrefix[i]);
917 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
drhceba7922018-01-01 21:28:25 +0000918 char *z = 0;
drh667a2a22018-01-02 00:04:37 +0000919 char *zFake = 0;
drhceba7922018-01-01 21:28:25 +0000920 if( zSchema ){
921 char cQuote = quoteChar(zSchema);
922 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
923 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
924 }else{
925 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
926 }
drh2ce15c32017-07-11 13:34:40 +0000927 }
drh667a2a22018-01-02 00:04:37 +0000928 if( zName
929 && aPrefix[i][0]=='V'
930 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
931 ){
932 if( z==0 ){
dandcfbff92018-01-08 17:05:32 +0000933 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
drh667a2a22018-01-02 00:04:37 +0000934 }else{
dandcfbff92018-01-08 17:05:32 +0000935 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
drh667a2a22018-01-02 00:04:37 +0000936 }
dandcfbff92018-01-08 17:05:32 +0000937 free(zFake);
drhceba7922018-01-01 21:28:25 +0000938 }
939 if( z ){
940 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
941 return;
942 }
drh2ce15c32017-07-11 13:34:40 +0000943 }
944 }
945 }
946 sqlite3_result_value(pCtx, apVal[0]);
947}
948
949/*
950** The source code for several run-time loadable extensions is inserted
951** below by the ../tool/mkshellc.tcl script. Before processing that included
952** code, we need to override some macros to make the included program code
953** work here in the middle of this regular program.
954*/
955#define SQLITE_EXTENSION_INIT1
drh89997982017-07-11 18:11:33 +0000956#define SQLITE_EXTENSION_INIT2(X) (void)(X)
drh2ce15c32017-07-11 13:34:40 +0000957
mistachkinacae8c32018-01-05 20:08:46 +0000958#if defined(_WIN32) && defined(_MSC_VER)
drh03491a12018-01-07 21:58:17 +0000959INCLUDE test_windirent.h
mistachkindfdfd8c2018-01-04 22:46:08 +0000960INCLUDE test_windirent.c
961#define dirent DIRENT
mistachkindfdfd8c2018-01-04 22:46:08 +0000962#endif
drh2ce15c32017-07-11 13:34:40 +0000963INCLUDE ../ext/misc/shathree.c
964INCLUDE ../ext/misc/fileio.c
drh56eb09b2017-07-11 13:59:07 +0000965INCLUDE ../ext/misc/completion.c
drh8682e122018-01-07 20:38:10 +0000966INCLUDE ../ext/misc/appendvfs.c
dan72afc3c2017-12-05 18:32:40 +0000967#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +0000968INCLUDE ../ext/misc/zipfile.c
dand1b51d42017-12-16 19:11:26 +0000969INCLUDE ../ext/misc/sqlar.c
dan72afc3c2017-12-05 18:32:40 +0000970#endif
dan43efc182017-12-19 17:42:13 +0000971INCLUDE ../ext/expert/sqlite3expert.h
972INCLUDE ../ext/expert/sqlite3expert.c
drh2ce15c32017-07-11 13:34:40 +0000973
974#if defined(SQLITE_ENABLE_SESSION)
975/*
976** State information for a single open session
977*/
978typedef struct OpenSession OpenSession;
979struct OpenSession {
980 char *zName; /* Symbolic name for this session */
981 int nFilter; /* Number of xFilter rejection GLOB patterns */
982 char **azFilter; /* Array of xFilter rejection GLOB patterns */
983 sqlite3_session *p; /* The open session */
984};
985#endif
986
987/*
988** Shell output mode information from before ".explain on",
989** saved so that it can be restored by ".explain off"
990*/
991typedef struct SavedModeInfo SavedModeInfo;
992struct SavedModeInfo {
993 int valid; /* Is there legit data in here? */
994 int mode; /* Mode prior to ".explain on" */
995 int showHeader; /* The ".header" setting prior to ".explain on" */
996 int colWidth[100]; /* Column widths prior to ".explain on" */
997};
998
dan43efc182017-12-19 17:42:13 +0000999typedef struct ExpertInfo ExpertInfo;
1000struct ExpertInfo {
1001 sqlite3expert *pExpert;
1002 int bVerbose;
1003};
1004
drh2ce15c32017-07-11 13:34:40 +00001005/*
1006** State information about the database connection is contained in an
1007** instance of the following structure.
1008*/
1009typedef struct ShellState ShellState;
1010struct ShellState {
1011 sqlite3 *db; /* The database */
drh1fa6d9f2018-01-06 21:46:01 +00001012 u8 autoExplain; /* Automatically turn on .explain mode */
1013 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1014 u8 statsOn; /* True to display memory stats before each finalize */
1015 u8 scanstatsOn; /* True to display scan stats before each finalize */
1016 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
drh13c20932018-01-10 21:41:55 +00001017 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
drh2ce15c32017-07-11 13:34:40 +00001018 int outCount; /* Revert to stdout when reaching zero */
1019 int cnt; /* Number of records displayed so far */
1020 FILE *out; /* Write results here */
1021 FILE *traceOut; /* Output for sqlite3_trace() */
1022 int nErr; /* Number of errors seen */
1023 int mode; /* An output mode setting */
drh3c484e82018-01-10 22:27:21 +00001024 int modePrior; /* Saved mode */
drh2ce15c32017-07-11 13:34:40 +00001025 int cMode; /* temporary output mode for the current query */
1026 int normalMode; /* Output mode before ".explain on" */
1027 int writableSchema; /* True if PRAGMA writable_schema=ON */
1028 int showHeader; /* True to show column names in List or Column mode */
1029 int nCheck; /* Number of ".check" commands run */
1030 unsigned shellFlgs; /* Various flags */
1031 char *zDestTable; /* Name of destination table when MODE_Insert */
drh13c20932018-01-10 21:41:55 +00001032 char *zTempFile; /* Temporary file that might need deleting */
drh2ce15c32017-07-11 13:34:40 +00001033 char zTestcase[30]; /* Name of current test case */
1034 char colSeparator[20]; /* Column separator character for several modes */
1035 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drh3c484e82018-01-10 22:27:21 +00001036 char colSepPrior[20]; /* Saved column separator */
1037 char rowSepPrior[20]; /* Saved row separator */
drh2ce15c32017-07-11 13:34:40 +00001038 int colWidth[100]; /* Requested width of each column when in column mode*/
1039 int actualWidth[100]; /* Actual width of each column */
1040 char nullValue[20]; /* The text to print when a NULL comes back from
1041 ** the database */
1042 char outfile[FILENAME_MAX]; /* Filename for *out */
1043 const char *zDbFilename; /* name of the database file */
1044 char *zFreeOnClose; /* Filename to free when closing */
1045 const char *zVfs; /* Name of VFS to use */
1046 sqlite3_stmt *pStmt; /* Current statement if any. */
1047 FILE *pLog; /* Write log output here */
1048 int *aiIndent; /* Array of indents used in MODE_Explain */
1049 int nIndent; /* Size of array aiIndent[] */
1050 int iIndent; /* Index of current op in aiIndent[] */
1051#if defined(SQLITE_ENABLE_SESSION)
1052 int nSession; /* Number of active sessions */
1053 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1054#endif
dan43efc182017-12-19 17:42:13 +00001055 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
drh2ce15c32017-07-11 13:34:40 +00001056};
1057
drh1fa6d9f2018-01-06 21:46:01 +00001058
drhada70452017-12-21 21:02:27 +00001059/* Allowed values for ShellState.autoEQP
1060*/
1061#define AUTOEQP_off 0
1062#define AUTOEQP_on 1
1063#define AUTOEQP_trigger 2
1064#define AUTOEQP_full 3
1065
drh1fa6d9f2018-01-06 21:46:01 +00001066/* Allowed values for ShellState.openMode
1067*/
1068#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1069#define SHELL_OPEN_NORMAL 1 /* Normal database file */
1070#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1071#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
drhee269a62018-02-14 23:27:43 +00001072#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
drh1fa6d9f2018-01-06 21:46:01 +00001073
drh2ce15c32017-07-11 13:34:40 +00001074/*
1075** These are the allowed shellFlgs values
1076*/
drhb2a0f752017-08-28 15:51:35 +00001077#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1078#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1079#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1080#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1081#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1082#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1083#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
drh2ce15c32017-07-11 13:34:40 +00001084
1085/*
1086** Macros for testing and setting shellFlgs
1087*/
1088#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1089#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1090#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1091
1092/*
1093** These are the allowed modes.
1094*/
1095#define MODE_Line 0 /* One column per line. Blank line between records */
1096#define MODE_Column 1 /* One record per line in neat columns */
1097#define MODE_List 2 /* One record per line with a separator */
1098#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1099#define MODE_Html 4 /* Generate an XHTML table */
1100#define MODE_Insert 5 /* Generate SQL "insert" statements */
1101#define MODE_Quote 6 /* Quote values as for SQL */
1102#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1103#define MODE_Csv 8 /* Quote strings, numbers are plain */
1104#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1105#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1106#define MODE_Pretty 11 /* Pretty-print schemas */
1107
1108static const char *modeDescr[] = {
1109 "line",
1110 "column",
1111 "list",
1112 "semi",
1113 "html",
1114 "insert",
1115 "quote",
1116 "tcl",
1117 "csv",
1118 "explain",
1119 "ascii",
1120 "prettyprint",
1121};
1122
1123/*
1124** These are the column/row/line separators used by the various
1125** import/export modes.
1126*/
1127#define SEP_Column "|"
1128#define SEP_Row "\n"
1129#define SEP_Tab "\t"
1130#define SEP_Space " "
1131#define SEP_Comma ","
1132#define SEP_CrLf "\r\n"
1133#define SEP_Unit "\x1F"
1134#define SEP_Record "\x1E"
1135
1136/*
drh2ce15c32017-07-11 13:34:40 +00001137** A callback for the sqlite3_log() interface.
1138*/
1139static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1140 ShellState *p = (ShellState*)pArg;
1141 if( p->pLog==0 ) return;
1142 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1143 fflush(p->pLog);
1144}
1145
1146/*
drh634c70f2018-01-10 16:50:18 +00001147** SQL function: shell_putsnl(X)
1148**
1149** Write the text X to the screen (or whatever output is being directed)
1150** adding a newline at the end, and then return X.
1151*/
1152static void shellPutsFunc(
1153 sqlite3_context *pCtx,
1154 int nVal,
1155 sqlite3_value **apVal
1156){
1157 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
drhb9685182018-01-17 13:15:23 +00001158 (void)nVal;
drh634c70f2018-01-10 16:50:18 +00001159 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1160 sqlite3_result_value(pCtx, apVal[0]);
1161}
1162
1163/*
drh97913132018-01-11 00:04:00 +00001164** SQL function: edit(VALUE)
1165** edit(VALUE,EDITOR)
1166**
1167** These steps:
1168**
1169** (1) Write VALUE into a temporary file.
1170** (2) Run program EDITOR on that temporary file.
1171** (3) Read the temporary file back and return its content as the result.
1172** (4) Delete the temporary file
1173**
1174** If the EDITOR argument is omitted, use the value in the VISUAL
1175** environment variable. If still there is no EDITOR, through an error.
1176**
1177** Also throw an error if the EDITOR program returns a non-zero exit code.
1178*/
drh04a28c32018-01-31 01:38:44 +00001179#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00001180static void editFunc(
1181 sqlite3_context *context,
1182 int argc,
1183 sqlite3_value **argv
1184){
1185 const char *zEditor;
1186 char *zTempFile = 0;
1187 sqlite3 *db;
1188 char *zCmd = 0;
1189 int bBin;
1190 int rc;
1191 FILE *f = 0;
1192 sqlite3_int64 sz;
1193 sqlite3_int64 x;
1194 unsigned char *p = 0;
1195
1196 if( argc==2 ){
1197 zEditor = (const char*)sqlite3_value_text(argv[1]);
1198 }else{
1199 zEditor = getenv("VISUAL");
1200 }
1201 if( zEditor==0 ){
1202 sqlite3_result_error(context, "no editor for edit()", -1);
1203 return;
1204 }
1205 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1206 sqlite3_result_error(context, "NULL input to edit()", -1);
1207 return;
1208 }
1209 db = sqlite3_context_db_handle(context);
1210 zTempFile = 0;
1211 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1212 if( zTempFile==0 ){
1213 sqlite3_uint64 r = 0;
1214 sqlite3_randomness(sizeof(r), &r);
1215 zTempFile = sqlite3_mprintf("temp%llx", r);
1216 if( zTempFile==0 ){
1217 sqlite3_result_error_nomem(context);
1218 return;
1219 }
1220 }
1221 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
1222 f = fopen(zTempFile, bBin ? "wb" : "w");
1223 if( f==0 ){
1224 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1225 goto edit_func_end;
1226 }
1227 sz = sqlite3_value_bytes(argv[0]);
1228 if( bBin ){
1229 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
1230 }else{
1231 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
1232 }
1233 fclose(f);
1234 f = 0;
1235 if( x!=sz ){
1236 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1237 goto edit_func_end;
1238 }
1239 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1240 if( zCmd==0 ){
1241 sqlite3_result_error_nomem(context);
1242 goto edit_func_end;
1243 }
1244 rc = system(zCmd);
1245 sqlite3_free(zCmd);
1246 if( rc ){
1247 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1248 goto edit_func_end;
1249 }
1250 f = fopen(zTempFile, bBin ? "rb" : "r");
1251 if( f==0 ){
1252 sqlite3_result_error(context,
1253 "edit() cannot reopen temp file after edit", -1);
1254 goto edit_func_end;
1255 }
1256 fseek(f, 0, SEEK_END);
1257 sz = ftell(f);
1258 rewind(f);
1259 p = sqlite3_malloc64( sz+(bBin==0) );
1260 if( p==0 ){
1261 sqlite3_result_error_nomem(context);
1262 goto edit_func_end;
1263 }
1264 if( bBin ){
1265 x = fread(p, 1, sz, f);
1266 }else{
1267 x = fread(p, 1, sz, f);
1268 p[sz] = 0;
1269 }
1270 fclose(f);
1271 f = 0;
1272 if( x!=sz ){
1273 sqlite3_result_error(context, "could not read back the whole file", -1);
1274 goto edit_func_end;
1275 }
1276 if( bBin ){
mistachkinb71aa092018-01-23 00:05:18 +00001277 sqlite3_result_blob64(context, p, sz, sqlite3_free);
drh97913132018-01-11 00:04:00 +00001278 }else{
mistachkinb71aa092018-01-23 00:05:18 +00001279 sqlite3_result_text64(context, (const char*)p, sz,
1280 sqlite3_free, SQLITE_UTF8);
drh97913132018-01-11 00:04:00 +00001281 }
1282 p = 0;
1283
1284edit_func_end:
1285 if( f ) fclose(f);
1286 unlink(zTempFile);
1287 sqlite3_free(zTempFile);
1288 sqlite3_free(p);
1289}
drh04a28c32018-01-31 01:38:44 +00001290#endif /* SQLITE_NOHAVE_SYSTEM */
drh97913132018-01-11 00:04:00 +00001291
1292/*
drh3c484e82018-01-10 22:27:21 +00001293** Save or restore the current output mode
1294*/
1295static void outputModePush(ShellState *p){
1296 p->modePrior = p->mode;
1297 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1298 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1299}
1300static void outputModePop(ShellState *p){
1301 p->mode = p->modePrior;
1302 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1303 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1304}
1305
1306/*
drh2ce15c32017-07-11 13:34:40 +00001307** Output the given string as a hex-encoded blob (eg. X'1234' )
1308*/
1309static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1310 int i;
1311 char *zBlob = (char *)pBlob;
1312 raw_printf(out,"X'");
1313 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1314 raw_printf(out,"'");
1315}
1316
1317/*
1318** Find a string that is not found anywhere in z[]. Return a pointer
1319** to that string.
1320**
1321** Try to use zA and zB first. If both of those are already found in z[]
1322** then make up some string and store it in the buffer zBuf.
1323*/
1324static const char *unused_string(
1325 const char *z, /* Result must not appear anywhere in z */
1326 const char *zA, const char *zB, /* Try these first */
1327 char *zBuf /* Space to store a generated string */
1328){
1329 unsigned i = 0;
1330 if( strstr(z, zA)==0 ) return zA;
1331 if( strstr(z, zB)==0 ) return zB;
1332 do{
1333 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1334 }while( strstr(z,zBuf)!=0 );
1335 return zBuf;
1336}
1337
1338/*
1339** Output the given string as a quoted string using SQL quoting conventions.
1340**
1341** See also: output_quoted_escaped_string()
1342*/
1343static void output_quoted_string(FILE *out, const char *z){
1344 int i;
1345 char c;
1346 setBinaryMode(out, 1);
1347 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1348 if( c==0 ){
1349 utf8_printf(out,"'%s'",z);
1350 }else{
1351 raw_printf(out, "'");
1352 while( *z ){
1353 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1354 if( c=='\'' ) i++;
1355 if( i ){
1356 utf8_printf(out, "%.*s", i, z);
1357 z += i;
1358 }
1359 if( c=='\'' ){
1360 raw_printf(out, "'");
1361 continue;
1362 }
1363 if( c==0 ){
1364 break;
1365 }
1366 z++;
1367 }
1368 raw_printf(out, "'");
1369 }
1370 setTextMode(out, 1);
1371}
1372
1373/*
1374** Output the given string as a quoted string using SQL quoting conventions.
1375** Additionallly , escape the "\n" and "\r" characters so that they do not
1376** get corrupted by end-of-line translation facilities in some operating
1377** systems.
1378**
1379** This is like output_quoted_string() but with the addition of the \r\n
1380** escape mechanism.
1381*/
1382static void output_quoted_escaped_string(FILE *out, const char *z){
1383 int i;
1384 char c;
1385 setBinaryMode(out, 1);
1386 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1387 if( c==0 ){
1388 utf8_printf(out,"'%s'",z);
1389 }else{
1390 const char *zNL = 0;
1391 const char *zCR = 0;
1392 int nNL = 0;
1393 int nCR = 0;
1394 char zBuf1[20], zBuf2[20];
1395 for(i=0; z[i]; i++){
1396 if( z[i]=='\n' ) nNL++;
1397 if( z[i]=='\r' ) nCR++;
1398 }
1399 if( nNL ){
1400 raw_printf(out, "replace(");
1401 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1402 }
1403 if( nCR ){
1404 raw_printf(out, "replace(");
1405 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1406 }
1407 raw_printf(out, "'");
1408 while( *z ){
1409 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1410 if( c=='\'' ) i++;
1411 if( i ){
1412 utf8_printf(out, "%.*s", i, z);
1413 z += i;
1414 }
1415 if( c=='\'' ){
1416 raw_printf(out, "'");
1417 continue;
1418 }
1419 if( c==0 ){
1420 break;
1421 }
1422 z++;
1423 if( c=='\n' ){
1424 raw_printf(out, "%s", zNL);
1425 continue;
1426 }
1427 raw_printf(out, "%s", zCR);
1428 }
1429 raw_printf(out, "'");
1430 if( nCR ){
1431 raw_printf(out, ",'%s',char(13))", zCR);
1432 }
1433 if( nNL ){
1434 raw_printf(out, ",'%s',char(10))", zNL);
1435 }
1436 }
1437 setTextMode(out, 1);
1438}
1439
1440/*
1441** Output the given string as a quoted according to C or TCL quoting rules.
1442*/
1443static void output_c_string(FILE *out, const char *z){
1444 unsigned int c;
1445 fputc('"', out);
1446 while( (c = *(z++))!=0 ){
1447 if( c=='\\' ){
1448 fputc(c, out);
1449 fputc(c, out);
1450 }else if( c=='"' ){
1451 fputc('\\', out);
1452 fputc('"', out);
1453 }else if( c=='\t' ){
1454 fputc('\\', out);
1455 fputc('t', out);
1456 }else if( c=='\n' ){
1457 fputc('\\', out);
1458 fputc('n', out);
1459 }else if( c=='\r' ){
1460 fputc('\\', out);
1461 fputc('r', out);
1462 }else if( !isprint(c&0xff) ){
1463 raw_printf(out, "\\%03o", c&0xff);
1464 }else{
1465 fputc(c, out);
1466 }
1467 }
1468 fputc('"', out);
1469}
1470
1471/*
1472** Output the given string with characters that are special to
1473** HTML escaped.
1474*/
1475static void output_html_string(FILE *out, const char *z){
1476 int i;
1477 if( z==0 ) z = "";
1478 while( *z ){
1479 for(i=0; z[i]
1480 && z[i]!='<'
1481 && z[i]!='&'
1482 && z[i]!='>'
1483 && z[i]!='\"'
1484 && z[i]!='\'';
1485 i++){}
1486 if( i>0 ){
1487 utf8_printf(out,"%.*s",i,z);
1488 }
1489 if( z[i]=='<' ){
1490 raw_printf(out,"&lt;");
1491 }else if( z[i]=='&' ){
1492 raw_printf(out,"&amp;");
1493 }else if( z[i]=='>' ){
1494 raw_printf(out,"&gt;");
1495 }else if( z[i]=='\"' ){
1496 raw_printf(out,"&quot;");
1497 }else if( z[i]=='\'' ){
1498 raw_printf(out,"&#39;");
1499 }else{
1500 break;
1501 }
1502 z += i + 1;
1503 }
1504}
1505
1506/*
1507** If a field contains any character identified by a 1 in the following
1508** array, then the string must be quoted for CSV.
1509*/
1510static const char needCsvQuote[] = {
1511 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1512 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1513 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1514 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1515 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1516 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1517 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1518 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1519 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1520 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1521 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1522 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1523 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1525 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1526 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1527};
1528
1529/*
1530** Output a single term of CSV. Actually, p->colSeparator is used for
1531** the separator, which may or may not be a comma. p->nullValue is
1532** the null value. Strings are quoted if necessary. The separator
1533** is only issued if bSep is true.
1534*/
1535static void output_csv(ShellState *p, const char *z, int bSep){
1536 FILE *out = p->out;
1537 if( z==0 ){
1538 utf8_printf(out,"%s",p->nullValue);
1539 }else{
1540 int i;
1541 int nSep = strlen30(p->colSeparator);
1542 for(i=0; z[i]; i++){
1543 if( needCsvQuote[((unsigned char*)z)[i]]
1544 || (z[i]==p->colSeparator[0] &&
1545 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1546 i = 0;
1547 break;
1548 }
1549 }
1550 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001551 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1552 utf8_printf(out, "%s", zQuoted);
1553 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001554 }else{
1555 utf8_printf(out, "%s", z);
1556 }
1557 }
1558 if( bSep ){
1559 utf8_printf(p->out, "%s", p->colSeparator);
1560 }
1561}
1562
drh2ce15c32017-07-11 13:34:40 +00001563/*
1564** This routine runs when the user presses Ctrl-C
1565*/
1566static void interrupt_handler(int NotUsed){
1567 UNUSED_PARAMETER(NotUsed);
1568 seenInterrupt++;
1569 if( seenInterrupt>2 ) exit(1);
1570 if( globalDb ) sqlite3_interrupt(globalDb);
1571}
mistachkinb4bab902017-10-27 17:09:44 +00001572
1573#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1574/*
1575** This routine runs for console events (e.g. Ctrl-C) on Win32
1576*/
1577static BOOL WINAPI ConsoleCtrlHandler(
1578 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1579){
1580 if( dwCtrlType==CTRL_C_EVENT ){
1581 interrupt_handler(0);
1582 return TRUE;
1583 }
1584 return FALSE;
1585}
drh2ce15c32017-07-11 13:34:40 +00001586#endif
1587
1588#ifndef SQLITE_OMIT_AUTHORIZATION
1589/*
1590** When the ".auth ON" is set, the following authorizer callback is
1591** invoked. It always returns SQLITE_OK.
1592*/
1593static int shellAuth(
1594 void *pClientData,
1595 int op,
1596 const char *zA1,
1597 const char *zA2,
1598 const char *zA3,
1599 const char *zA4
1600){
1601 ShellState *p = (ShellState*)pClientData;
1602 static const char *azAction[] = { 0,
1603 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1604 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1605 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1606 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1607 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1608 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1609 "PRAGMA", "READ", "SELECT",
1610 "TRANSACTION", "UPDATE", "ATTACH",
1611 "DETACH", "ALTER_TABLE", "REINDEX",
1612 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1613 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1614 };
1615 int i;
1616 const char *az[4];
1617 az[0] = zA1;
1618 az[1] = zA2;
1619 az[2] = zA3;
1620 az[3] = zA4;
1621 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1622 for(i=0; i<4; i++){
1623 raw_printf(p->out, " ");
1624 if( az[i] ){
1625 output_c_string(p->out, az[i]);
1626 }else{
1627 raw_printf(p->out, "NULL");
1628 }
1629 }
1630 raw_printf(p->out, "\n");
1631 return SQLITE_OK;
1632}
1633#endif
1634
1635/*
1636** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1637**
1638** This routine converts some CREATE TABLE statements for shadow tables
1639** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1640*/
1641static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1642 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1643 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1644 }else{
1645 utf8_printf(out, "%s%s", z, zTail);
1646 }
1647}
1648static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1649 char c = z[n];
1650 z[n] = 0;
1651 printSchemaLine(out, z, zTail);
1652 z[n] = c;
1653}
1654
1655/*
drh11be81d2018-01-06 15:46:20 +00001656** Return true if string z[] has nothing but whitespace and comments to the
1657** end of the first line.
1658*/
1659static int wsToEol(const char *z){
1660 int i;
1661 for(i=0; z[i]; i++){
1662 if( z[i]=='\n' ) return 1;
1663 if( IsSpace(z[i]) ) continue;
1664 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1665 return 0;
1666 }
1667 return 1;
1668}
1669
1670
1671/*
drh2ce15c32017-07-11 13:34:40 +00001672** This is the callback routine that the shell
1673** invokes for each row of a query result.
1674*/
1675static int shell_callback(
1676 void *pArg,
1677 int nArg, /* Number of result columns */
1678 char **azArg, /* Text of each result column */
1679 char **azCol, /* Column names */
1680 int *aiType /* Column types */
1681){
1682 int i;
1683 ShellState *p = (ShellState*)pArg;
1684
drhb3c45232017-08-28 14:33:27 +00001685 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001686 switch( p->cMode ){
1687 case MODE_Line: {
1688 int w = 5;
1689 if( azArg==0 ) break;
1690 for(i=0; i<nArg; i++){
1691 int len = strlen30(azCol[i] ? azCol[i] : "");
1692 if( len>w ) w = len;
1693 }
1694 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1695 for(i=0; i<nArg; i++){
1696 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1697 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1698 }
1699 break;
1700 }
1701 case MODE_Explain:
1702 case MODE_Column: {
1703 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1704 const int *colWidth;
1705 int showHdr;
1706 char *rowSep;
1707 if( p->cMode==MODE_Column ){
1708 colWidth = p->colWidth;
1709 showHdr = p->showHeader;
1710 rowSep = p->rowSeparator;
1711 }else{
1712 colWidth = aExplainWidths;
1713 showHdr = 1;
1714 rowSep = SEP_Row;
1715 }
1716 if( p->cnt++==0 ){
1717 for(i=0; i<nArg; i++){
1718 int w, n;
1719 if( i<ArraySize(p->colWidth) ){
1720 w = colWidth[i];
1721 }else{
1722 w = 0;
1723 }
1724 if( w==0 ){
1725 w = strlenChar(azCol[i] ? azCol[i] : "");
1726 if( w<10 ) w = 10;
1727 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1728 if( w<n ) w = n;
1729 }
1730 if( i<ArraySize(p->actualWidth) ){
1731 p->actualWidth[i] = w;
1732 }
1733 if( showHdr ){
1734 utf8_width_print(p->out, w, azCol[i]);
1735 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1736 }
1737 }
1738 if( showHdr ){
1739 for(i=0; i<nArg; i++){
1740 int w;
1741 if( i<ArraySize(p->actualWidth) ){
1742 w = p->actualWidth[i];
1743 if( w<0 ) w = -w;
1744 }else{
1745 w = 10;
1746 }
1747 utf8_printf(p->out,"%-*.*s%s",w,w,
1748 "----------------------------------------------------------"
1749 "----------------------------------------------------------",
1750 i==nArg-1 ? rowSep : " ");
1751 }
1752 }
1753 }
1754 if( azArg==0 ) break;
1755 for(i=0; i<nArg; i++){
1756 int w;
1757 if( i<ArraySize(p->actualWidth) ){
1758 w = p->actualWidth[i];
1759 }else{
1760 w = 10;
1761 }
1762 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1763 w = strlenChar(azArg[i]);
1764 }
1765 if( i==1 && p->aiIndent && p->pStmt ){
1766 if( p->iIndent<p->nIndent ){
1767 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1768 }
1769 p->iIndent++;
1770 }
1771 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1772 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1773 }
1774 break;
1775 }
1776 case MODE_Semi: { /* .schema and .fullschema output */
1777 printSchemaLine(p->out, azArg[0], ";\n");
1778 break;
1779 }
1780 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1781 char *z;
1782 int j;
1783 int nParen = 0;
1784 char cEnd = 0;
1785 char c;
1786 int nLine = 0;
1787 assert( nArg==1 );
1788 if( azArg[0]==0 ) break;
1789 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1790 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1791 ){
1792 utf8_printf(p->out, "%s;\n", azArg[0]);
1793 break;
1794 }
1795 z = sqlite3_mprintf("%s", azArg[0]);
1796 j = 0;
1797 for(i=0; IsSpace(z[i]); i++){}
1798 for(; (c = z[i])!=0; i++){
1799 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001800 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001801 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1802 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1803 j--;
1804 }
1805 z[j++] = c;
1806 }
1807 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1808 z[j] = 0;
1809 if( strlen30(z)>=79 ){
drh11be81d2018-01-06 15:46:20 +00001810 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001811 if( c==cEnd ){
1812 cEnd = 0;
1813 }else if( c=='"' || c=='\'' || c=='`' ){
1814 cEnd = c;
1815 }else if( c=='[' ){
1816 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001817 }else if( c=='-' && z[i+1]=='-' ){
1818 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001819 }else if( c=='(' ){
1820 nParen++;
1821 }else if( c==')' ){
1822 nParen--;
1823 if( nLine>0 && nParen==0 && j>0 ){
1824 printSchemaLineN(p->out, z, j, "\n");
1825 j = 0;
1826 }
1827 }
1828 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001829 if( nParen==1 && cEnd==0
1830 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1831 ){
drh2ce15c32017-07-11 13:34:40 +00001832 if( c=='\n' ) j--;
1833 printSchemaLineN(p->out, z, j, "\n ");
1834 j = 0;
1835 nLine++;
1836 while( IsSpace(z[i+1]) ){ i++; }
1837 }
1838 }
1839 z[j] = 0;
1840 }
1841 printSchemaLine(p->out, z, ";\n");
1842 sqlite3_free(z);
1843 break;
1844 }
1845 case MODE_List: {
1846 if( p->cnt++==0 && p->showHeader ){
1847 for(i=0; i<nArg; i++){
1848 utf8_printf(p->out,"%s%s",azCol[i],
1849 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1850 }
1851 }
1852 if( azArg==0 ) break;
1853 for(i=0; i<nArg; i++){
1854 char *z = azArg[i];
1855 if( z==0 ) z = p->nullValue;
1856 utf8_printf(p->out, "%s", z);
1857 if( i<nArg-1 ){
1858 utf8_printf(p->out, "%s", p->colSeparator);
1859 }else{
1860 utf8_printf(p->out, "%s", p->rowSeparator);
1861 }
1862 }
1863 break;
1864 }
1865 case MODE_Html: {
1866 if( p->cnt++==0 && p->showHeader ){
1867 raw_printf(p->out,"<TR>");
1868 for(i=0; i<nArg; i++){
1869 raw_printf(p->out,"<TH>");
1870 output_html_string(p->out, azCol[i]);
1871 raw_printf(p->out,"</TH>\n");
1872 }
1873 raw_printf(p->out,"</TR>\n");
1874 }
1875 if( azArg==0 ) break;
1876 raw_printf(p->out,"<TR>");
1877 for(i=0; i<nArg; i++){
1878 raw_printf(p->out,"<TD>");
1879 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1880 raw_printf(p->out,"</TD>\n");
1881 }
1882 raw_printf(p->out,"</TR>\n");
1883 break;
1884 }
1885 case MODE_Tcl: {
1886 if( p->cnt++==0 && p->showHeader ){
1887 for(i=0; i<nArg; i++){
1888 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1889 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1890 }
1891 utf8_printf(p->out, "%s", p->rowSeparator);
1892 }
1893 if( azArg==0 ) break;
1894 for(i=0; i<nArg; i++){
1895 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1896 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1897 }
1898 utf8_printf(p->out, "%s", p->rowSeparator);
1899 break;
1900 }
1901 case MODE_Csv: {
1902 setBinaryMode(p->out, 1);
1903 if( p->cnt++==0 && p->showHeader ){
1904 for(i=0; i<nArg; i++){
1905 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1906 }
1907 utf8_printf(p->out, "%s", p->rowSeparator);
1908 }
1909 if( nArg>0 ){
1910 for(i=0; i<nArg; i++){
1911 output_csv(p, azArg[i], i<nArg-1);
1912 }
1913 utf8_printf(p->out, "%s", p->rowSeparator);
1914 }
1915 setTextMode(p->out, 1);
1916 break;
1917 }
1918 case MODE_Insert: {
1919 if( azArg==0 ) break;
1920 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
1921 if( p->showHeader ){
1922 raw_printf(p->out,"(");
1923 for(i=0; i<nArg; i++){
1924 if( i>0 ) raw_printf(p->out, ",");
1925 if( quoteChar(azCol[i]) ){
1926 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
1927 utf8_printf(p->out, "%s", z);
1928 sqlite3_free(z);
1929 }else{
1930 raw_printf(p->out, "%s", azCol[i]);
1931 }
1932 }
1933 raw_printf(p->out,")");
1934 }
1935 p->cnt++;
1936 for(i=0; i<nArg; i++){
1937 raw_printf(p->out, i>0 ? "," : " VALUES(");
1938 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1939 utf8_printf(p->out,"NULL");
1940 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1941 if( ShellHasFlag(p, SHFLG_Newlines) ){
1942 output_quoted_string(p->out, azArg[i]);
1943 }else{
1944 output_quoted_escaped_string(p->out, azArg[i]);
1945 }
1946 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1947 utf8_printf(p->out,"%s", azArg[i]);
1948 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1949 char z[50];
1950 double r = sqlite3_column_double(p->pStmt, i);
1951 sqlite3_snprintf(50,z,"%!.20g", r);
1952 raw_printf(p->out, "%s", z);
1953 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1954 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1955 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1956 output_hex_blob(p->out, pBlob, nBlob);
1957 }else if( isNumber(azArg[i], 0) ){
1958 utf8_printf(p->out,"%s", azArg[i]);
1959 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
1960 output_quoted_string(p->out, azArg[i]);
1961 }else{
1962 output_quoted_escaped_string(p->out, azArg[i]);
1963 }
1964 }
1965 raw_printf(p->out,");\n");
1966 break;
1967 }
1968 case MODE_Quote: {
1969 if( azArg==0 ) break;
1970 if( p->cnt==0 && p->showHeader ){
1971 for(i=0; i<nArg; i++){
1972 if( i>0 ) raw_printf(p->out, ",");
1973 output_quoted_string(p->out, azCol[i]);
1974 }
1975 raw_printf(p->out,"\n");
1976 }
1977 p->cnt++;
1978 for(i=0; i<nArg; i++){
1979 if( i>0 ) raw_printf(p->out, ",");
1980 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1981 utf8_printf(p->out,"NULL");
1982 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1983 output_quoted_string(p->out, azArg[i]);
1984 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1985 utf8_printf(p->out,"%s", azArg[i]);
1986 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1987 char z[50];
1988 double r = sqlite3_column_double(p->pStmt, i);
1989 sqlite3_snprintf(50,z,"%!.20g", r);
1990 raw_printf(p->out, "%s", z);
1991 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1992 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1993 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1994 output_hex_blob(p->out, pBlob, nBlob);
1995 }else if( isNumber(azArg[i], 0) ){
1996 utf8_printf(p->out,"%s", azArg[i]);
1997 }else{
1998 output_quoted_string(p->out, azArg[i]);
1999 }
2000 }
2001 raw_printf(p->out,"\n");
2002 break;
2003 }
2004 case MODE_Ascii: {
2005 if( p->cnt++==0 && p->showHeader ){
2006 for(i=0; i<nArg; i++){
2007 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2008 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2009 }
2010 utf8_printf(p->out, "%s", p->rowSeparator);
2011 }
2012 if( azArg==0 ) break;
2013 for(i=0; i<nArg; i++){
2014 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2015 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2016 }
2017 utf8_printf(p->out, "%s", p->rowSeparator);
2018 break;
2019 }
2020 }
2021 return 0;
2022}
2023
2024/*
2025** This is the callback routine that the SQLite library
2026** invokes for each row of a query result.
2027*/
2028static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2029 /* since we don't have type info, call the shell_callback with a NULL value */
2030 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2031}
2032
2033/*
2034** This is the callback routine from sqlite3_exec() that appends all
2035** output onto the end of a ShellText object.
2036*/
2037static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2038 ShellText *p = (ShellText*)pArg;
2039 int i;
2040 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00002041 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002042 if( p->n ) appendText(p, "|", 0);
2043 for(i=0; i<nArg; i++){
2044 if( i ) appendText(p, ",", 0);
2045 if( azArg[i] ) appendText(p, azArg[i], 0);
2046 }
2047 return 0;
2048}
2049
2050/*
2051** Generate an appropriate SELFTEST table in the main database.
2052*/
2053static void createSelftestTable(ShellState *p){
2054 char *zErrMsg = 0;
2055 sqlite3_exec(p->db,
2056 "SAVEPOINT selftest_init;\n"
2057 "CREATE TABLE IF NOT EXISTS selftest(\n"
2058 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2059 " op TEXT,\n" /* Operator: memo run */
2060 " cmd TEXT,\n" /* Command text */
2061 " ans TEXT\n" /* Desired answer */
2062 ");"
2063 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2064 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2065 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2066 " 'memo','Tests generated by --init');\n"
2067 "INSERT INTO [_shell$self]\n"
2068 " SELECT 'run',\n"
2069 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2070 "FROM sqlite_master ORDER BY 2'',224))',\n"
2071 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2072 "FROM sqlite_master ORDER BY 2',224));\n"
2073 "INSERT INTO [_shell$self]\n"
2074 " SELECT 'run',"
2075 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2076 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2077 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2078 " FROM (\n"
2079 " SELECT name FROM sqlite_master\n"
2080 " WHERE type='table'\n"
2081 " AND name<>'selftest'\n"
2082 " AND coalesce(rootpage,0)>0\n"
2083 " )\n"
2084 " ORDER BY name;\n"
2085 "INSERT INTO [_shell$self]\n"
2086 " VALUES('run','PRAGMA integrity_check','ok');\n"
2087 "INSERT INTO selftest(tno,op,cmd,ans)"
2088 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2089 "DROP TABLE [_shell$self];"
2090 ,0,0,&zErrMsg);
2091 if( zErrMsg ){
2092 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2093 sqlite3_free(zErrMsg);
2094 }
2095 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2096}
2097
2098
2099/*
2100** Set the destination table field of the ShellState structure to
2101** the name of the table given. Escape any quote characters in the
2102** table name.
2103*/
2104static void set_table_name(ShellState *p, const char *zName){
2105 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00002106 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00002107 char *z;
2108
2109 if( p->zDestTable ){
2110 free(p->zDestTable);
2111 p->zDestTable = 0;
2112 }
2113 if( zName==0 ) return;
2114 cQuote = quoteChar(zName);
2115 n = strlen30(zName);
2116 if( cQuote ) n += n+2;
2117 z = p->zDestTable = malloc( n+1 );
2118 if( z==0 ){
2119 raw_printf(stderr,"Error: out of memory\n");
2120 exit(1);
2121 }
2122 n = 0;
2123 if( cQuote ) z[n++] = cQuote;
2124 for(i=0; zName[i]; i++){
2125 z[n++] = zName[i];
2126 if( zName[i]==cQuote ) z[n++] = cQuote;
2127 }
2128 if( cQuote ) z[n++] = cQuote;
2129 z[n] = 0;
2130}
2131
2132
2133/*
2134** Execute a query statement that will generate SQL output. Print
2135** the result columns, comma-separated, on a line and then add a
2136** semicolon terminator to the end of that line.
2137**
2138** If the number of columns is 1 and that column contains text "--"
2139** then write the semicolon on a separate line. That way, if a
2140** "--" comment occurs at the end of the statement, the comment
2141** won't consume the semicolon terminator.
2142*/
2143static int run_table_dump_query(
2144 ShellState *p, /* Query context */
2145 const char *zSelect, /* SELECT statement to extract content */
2146 const char *zFirstRow /* Print before first row, if not NULL */
2147){
2148 sqlite3_stmt *pSelect;
2149 int rc;
2150 int nResult;
2151 int i;
2152 const char *z;
2153 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2154 if( rc!=SQLITE_OK || !pSelect ){
2155 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2156 sqlite3_errmsg(p->db));
2157 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2158 return rc;
2159 }
2160 rc = sqlite3_step(pSelect);
2161 nResult = sqlite3_column_count(pSelect);
2162 while( rc==SQLITE_ROW ){
2163 if( zFirstRow ){
2164 utf8_printf(p->out, "%s", zFirstRow);
2165 zFirstRow = 0;
2166 }
2167 z = (const char*)sqlite3_column_text(pSelect, 0);
2168 utf8_printf(p->out, "%s", z);
2169 for(i=1; i<nResult; i++){
2170 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2171 }
2172 if( z==0 ) z = "";
2173 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2174 if( z[0] ){
2175 raw_printf(p->out, "\n;\n");
2176 }else{
2177 raw_printf(p->out, ";\n");
2178 }
2179 rc = sqlite3_step(pSelect);
2180 }
2181 rc = sqlite3_finalize(pSelect);
2182 if( rc!=SQLITE_OK ){
2183 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2184 sqlite3_errmsg(p->db));
2185 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2186 }
2187 return rc;
2188}
2189
2190/*
2191** Allocate space and save off current error string.
2192*/
2193static char *save_err_msg(
2194 sqlite3 *db /* Database to query */
2195){
2196 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2197 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2198 if( zErrMsg ){
2199 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2200 }
2201 return zErrMsg;
2202}
2203
2204#ifdef __linux__
2205/*
2206** Attempt to display I/O stats on Linux using /proc/PID/io
2207*/
2208static void displayLinuxIoStats(FILE *out){
2209 FILE *in;
2210 char z[200];
2211 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2212 in = fopen(z, "rb");
2213 if( in==0 ) return;
2214 while( fgets(z, sizeof(z), in)!=0 ){
2215 static const struct {
2216 const char *zPattern;
2217 const char *zDesc;
2218 } aTrans[] = {
2219 { "rchar: ", "Bytes received by read():" },
2220 { "wchar: ", "Bytes sent to write():" },
2221 { "syscr: ", "Read() system calls:" },
2222 { "syscw: ", "Write() system calls:" },
2223 { "read_bytes: ", "Bytes read from storage:" },
2224 { "write_bytes: ", "Bytes written to storage:" },
2225 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2226 };
2227 int i;
2228 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00002229 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00002230 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2231 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2232 break;
2233 }
2234 }
2235 }
2236 fclose(in);
2237}
2238#endif
2239
2240/*
2241** Display a single line of status using 64-bit values.
2242*/
2243static void displayStatLine(
2244 ShellState *p, /* The shell context */
2245 char *zLabel, /* Label for this one line */
2246 char *zFormat, /* Format for the result */
2247 int iStatusCtrl, /* Which status to display */
2248 int bReset /* True to reset the stats */
2249){
2250 sqlite3_int64 iCur = -1;
2251 sqlite3_int64 iHiwtr = -1;
2252 int i, nPercent;
2253 char zLine[200];
2254 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2255 for(i=0, nPercent=0; zFormat[i]; i++){
2256 if( zFormat[i]=='%' ) nPercent++;
2257 }
2258 if( nPercent>1 ){
2259 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2260 }else{
2261 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2262 }
2263 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2264}
2265
2266/*
2267** Display memory stats.
2268*/
2269static int display_stats(
2270 sqlite3 *db, /* Database to query */
2271 ShellState *pArg, /* Pointer to ShellState */
2272 int bReset /* True to reset the stats */
2273){
2274 int iCur;
2275 int iHiwtr;
drh393344f2018-03-09 16:37:05 +00002276 FILE *out;
2277 if( pArg==0 || pArg->out==0 ) return 0;
2278 out = pArg->out;
drh2ce15c32017-07-11 13:34:40 +00002279
drh393344f2018-03-09 16:37:05 +00002280 if( pArg->pStmt && (pArg->statsOn & 2) ){
2281 int nCol, i, x;
2282 sqlite3_stmt *pStmt = pArg->pStmt;
2283 char z[100];
2284 nCol = sqlite3_column_count(pStmt);
2285 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2286 for(i=0; i<nCol; i++){
2287 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2288 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
2289 sqlite3_snprintf(30, z+x, "declared type:");
2290 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
2291 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2292 sqlite3_snprintf(30, z+x, "database name:");
2293 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2294 sqlite3_snprintf(30, z+x, "table name:");
2295 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2296 sqlite3_snprintf(30, z+x, "origin name:");
2297 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
2298 #endif
drh2ce15c32017-07-11 13:34:40 +00002299 }
drh393344f2018-03-09 16:37:05 +00002300 }
drh2ce15c32017-07-11 13:34:40 +00002301
drh393344f2018-03-09 16:37:05 +00002302 displayStatLine(pArg, "Memory Used:",
2303 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2304 displayStatLine(pArg, "Number of Outstanding Allocations:",
2305 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2306 if( pArg->shellFlgs & SHFLG_Pagecache ){
2307 displayStatLine(pArg, "Number of Pcache Pages Used:",
2308 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2309 }
2310 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2311 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2312 displayStatLine(pArg, "Largest Allocation:",
2313 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2314 displayStatLine(pArg, "Largest Pcache Allocation:",
2315 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2316#ifdef YYTRACKMAXSTACKDEPTH
2317 displayStatLine(pArg, "Deepest Parser Stack:",
2318 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2319#endif
2320
2321 if( db ){
drh2ce15c32017-07-11 13:34:40 +00002322 if( pArg->shellFlgs & SHFLG_Lookaside ){
2323 iHiwtr = iCur = -1;
2324 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2325 &iCur, &iHiwtr, bReset);
2326 raw_printf(pArg->out,
2327 "Lookaside Slots Used: %d (max %d)\n",
2328 iCur, iHiwtr);
2329 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2330 &iCur, &iHiwtr, bReset);
2331 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2332 iHiwtr);
2333 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2334 &iCur, &iHiwtr, bReset);
2335 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2336 iHiwtr);
2337 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2338 &iCur, &iHiwtr, bReset);
2339 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2340 iHiwtr);
2341 }
2342 iHiwtr = iCur = -1;
2343 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2344 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2345 iCur);
2346 iHiwtr = iCur = -1;
2347 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2348 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2349 iHiwtr = iCur = -1;
2350 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2351 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2352 iHiwtr = iCur = -1;
2353 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2354 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2355 iHiwtr = iCur = -1;
drhffc78a42018-03-14 14:53:50 +00002356 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2357 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2358 iHiwtr = iCur = -1;
drh2ce15c32017-07-11 13:34:40 +00002359 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2360 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2361 iCur);
2362 iHiwtr = iCur = -1;
2363 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2364 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2365 iCur);
2366 }
2367
drh393344f2018-03-09 16:37:05 +00002368 if( pArg->pStmt ){
drh2ce15c32017-07-11 13:34:40 +00002369 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2370 bReset);
2371 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2372 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2373 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2374 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2375 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2376 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2377 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
drh393344f2018-03-09 16:37:05 +00002378 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
2379 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2380 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2381 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2382 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2383 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
drh2ce15c32017-07-11 13:34:40 +00002384 }
2385
2386#ifdef __linux__
2387 displayLinuxIoStats(pArg->out);
2388#endif
2389
2390 /* Do not remove this machine readable comment: extra-stats-output-here */
2391
2392 return 0;
2393}
2394
2395/*
2396** Display scan stats.
2397*/
2398static void display_scanstats(
2399 sqlite3 *db, /* Database to query */
2400 ShellState *pArg /* Pointer to ShellState */
2401){
2402#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2403 UNUSED_PARAMETER(db);
2404 UNUSED_PARAMETER(pArg);
2405#else
2406 int i, k, n, mx;
2407 raw_printf(pArg->out, "-------- scanstats --------\n");
2408 mx = 0;
2409 for(k=0; k<=mx; k++){
2410 double rEstLoop = 1.0;
2411 for(i=n=0; 1; i++){
2412 sqlite3_stmt *p = pArg->pStmt;
2413 sqlite3_int64 nLoop, nVisit;
2414 double rEst;
2415 int iSid;
2416 const char *zExplain;
2417 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2418 break;
2419 }
2420 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2421 if( iSid>mx ) mx = iSid;
2422 if( iSid!=k ) continue;
2423 if( n==0 ){
2424 rEstLoop = (double)nLoop;
2425 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2426 }
2427 n++;
2428 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2429 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2430 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2431 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2432 rEstLoop *= rEst;
2433 raw_printf(pArg->out,
2434 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2435 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2436 );
2437 }
2438 }
2439 raw_printf(pArg->out, "---------------------------\n");
2440#endif
2441}
2442
2443/*
2444** Parameter azArray points to a zero-terminated array of strings. zStr
2445** points to a single nul-terminated string. Return non-zero if zStr
2446** is equal, according to strcmp(), to any of the strings in the array.
2447** Otherwise, return zero.
2448*/
2449static int str_in_array(const char *zStr, const char **azArray){
2450 int i;
2451 for(i=0; azArray[i]; i++){
2452 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2453 }
2454 return 0;
2455}
2456
2457/*
2458** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2459** and populate the ShellState.aiIndent[] array with the number of
2460** spaces each opcode should be indented before it is output.
2461**
2462** The indenting rules are:
2463**
2464** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2465** all opcodes that occur between the p2 jump destination and the opcode
2466** itself by 2 spaces.
2467**
2468** * For each "Goto", if the jump destination is earlier in the program
2469** and ends on one of:
2470** Yield SeekGt SeekLt RowSetRead Rewind
2471** or if the P1 parameter is one instead of zero,
2472** then indent all opcodes between the earlier instruction
2473** and "Goto" by 2 spaces.
2474*/
2475static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2476 const char *zSql; /* The text of the SQL statement */
2477 const char *z; /* Used to check if this is an EXPLAIN */
2478 int *abYield = 0; /* True if op is an OP_Yield */
2479 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2480 int iOp; /* Index of operation in p->aiIndent[] */
2481
2482 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2483 "NextIfOpen", "PrevIfOpen", 0 };
2484 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2485 "Rewind", 0 };
2486 const char *azGoto[] = { "Goto", 0 };
2487
2488 /* Try to figure out if this is really an EXPLAIN statement. If this
2489 ** cannot be verified, return early. */
2490 if( sqlite3_column_count(pSql)!=8 ){
2491 p->cMode = p->mode;
2492 return;
2493 }
2494 zSql = sqlite3_sql(pSql);
2495 if( zSql==0 ) return;
2496 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2497 if( sqlite3_strnicmp(z, "explain", 7) ){
2498 p->cMode = p->mode;
2499 return;
2500 }
2501
2502 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2503 int i;
2504 int iAddr = sqlite3_column_int(pSql, 0);
2505 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2506
2507 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2508 ** p2 is an instruction address, set variable p2op to the index of that
2509 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2510 ** the current instruction is part of a sub-program generated by an
2511 ** SQL trigger or foreign key. */
2512 int p2 = sqlite3_column_int(pSql, 3);
2513 int p2op = (p2 + (iOp-iAddr));
2514
2515 /* Grow the p->aiIndent array as required */
2516 if( iOp>=nAlloc ){
2517 if( iOp==0 ){
2518 /* Do further verfication that this is explain output. Abort if
2519 ** it is not */
2520 static const char *explainCols[] = {
2521 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2522 int jj;
2523 for(jj=0; jj<ArraySize(explainCols); jj++){
2524 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2525 p->cMode = p->mode;
2526 sqlite3_reset(pSql);
2527 return;
2528 }
2529 }
2530 }
2531 nAlloc += 100;
2532 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2533 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2534 }
2535 abYield[iOp] = str_in_array(zOp, azYield);
2536 p->aiIndent[iOp] = 0;
2537 p->nIndent = iOp+1;
2538
2539 if( str_in_array(zOp, azNext) ){
2540 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2541 }
2542 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2543 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2544 ){
2545 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2546 }
2547 }
2548
2549 p->iIndent = 0;
2550 sqlite3_free(abYield);
2551 sqlite3_reset(pSql);
2552}
2553
2554/*
2555** Free the array allocated by explain_data_prepare().
2556*/
2557static void explain_data_delete(ShellState *p){
2558 sqlite3_free(p->aiIndent);
2559 p->aiIndent = 0;
2560 p->nIndent = 0;
2561 p->iIndent = 0;
2562}
2563
2564/*
2565** Disable and restore .wheretrace and .selecttrace settings.
2566*/
2567#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2568extern int sqlite3SelectTrace;
2569static int savedSelectTrace;
2570#endif
2571#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2572extern int sqlite3WhereTrace;
2573static int savedWhereTrace;
2574#endif
2575static void disable_debug_trace_modes(void){
2576#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2577 savedSelectTrace = sqlite3SelectTrace;
2578 sqlite3SelectTrace = 0;
2579#endif
2580#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2581 savedWhereTrace = sqlite3WhereTrace;
2582 sqlite3WhereTrace = 0;
2583#endif
2584}
2585static void restore_debug_trace_modes(void){
2586#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2587 sqlite3SelectTrace = savedSelectTrace;
2588#endif
2589#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2590 sqlite3WhereTrace = savedWhereTrace;
2591#endif
2592}
2593
2594/*
2595** Run a prepared statement
2596*/
2597static void exec_prepared_stmt(
2598 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002599 sqlite3_stmt *pStmt /* Statment to run */
drh2ce15c32017-07-11 13:34:40 +00002600){
2601 int rc;
2602
2603 /* perform the first step. this will tell us if we
2604 ** have a result set or not and how wide it is.
2605 */
2606 rc = sqlite3_step(pStmt);
2607 /* if we have a result set... */
2608 if( SQLITE_ROW == rc ){
drha10b9992018-03-09 15:24:33 +00002609 /* allocate space for col name ptr, value ptr, and type */
2610 int nCol = sqlite3_column_count(pStmt);
2611 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2612 if( !pData ){
2613 rc = SQLITE_NOMEM;
drh2ce15c32017-07-11 13:34:40 +00002614 }else{
drha10b9992018-03-09 15:24:33 +00002615 char **azCols = (char **)pData; /* Names of result columns */
2616 char **azVals = &azCols[nCol]; /* Results */
2617 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2618 int i, x;
2619 assert(sizeof(int) <= sizeof(char *));
2620 /* save off ptrs to column names */
2621 for(i=0; i<nCol; i++){
2622 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2623 }
drh2ce15c32017-07-11 13:34:40 +00002624 do{
drha10b9992018-03-09 15:24:33 +00002625 /* extract the data and data types */
2626 for(i=0; i<nCol; i++){
2627 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2628 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2629 azVals[i] = "";
2630 }else{
2631 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2632 }
2633 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2634 rc = SQLITE_NOMEM;
2635 break; /* from for */
2636 }
2637 } /* end for */
2638
2639 /* if data and types extracted successfully... */
2640 if( SQLITE_ROW == rc ){
2641 /* call the supplied callback with the result row data */
2642 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2643 rc = SQLITE_ABORT;
2644 }else{
2645 rc = sqlite3_step(pStmt);
2646 }
2647 }
2648 } while( SQLITE_ROW == rc );
2649 sqlite3_free(pData);
drh2ce15c32017-07-11 13:34:40 +00002650 }
2651 }
2652}
2653
dan6b046be2018-01-09 15:25:55 +00002654#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002655/*
dan43efc182017-12-19 17:42:13 +00002656** This function is called to process SQL if the previous shell command
2657** was ".expert". It passes the SQL in the second argument directly to
2658** the sqlite3expert object.
2659**
2660** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2661** code. In this case, (*pzErr) may be set to point to a buffer containing
2662** an English language error message. It is the responsibility of the
2663** caller to eventually free this buffer using sqlite3_free().
2664*/
2665static int expertHandleSQL(
2666 ShellState *pState,
2667 const char *zSql,
2668 char **pzErr
2669){
2670 assert( pState->expert.pExpert );
2671 assert( pzErr==0 || *pzErr==0 );
2672 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2673}
2674
2675/*
2676** This function is called either to silently clean up the object
2677** created by the ".expert" command (if bCancel==1), or to generate a
2678** report from it and then clean it up (if bCancel==0).
2679**
2680** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2681** code. In this case, (*pzErr) may be set to point to a buffer containing
2682** an English language error message. It is the responsibility of the
2683** caller to eventually free this buffer using sqlite3_free().
2684*/
2685static int expertFinish(
2686 ShellState *pState,
2687 int bCancel,
2688 char **pzErr
2689){
2690 int rc = SQLITE_OK;
2691 sqlite3expert *p = pState->expert.pExpert;
2692 assert( p );
2693 assert( bCancel || pzErr==0 || *pzErr==0 );
2694 if( bCancel==0 ){
2695 FILE *out = pState->out;
2696 int bVerbose = pState->expert.bVerbose;
2697
2698 rc = sqlite3_expert_analyze(p, pzErr);
2699 if( rc==SQLITE_OK ){
2700 int nQuery = sqlite3_expert_count(p);
2701 int i;
2702
2703 if( bVerbose ){
2704 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2705 raw_printf(out, "-- Candidates -----------------------------\n");
2706 raw_printf(out, "%s\n", zCand);
2707 }
2708 for(i=0; i<nQuery; i++){
2709 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2710 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2711 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2712 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2713 if( bVerbose ){
2714 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2715 raw_printf(out, "%s\n\n", zSql);
2716 }
2717 raw_printf(out, "%s\n", zIdx);
2718 raw_printf(out, "%s\n", zEQP);
2719 }
2720 }
2721 }
2722 sqlite3_expert_destroy(p);
2723 pState->expert.pExpert = 0;
2724 return rc;
2725}
2726
dan6b046be2018-01-09 15:25:55 +00002727/*
2728** Implementation of ".expert" dot command.
2729*/
2730static int expertDotCommand(
2731 ShellState *pState, /* Current shell tool state */
2732 char **azArg, /* Array of arguments passed to dot command */
2733 int nArg /* Number of entries in azArg[] */
2734){
2735 int rc = SQLITE_OK;
2736 char *zErr = 0;
2737 int i;
2738 int iSample = 0;
2739
2740 assert( pState->expert.pExpert==0 );
2741 memset(&pState->expert, 0, sizeof(ExpertInfo));
2742
2743 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2744 char *z = azArg[i];
2745 int n;
2746 if( z[0]=='-' && z[1]=='-' ) z++;
2747 n = strlen30(z);
2748 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2749 pState->expert.bVerbose = 1;
2750 }
2751 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2752 if( i==(nArg-1) ){
2753 raw_printf(stderr, "option requires an argument: %s\n", z);
2754 rc = SQLITE_ERROR;
2755 }else{
2756 iSample = (int)integerValue(azArg[++i]);
2757 if( iSample<0 || iSample>100 ){
2758 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2759 rc = SQLITE_ERROR;
2760 }
2761 }
2762 }
2763 else{
2764 raw_printf(stderr, "unknown option: %s\n", z);
2765 rc = SQLITE_ERROR;
2766 }
2767 }
2768
2769 if( rc==SQLITE_OK ){
2770 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2771 if( pState->expert.pExpert==0 ){
2772 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2773 rc = SQLITE_ERROR;
2774 }else{
2775 sqlite3_expert_config(
2776 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2777 );
2778 }
2779 }
2780
2781 return rc;
2782}
2783#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00002784
2785/*
drh2ce15c32017-07-11 13:34:40 +00002786** Execute a statement or set of statements. Print
2787** any result rows/columns depending on the current mode
2788** set via the supplied callback.
2789**
2790** This is very similar to SQLite's built-in sqlite3_exec()
2791** function except it takes a slightly different callback
2792** and callback data argument.
2793*/
2794static int shell_exec(
drh2ce15c32017-07-11 13:34:40 +00002795 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002796 const char *zSql, /* SQL to be evaluated */
drh2ce15c32017-07-11 13:34:40 +00002797 char **pzErrMsg /* Error msg written here */
2798){
2799 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2800 int rc = SQLITE_OK; /* Return Code */
2801 int rc2;
2802 const char *zLeftover; /* Tail of unprocessed SQL */
drha10b9992018-03-09 15:24:33 +00002803 sqlite3 *db = pArg->db;
drh2ce15c32017-07-11 13:34:40 +00002804
2805 if( pzErrMsg ){
2806 *pzErrMsg = NULL;
2807 }
2808
dan6b046be2018-01-09 15:25:55 +00002809#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00002810 if( pArg->expert.pExpert ){
2811 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2812 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2813 }
dan6b046be2018-01-09 15:25:55 +00002814#endif
dan43efc182017-12-19 17:42:13 +00002815
drh2ce15c32017-07-11 13:34:40 +00002816 while( zSql[0] && (SQLITE_OK == rc) ){
2817 static const char *zStmtSql;
2818 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2819 if( SQLITE_OK != rc ){
2820 if( pzErrMsg ){
2821 *pzErrMsg = save_err_msg(db);
2822 }
2823 }else{
2824 if( !pStmt ){
2825 /* this happens for a comment or white-space */
2826 zSql = zLeftover;
2827 while( IsSpace(zSql[0]) ) zSql++;
2828 continue;
2829 }
2830 zStmtSql = sqlite3_sql(pStmt);
2831 if( zStmtSql==0 ) zStmtSql = "";
2832 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2833
2834 /* save off the prepared statment handle and reset row count */
2835 if( pArg ){
2836 pArg->pStmt = pStmt;
2837 pArg->cnt = 0;
2838 }
2839
2840 /* echo the sql statement if echo on */
2841 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2842 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2843 }
2844
2845 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2846 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2847 sqlite3_stmt *pExplain;
2848 char *zEQP;
drhada70452017-12-21 21:02:27 +00002849 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00002850 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00002851 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2852 if( pArg->autoEQP>=AUTOEQP_trigger ){
2853 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2854 }
drh2ce15c32017-07-11 13:34:40 +00002855 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2856 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2857 if( rc==SQLITE_OK ){
2858 while( sqlite3_step(pExplain)==SQLITE_ROW ){
2859 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2860 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2861 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
2862 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2863 }
2864 }
2865 sqlite3_finalize(pExplain);
2866 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00002867 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00002868 /* Also do an EXPLAIN for ".eqp full" mode */
2869 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2870 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2871 if( rc==SQLITE_OK ){
2872 pArg->cMode = MODE_Explain;
2873 explain_data_prepare(pArg, pExplain);
drha10b9992018-03-09 15:24:33 +00002874 exec_prepared_stmt(pArg, pExplain);
drh2ce15c32017-07-11 13:34:40 +00002875 explain_data_delete(pArg);
2876 }
2877 sqlite3_finalize(pExplain);
2878 sqlite3_free(zEQP);
2879 }
drhada70452017-12-21 21:02:27 +00002880 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, triggerEQP, 0);
drh2ce15c32017-07-11 13:34:40 +00002881 restore_debug_trace_modes();
2882 }
2883
2884 if( pArg ){
2885 pArg->cMode = pArg->mode;
2886 if( pArg->autoExplain
2887 && sqlite3_column_count(pStmt)==8
2888 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2889 ){
2890 pArg->cMode = MODE_Explain;
2891 }
2892
2893 /* If the shell is currently in ".explain" mode, gather the extra
2894 ** data required to add indents to the output.*/
2895 if( pArg->cMode==MODE_Explain ){
2896 explain_data_prepare(pArg, pStmt);
2897 }
2898 }
2899
drha10b9992018-03-09 15:24:33 +00002900 exec_prepared_stmt(pArg, pStmt);
drh2ce15c32017-07-11 13:34:40 +00002901 explain_data_delete(pArg);
2902
2903 /* print usage stats if stats on */
2904 if( pArg && pArg->statsOn ){
2905 display_stats(db, pArg, 0);
2906 }
2907
2908 /* print loop-counters if required */
2909 if( pArg && pArg->scanstatsOn ){
2910 display_scanstats(db, pArg);
2911 }
2912
2913 /* Finalize the statement just executed. If this fails, save a
2914 ** copy of the error message. Otherwise, set zSql to point to the
2915 ** next statement to execute. */
2916 rc2 = sqlite3_finalize(pStmt);
2917 if( rc!=SQLITE_NOMEM ) rc = rc2;
2918 if( rc==SQLITE_OK ){
2919 zSql = zLeftover;
2920 while( IsSpace(zSql[0]) ) zSql++;
2921 }else if( pzErrMsg ){
2922 *pzErrMsg = save_err_msg(db);
2923 }
2924
2925 /* clear saved stmt handle */
2926 if( pArg ){
2927 pArg->pStmt = NULL;
2928 }
2929 }
2930 } /* end while */
2931
2932 return rc;
2933}
2934
2935/*
2936** Release memory previously allocated by tableColumnList().
2937*/
2938static void freeColumnList(char **azCol){
2939 int i;
2940 for(i=1; azCol[i]; i++){
2941 sqlite3_free(azCol[i]);
2942 }
2943 /* azCol[0] is a static string */
2944 sqlite3_free(azCol);
2945}
2946
2947/*
2948** Return a list of pointers to strings which are the names of all
2949** columns in table zTab. The memory to hold the names is dynamically
2950** allocated and must be released by the caller using a subsequent call
2951** to freeColumnList().
2952**
2953** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2954** value that needs to be preserved, then azCol[0] is filled in with the
2955** name of the rowid column.
2956**
2957** The first regular column in the table is azCol[1]. The list is terminated
2958** by an entry with azCol[i]==0.
2959*/
2960static char **tableColumnList(ShellState *p, const char *zTab){
2961 char **azCol = 0;
2962 sqlite3_stmt *pStmt;
2963 char *zSql;
2964 int nCol = 0;
2965 int nAlloc = 0;
2966 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2967 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
2968 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
2969 int rc;
2970
2971 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2972 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2973 sqlite3_free(zSql);
2974 if( rc ) return 0;
2975 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2976 if( nCol>=nAlloc-2 ){
2977 nAlloc = nAlloc*2 + nCol + 10;
2978 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2979 if( azCol==0 ){
2980 raw_printf(stderr, "Error: out of memory\n");
2981 exit(1);
2982 }
2983 }
2984 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2985 if( sqlite3_column_int(pStmt, 5) ){
2986 nPK++;
2987 if( nPK==1
2988 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2989 "INTEGER")==0
2990 ){
2991 isIPK = 1;
2992 }else{
2993 isIPK = 0;
2994 }
2995 }
2996 }
2997 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00002998 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002999 azCol[0] = 0;
3000 azCol[nCol+1] = 0;
3001
3002 /* The decision of whether or not a rowid really needs to be preserved
3003 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3004 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3005 ** rowids on tables where the rowid is inaccessible because there are other
3006 ** columns in the table named "rowid", "_rowid_", and "oid".
3007 */
3008 if( preserveRowid && isIPK ){
3009 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3010 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3011 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3012 ** ROWID aliases. To distinguish these cases, check to see if
3013 ** there is a "pk" entry in "PRAGMA index_list". There will be
3014 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3015 */
3016 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3017 " WHERE origin='pk'", zTab);
3018 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3019 sqlite3_free(zSql);
3020 if( rc ){
3021 freeColumnList(azCol);
3022 return 0;
3023 }
3024 rc = sqlite3_step(pStmt);
3025 sqlite3_finalize(pStmt);
3026 preserveRowid = rc==SQLITE_ROW;
3027 }
3028 if( preserveRowid ){
3029 /* Only preserve the rowid if we can find a name to use for the
3030 ** rowid */
3031 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3032 int i, j;
3033 for(j=0; j<3; j++){
3034 for(i=1; i<=nCol; i++){
3035 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3036 }
3037 if( i>nCol ){
3038 /* At this point, we know that azRowid[j] is not the name of any
3039 ** ordinary column in the table. Verify that azRowid[j] is a valid
3040 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3041 ** tables will fail this last check */
3042 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3043 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3044 break;
3045 }
3046 }
3047 }
3048 return azCol;
3049}
3050
3051/*
3052** Toggle the reverse_unordered_selects setting.
3053*/
3054static void toggleSelectOrder(sqlite3 *db){
3055 sqlite3_stmt *pStmt = 0;
3056 int iSetting = 0;
3057 char zStmt[100];
3058 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3059 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3060 iSetting = sqlite3_column_int(pStmt, 0);
3061 }
3062 sqlite3_finalize(pStmt);
3063 sqlite3_snprintf(sizeof(zStmt), zStmt,
3064 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3065 sqlite3_exec(db, zStmt, 0, 0, 0);
3066}
3067
3068/*
3069** This is a different callback routine used for dumping the database.
3070** Each row received by this callback consists of a table name,
3071** the table type ("index" or "table") and SQL to create the table.
3072** This routine should print text sufficient to recreate the table.
3073*/
3074static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3075 int rc;
3076 const char *zTable;
3077 const char *zType;
3078 const char *zSql;
3079 ShellState *p = (ShellState *)pArg;
3080
3081 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00003082 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003083 zTable = azArg[0];
3084 zType = azArg[1];
3085 zSql = azArg[2];
3086
3087 if( strcmp(zTable, "sqlite_sequence")==0 ){
3088 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3089 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3090 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3091 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3092 return 0;
3093 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3094 char *zIns;
3095 if( !p->writableSchema ){
3096 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3097 p->writableSchema = 1;
3098 }
3099 zIns = sqlite3_mprintf(
3100 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3101 "VALUES('table','%q','%q',0,'%q');",
3102 zTable, zTable, zSql);
3103 utf8_printf(p->out, "%s\n", zIns);
3104 sqlite3_free(zIns);
3105 return 0;
3106 }else{
3107 printSchemaLine(p->out, zSql, ";\n");
3108 }
3109
3110 if( strcmp(zType, "table")==0 ){
3111 ShellText sSelect;
3112 ShellText sTable;
3113 char **azCol;
3114 int i;
3115 char *savedDestTable;
3116 int savedMode;
3117
3118 azCol = tableColumnList(p, zTable);
3119 if( azCol==0 ){
3120 p->nErr++;
3121 return 0;
3122 }
3123
3124 /* Always quote the table name, even if it appears to be pure ascii,
3125 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3126 initText(&sTable);
3127 appendText(&sTable, zTable, quoteChar(zTable));
3128 /* If preserving the rowid, add a column list after the table name.
3129 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3130 ** instead of the usual "INSERT INTO tab VALUES(...)".
3131 */
3132 if( azCol[0] ){
3133 appendText(&sTable, "(", 0);
3134 appendText(&sTable, azCol[0], 0);
3135 for(i=1; azCol[i]; i++){
3136 appendText(&sTable, ",", 0);
3137 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3138 }
3139 appendText(&sTable, ")", 0);
3140 }
3141
3142 /* Build an appropriate SELECT statement */
3143 initText(&sSelect);
3144 appendText(&sSelect, "SELECT ", 0);
3145 if( azCol[0] ){
3146 appendText(&sSelect, azCol[0], 0);
3147 appendText(&sSelect, ",", 0);
3148 }
3149 for(i=1; azCol[i]; i++){
3150 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3151 if( azCol[i+1] ){
3152 appendText(&sSelect, ",", 0);
3153 }
3154 }
3155 freeColumnList(azCol);
3156 appendText(&sSelect, " FROM ", 0);
3157 appendText(&sSelect, zTable, quoteChar(zTable));
3158
3159 savedDestTable = p->zDestTable;
3160 savedMode = p->mode;
3161 p->zDestTable = sTable.z;
3162 p->mode = p->cMode = MODE_Insert;
drha10b9992018-03-09 15:24:33 +00003163 rc = shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003164 if( (rc&0xff)==SQLITE_CORRUPT ){
3165 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3166 toggleSelectOrder(p->db);
drha10b9992018-03-09 15:24:33 +00003167 shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003168 toggleSelectOrder(p->db);
3169 }
3170 p->zDestTable = savedDestTable;
3171 p->mode = savedMode;
3172 freeText(&sTable);
3173 freeText(&sSelect);
3174 if( rc ) p->nErr++;
3175 }
3176 return 0;
3177}
3178
3179/*
3180** Run zQuery. Use dump_callback() as the callback routine so that
3181** the contents of the query are output as SQL statements.
3182**
3183** If we get a SQLITE_CORRUPT error, rerun the query after appending
3184** "ORDER BY rowid DESC" to the end.
3185*/
3186static int run_schema_dump_query(
3187 ShellState *p,
3188 const char *zQuery
3189){
3190 int rc;
3191 char *zErr = 0;
3192 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3193 if( rc==SQLITE_CORRUPT ){
3194 char *zQ2;
3195 int len = strlen30(zQuery);
3196 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3197 if( zErr ){
3198 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3199 sqlite3_free(zErr);
3200 zErr = 0;
3201 }
3202 zQ2 = malloc( len+100 );
3203 if( zQ2==0 ) return rc;
3204 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3205 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3206 if( rc ){
3207 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3208 }else{
3209 rc = SQLITE_CORRUPT;
3210 }
3211 sqlite3_free(zErr);
3212 free(zQ2);
3213 }
3214 return rc;
3215}
3216
3217/*
3218** Text of a help message
3219*/
3220static char zHelp[] =
drhe37c0e12018-01-06 19:19:50 +00003221#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3222 ".archive ... Manage SQL archives: \".archive --help\" for details\n"
3223#endif
drh2ce15c32017-07-11 13:34:40 +00003224#ifndef SQLITE_OMIT_AUTHORIZATION
3225 ".auth ON|OFF Show authorizer callbacks\n"
3226#endif
3227 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
3228 ".bail on|off Stop after hitting an error. Default OFF\n"
3229 ".binary on|off Turn binary output on or off. Default OFF\n"
3230 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
3231 ".changes on|off Show number of rows changed by SQL\n"
3232 ".check GLOB Fail if output since .testcase does not match\n"
3233 ".clone NEWDB Clone data into NEWDB from the existing database\n"
3234 ".databases List names and files of attached databases\n"
3235 ".dbinfo ?DB? Show status information about the database\n"
3236 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
3237 " If TABLE specified, only dump tables matching\n"
3238 " LIKE pattern TABLE.\n"
3239 ".echo on|off Turn command echo on or off\n"
3240 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
drh13c20932018-01-10 21:41:55 +00003241 ".excel Display the output of next command in a spreadsheet\n"
drh2ce15c32017-07-11 13:34:40 +00003242 ".exit Exit this program\n"
dan2e1ea572017-12-21 18:55:24 +00003243 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
drh2ce15c32017-07-11 13:34:40 +00003244/* Because explain mode comes on automatically now, the ".explain" mode
3245** is removed from the help screen. It is still supported for legacy, however */
3246/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
3247 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3248 ".headers on|off Turn display of headers on or off\n"
3249 ".help Show this message\n"
3250 ".import FILE TABLE Import data from FILE into TABLE\n"
3251#ifndef SQLITE_OMIT_TEST_CONTROL
3252 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3253#endif
3254 ".indexes ?TABLE? Show names of all indexes\n"
3255 " If TABLE specified, only show indexes for tables\n"
3256 " matching LIKE pattern TABLE.\n"
3257#ifdef SQLITE_ENABLE_IOTRACE
3258 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3259#endif
3260 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
3261 ".lint OPTIONS Report potential schema issues. Options:\n"
3262 " fkey-indexes Find missing foreign key indexes\n"
3263#ifndef SQLITE_OMIT_LOAD_EXTENSION
3264 ".load FILE ?ENTRY? Load an extension library\n"
3265#endif
3266 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
3267 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
3268 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
3269 " csv Comma-separated values\n"
3270 " column Left-aligned columns. (See .width)\n"
3271 " html HTML <table> code\n"
3272 " insert SQL insert statements for TABLE\n"
3273 " line One value per line\n"
3274 " list Values delimited by \"|\"\n"
3275 " quote Escape answers as for SQL\n"
3276 " tabs Tab-separated values\n"
3277 " tcl TCL list elements\n"
3278 ".nullvalue STRING Use STRING in place of NULL values\n"
drh536c3452018-01-11 00:38:39 +00003279 ".once (-e|-x|FILE) Output for the next SQL command only to FILE\n"
3280 " or invoke system text editor (-e) or spreadsheet (-x)\n"
3281 " on the output.\n"
drh2ce15c32017-07-11 13:34:40 +00003282 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3283 " The --new option starts with an empty file\n"
drhee269a62018-02-14 23:27:43 +00003284 " Other options: --readonly --append --zip\n"
drh536c3452018-01-11 00:38:39 +00003285 ".output ?FILE? Send output to FILE or stdout\n"
drh2ce15c32017-07-11 13:34:40 +00003286 ".print STRING... Print literal STRING\n"
3287 ".prompt MAIN CONTINUE Replace the standard prompts\n"
3288 ".quit Exit this program\n"
3289 ".read FILENAME Execute SQL in FILENAME\n"
3290 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
3291 ".save FILE Write in-memory database into FILE\n"
3292 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3293 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3294 " Add --indent for pretty-printing\n"
3295 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
3296 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3297 " separator for both the output mode and .import\n"
3298#if defined(SQLITE_ENABLE_SESSION)
3299 ".session CMD ... Create or control sessions\n"
3300#endif
3301 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
drh04a28c32018-01-31 01:38:44 +00003302#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00003303 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
drh04a28c32018-01-31 01:38:44 +00003304#endif
drh2ce15c32017-07-11 13:34:40 +00003305 ".show Show the current values for various settings\n"
3306 ".stats ?on|off? Show stats or turn stats on or off\n"
drh04a28c32018-01-31 01:38:44 +00003307#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00003308 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
drh04a28c32018-01-31 01:38:44 +00003309#endif
drh2ce15c32017-07-11 13:34:40 +00003310 ".tables ?TABLE? List names of tables\n"
3311 " If TABLE specified, only list tables matching\n"
3312 " LIKE pattern TABLE.\n"
3313 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
3314 ".timeout MS Try opening locked tables for MS milliseconds\n"
3315 ".timer on|off Turn SQL timer on or off\n"
3316 ".trace FILE|off Output each SQL statement as it is run\n"
3317 ".vfsinfo ?AUX? Information about the top-level VFS\n"
3318 ".vfslist List all available VFSes\n"
3319 ".vfsname ?AUX? Print the name of the VFS stack\n"
3320 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
3321 " Negative values right-justify\n"
3322;
3323
3324#if defined(SQLITE_ENABLE_SESSION)
3325/*
3326** Print help information for the ".sessions" command
3327*/
3328void session_help(ShellState *p){
3329 raw_printf(p->out,
3330 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3331 "If ?NAME? is omitted, the first defined session is used.\n"
3332 "Subcommands:\n"
3333 " attach TABLE Attach TABLE\n"
3334 " changeset FILE Write a changeset into FILE\n"
3335 " close Close one session\n"
3336 " enable ?BOOLEAN? Set or query the enable bit\n"
3337 " filter GLOB... Reject tables matching GLOBs\n"
3338 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3339 " isempty Query whether the session is empty\n"
3340 " list List currently open session names\n"
3341 " open DB NAME Open a new session on DB\n"
3342 " patchset FILE Write a patchset into FILE\n"
3343 );
3344}
3345#endif
3346
3347
3348/* Forward reference */
3349static int process_input(ShellState *p, FILE *in);
3350
3351/*
3352** Read the content of file zName into memory obtained from sqlite3_malloc64()
3353** and return a pointer to the buffer. The caller is responsible for freeing
3354** the memory.
3355**
3356** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3357** read.
3358**
3359** For convenience, a nul-terminator byte is always appended to the data read
3360** from the file before the buffer is returned. This byte is not included in
3361** the final value of (*pnByte), if applicable.
3362**
3363** NULL is returned if any error is encountered. The final value of *pnByte
3364** is undefined in this case.
3365*/
3366static char *readFile(const char *zName, int *pnByte){
3367 FILE *in = fopen(zName, "rb");
3368 long nIn;
3369 size_t nRead;
3370 char *pBuf;
3371 if( in==0 ) return 0;
3372 fseek(in, 0, SEEK_END);
3373 nIn = ftell(in);
3374 rewind(in);
3375 pBuf = sqlite3_malloc64( nIn+1 );
3376 if( pBuf==0 ) return 0;
3377 nRead = fread(pBuf, nIn, 1, in);
3378 fclose(in);
3379 if( nRead!=1 ){
3380 sqlite3_free(pBuf);
3381 return 0;
3382 }
3383 pBuf[nIn] = 0;
3384 if( pnByte ) *pnByte = nIn;
3385 return pBuf;
3386}
3387
3388#if defined(SQLITE_ENABLE_SESSION)
3389/*
3390** Close a single OpenSession object and release all of its associated
3391** resources.
3392*/
3393static void session_close(OpenSession *pSession){
3394 int i;
3395 sqlite3session_delete(pSession->p);
3396 sqlite3_free(pSession->zName);
3397 for(i=0; i<pSession->nFilter; i++){
3398 sqlite3_free(pSession->azFilter[i]);
3399 }
3400 sqlite3_free(pSession->azFilter);
3401 memset(pSession, 0, sizeof(OpenSession));
3402}
3403#endif
3404
3405/*
3406** Close all OpenSession objects and release all associated resources.
3407*/
3408#if defined(SQLITE_ENABLE_SESSION)
3409static void session_close_all(ShellState *p){
3410 int i;
3411 for(i=0; i<p->nSession; i++){
3412 session_close(&p->aSession[i]);
3413 }
3414 p->nSession = 0;
3415}
3416#else
3417# define session_close_all(X)
3418#endif
3419
3420/*
3421** Implementation of the xFilter function for an open session. Omit
3422** any tables named by ".session filter" but let all other table through.
3423*/
3424#if defined(SQLITE_ENABLE_SESSION)
3425static int session_filter(void *pCtx, const char *zTab){
3426 OpenSession *pSession = (OpenSession*)pCtx;
3427 int i;
3428 for(i=0; i<pSession->nFilter; i++){
3429 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3430 }
3431 return 1;
3432}
3433#endif
3434
3435/*
drh1fa6d9f2018-01-06 21:46:01 +00003436** Try to deduce the type of file for zName based on its content. Return
3437** one of the SHELL_OPEN_* constants.
drh1bf208c2018-03-09 21:54:01 +00003438**
3439** If the file does not exist or is empty but its name looks like a ZIP
3440** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3441** Otherwise, assume an ordinary database regardless of the filename if
3442** the type cannot be determined from content.
drh1fa6d9f2018-01-06 21:46:01 +00003443*/
drh1bf208c2018-03-09 21:54:01 +00003444static int deduceDatabaseType(const char *zName, int dfltZip){
drh1fa6d9f2018-01-06 21:46:01 +00003445 FILE *f = fopen(zName, "rb");
3446 size_t n;
3447 int rc = SHELL_OPEN_UNSPEC;
3448 char zBuf[100];
drh1bf208c2018-03-09 21:54:01 +00003449 if( f==0 ){
3450 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ) return SHELL_OPEN_ZIPFILE;
3451 return SHELL_OPEN_NORMAL;
3452 }
drh1fa6d9f2018-01-06 21:46:01 +00003453 fseek(f, -25, SEEK_END);
3454 n = fread(zBuf, 25, 1, f);
3455 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3456 rc = SHELL_OPEN_APPENDVFS;
3457 }else{
3458 fseek(f, -22, SEEK_END);
3459 n = fread(zBuf, 22, 1, f);
3460 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3461 && zBuf[3]==0x06 ){
3462 rc = SHELL_OPEN_ZIPFILE;
drh1bf208c2018-03-09 21:54:01 +00003463 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3464 return SHELL_OPEN_ZIPFILE;
drh1fa6d9f2018-01-06 21:46:01 +00003465 }
3466 }
3467 fclose(f);
3468 return rc;
3469}
3470
3471/*
drh2ce15c32017-07-11 13:34:40 +00003472** Make sure the database is open. If it is not, then open it. If
3473** the database fails to open, print an error message and exit.
3474*/
3475static void open_db(ShellState *p, int keepAlive){
3476 if( p->db==0 ){
3477 sqlite3_initialize();
drh1fa6d9f2018-01-06 21:46:01 +00003478 if( p->openMode==SHELL_OPEN_UNSPEC && access(p->zDbFilename,0)==0 ){
drh1bf208c2018-03-09 21:54:01 +00003479 p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 0);
drh1fa6d9f2018-01-06 21:46:01 +00003480 }
3481 switch( p->openMode ){
3482 case SHELL_OPEN_APPENDVFS: {
3483 sqlite3_open_v2(p->zDbFilename, &p->db,
3484 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
3485 break;
3486 }
3487 case SHELL_OPEN_ZIPFILE: {
3488 sqlite3_open(":memory:", &p->db);
3489 break;
3490 }
drhee269a62018-02-14 23:27:43 +00003491 case SHELL_OPEN_READONLY: {
3492 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
3493 break;
3494 }
drh1fa6d9f2018-01-06 21:46:01 +00003495 case SHELL_OPEN_UNSPEC:
3496 case SHELL_OPEN_NORMAL: {
3497 sqlite3_open(p->zDbFilename, &p->db);
3498 break;
3499 }
3500 }
drh2ce15c32017-07-11 13:34:40 +00003501 globalDb = p->db;
3502 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3503 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3504 p->zDbFilename, sqlite3_errmsg(p->db));
3505 if( keepAlive ) return;
3506 exit(1);
3507 }
3508#ifndef SQLITE_OMIT_LOAD_EXTENSION
3509 sqlite3_enable_load_extension(p->db, 1);
3510#endif
3511 sqlite3_fileio_init(p->db, 0, 0);
3512 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00003513 sqlite3_completion_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003514#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00003515 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00003516 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003517#endif
drhceba7922018-01-01 21:28:25 +00003518 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00003519 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00003520 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3521 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00003522 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
3523 shellPutsFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00003524#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00003525 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
3526 editFunc, 0, 0);
3527 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
3528 editFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00003529#endif
drh1fa6d9f2018-01-06 21:46:01 +00003530 if( p->openMode==SHELL_OPEN_ZIPFILE ){
3531 char *zSql = sqlite3_mprintf(
3532 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
3533 sqlite3_exec(p->db, zSql, 0, 0, 0);
3534 sqlite3_free(zSql);
3535 }
drh2ce15c32017-07-11 13:34:40 +00003536 }
3537}
3538
drh56eb09b2017-07-11 13:59:07 +00003539#if HAVE_READLINE || HAVE_EDITLINE
3540/*
3541** Readline completion callbacks
3542*/
3543static char *readline_completion_generator(const char *text, int state){
3544 static sqlite3_stmt *pStmt = 0;
3545 char *zRet;
3546 if( state==0 ){
3547 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00003548 sqlite3_finalize(pStmt);
3549 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3550 " FROM completion(%Q) ORDER BY 1", text);
3551 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3552 sqlite3_free(zSql);
3553 }
3554 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00003555 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00003556 }else{
3557 sqlite3_finalize(pStmt);
3558 pStmt = 0;
3559 zRet = 0;
3560 }
3561 return zRet;
3562}
3563static char **readline_completion(const char *zText, int iStart, int iEnd){
3564 rl_attempted_completion_over = 1;
3565 return rl_completion_matches(zText, readline_completion_generator);
3566}
3567
3568#elif HAVE_LINENOISE
3569/*
3570** Linenoise completion callback
3571*/
3572static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00003573 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00003574 int i, iStart;
3575 sqlite3_stmt *pStmt = 0;
3576 char *zSql;
3577 char zBuf[1000];
3578
3579 if( nLine>sizeof(zBuf)-30 ) return;
3580 if( zLine[0]=='.' ) return;
3581 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
3582 if( i==nLine-1 ) return;
3583 iStart = i+1;
3584 memcpy(zBuf, zLine, iStart);
3585 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3586 " FROM completion(%Q,%Q) ORDER BY 1",
3587 &zLine[iStart], zLine);
3588 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3589 sqlite3_free(zSql);
3590 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3591 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3592 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
3593 int nCompletion = sqlite3_column_bytes(pStmt, 0);
3594 if( iStart+nCompletion < sizeof(zBuf)-1 ){
3595 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
3596 linenoiseAddCompletion(lc, zBuf);
3597 }
3598 }
3599 sqlite3_finalize(pStmt);
3600}
3601#endif
3602
drh2ce15c32017-07-11 13:34:40 +00003603/*
3604** Do C-language style dequoting.
3605**
3606** \a -> alarm
3607** \b -> backspace
3608** \t -> tab
3609** \n -> newline
3610** \v -> vertical tab
3611** \f -> form feed
3612** \r -> carriage return
3613** \s -> space
3614** \" -> "
3615** \' -> '
3616** \\ -> backslash
3617** \NNN -> ascii character NNN in octal
3618*/
3619static void resolve_backslashes(char *z){
3620 int i, j;
3621 char c;
3622 while( *z && *z!='\\' ) z++;
3623 for(i=j=0; (c = z[i])!=0; i++, j++){
3624 if( c=='\\' && z[i+1]!=0 ){
3625 c = z[++i];
3626 if( c=='a' ){
3627 c = '\a';
3628 }else if( c=='b' ){
3629 c = '\b';
3630 }else if( c=='t' ){
3631 c = '\t';
3632 }else if( c=='n' ){
3633 c = '\n';
3634 }else if( c=='v' ){
3635 c = '\v';
3636 }else if( c=='f' ){
3637 c = '\f';
3638 }else if( c=='r' ){
3639 c = '\r';
3640 }else if( c=='"' ){
3641 c = '"';
3642 }else if( c=='\'' ){
3643 c = '\'';
3644 }else if( c=='\\' ){
3645 c = '\\';
3646 }else if( c>='0' && c<='7' ){
3647 c -= '0';
3648 if( z[i+1]>='0' && z[i+1]<='7' ){
3649 i++;
3650 c = (c<<3) + z[i] - '0';
3651 if( z[i+1]>='0' && z[i+1]<='7' ){
3652 i++;
3653 c = (c<<3) + z[i] - '0';
3654 }
3655 }
3656 }
3657 }
3658 z[j] = c;
3659 }
3660 if( j<i ) z[j] = 0;
3661}
3662
3663/*
drh2ce15c32017-07-11 13:34:40 +00003664** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3665** for TRUE and FALSE. Return the integer value if appropriate.
3666*/
3667static int booleanValue(const char *zArg){
3668 int i;
3669 if( zArg[0]=='0' && zArg[1]=='x' ){
3670 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3671 }else{
3672 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3673 }
3674 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3675 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3676 return 1;
3677 }
3678 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3679 return 0;
3680 }
3681 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3682 zArg);
3683 return 0;
3684}
3685
3686/*
3687** Set or clear a shell flag according to a boolean value.
3688*/
3689static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3690 if( booleanValue(zArg) ){
3691 ShellSetFlag(p, mFlag);
3692 }else{
3693 ShellClearFlag(p, mFlag);
3694 }
3695}
3696
3697/*
3698** Close an output file, assuming it is not stderr or stdout
3699*/
3700static void output_file_close(FILE *f){
3701 if( f && f!=stdout && f!=stderr ) fclose(f);
3702}
3703
3704/*
3705** Try to open an output file. The names "stdout" and "stderr" are
3706** recognized and do the right thing. NULL is returned if the output
3707** filename is "off".
3708*/
drha92a01a2018-01-10 22:15:37 +00003709static FILE *output_file_open(const char *zFile, int bTextMode){
drh2ce15c32017-07-11 13:34:40 +00003710 FILE *f;
3711 if( strcmp(zFile,"stdout")==0 ){
3712 f = stdout;
3713 }else if( strcmp(zFile, "stderr")==0 ){
3714 f = stderr;
3715 }else if( strcmp(zFile, "off")==0 ){
3716 f = 0;
3717 }else{
drha92a01a2018-01-10 22:15:37 +00003718 f = fopen(zFile, bTextMode ? "w" : "wb");
drh2ce15c32017-07-11 13:34:40 +00003719 if( f==0 ){
3720 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3721 }
3722 }
3723 return f;
3724}
3725
3726#if !defined(SQLITE_UNTESTABLE)
3727#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3728/*
3729** A routine for handling output from sqlite3_trace().
3730*/
3731static int sql_trace_callback(
3732 unsigned mType,
3733 void *pArg,
3734 void *pP,
3735 void *pX
3736){
3737 FILE *f = (FILE*)pArg;
3738 UNUSED_PARAMETER(mType);
3739 UNUSED_PARAMETER(pP);
3740 if( f ){
3741 const char *z = (const char*)pX;
drhaf2770f2018-01-05 14:55:43 +00003742 int i = strlen30(z);
drh2ce15c32017-07-11 13:34:40 +00003743 while( i>0 && z[i-1]==';' ){ i--; }
3744 utf8_printf(f, "%.*s;\n", i, z);
3745 }
3746 return 0;
3747}
3748#endif
3749#endif
3750
3751/*
3752** A no-op routine that runs with the ".breakpoint" doc-command. This is
3753** a useful spot to set a debugger breakpoint.
3754*/
3755static void test_breakpoint(void){
3756 static int nCall = 0;
3757 nCall++;
3758}
3759
3760/*
3761** An object used to read a CSV and other files for import.
3762*/
3763typedef struct ImportCtx ImportCtx;
3764struct ImportCtx {
3765 const char *zFile; /* Name of the input file */
3766 FILE *in; /* Read the CSV text from this input stream */
3767 char *z; /* Accumulated text for a field */
3768 int n; /* Number of bytes in z */
3769 int nAlloc; /* Space allocated for z[] */
3770 int nLine; /* Current line number */
3771 int bNotFirst; /* True if one or more bytes already read */
3772 int cTerm; /* Character that terminated the most recent field */
3773 int cColSep; /* The column separator character. (Usually ",") */
3774 int cRowSep; /* The row separator character. (Usually "\n") */
3775};
3776
3777/* Append a single byte to z[] */
3778static void import_append_char(ImportCtx *p, int c){
3779 if( p->n+1>=p->nAlloc ){
3780 p->nAlloc += p->nAlloc + 100;
3781 p->z = sqlite3_realloc64(p->z, p->nAlloc);
3782 if( p->z==0 ){
3783 raw_printf(stderr, "out of memory\n");
3784 exit(1);
3785 }
3786 }
3787 p->z[p->n++] = (char)c;
3788}
3789
3790/* Read a single field of CSV text. Compatible with rfc4180 and extended
3791** with the option of having a separator other than ",".
3792**
3793** + Input comes from p->in.
3794** + Store results in p->z of length p->n. Space to hold p->z comes
3795** from sqlite3_malloc64().
3796** + Use p->cSep as the column separator. The default is ",".
3797** + Use p->rSep as the row separator. The default is "\n".
3798** + Keep track of the line number in p->nLine.
3799** + Store the character that terminates the field in p->cTerm. Store
3800** EOF on end-of-file.
3801** + Report syntax errors on stderr
3802*/
3803static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3804 int c;
3805 int cSep = p->cColSep;
3806 int rSep = p->cRowSep;
3807 p->n = 0;
3808 c = fgetc(p->in);
3809 if( c==EOF || seenInterrupt ){
3810 p->cTerm = EOF;
3811 return 0;
3812 }
3813 if( c=='"' ){
3814 int pc, ppc;
3815 int startLine = p->nLine;
3816 int cQuote = c;
3817 pc = ppc = 0;
3818 while( 1 ){
3819 c = fgetc(p->in);
3820 if( c==rSep ) p->nLine++;
3821 if( c==cQuote ){
3822 if( pc==cQuote ){
3823 pc = 0;
3824 continue;
3825 }
3826 }
3827 if( (c==cSep && pc==cQuote)
3828 || (c==rSep && pc==cQuote)
3829 || (c==rSep && pc=='\r' && ppc==cQuote)
3830 || (c==EOF && pc==cQuote)
3831 ){
3832 do{ p->n--; }while( p->z[p->n]!=cQuote );
3833 p->cTerm = c;
3834 break;
3835 }
3836 if( pc==cQuote && c!='\r' ){
3837 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3838 p->zFile, p->nLine, cQuote);
3839 }
3840 if( c==EOF ){
3841 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3842 p->zFile, startLine, cQuote);
3843 p->cTerm = c;
3844 break;
3845 }
3846 import_append_char(p, c);
3847 ppc = pc;
3848 pc = c;
3849 }
3850 }else{
3851 /* If this is the first field being parsed and it begins with the
3852 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3853 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3854 import_append_char(p, c);
3855 c = fgetc(p->in);
3856 if( (c&0xff)==0xbb ){
3857 import_append_char(p, c);
3858 c = fgetc(p->in);
3859 if( (c&0xff)==0xbf ){
3860 p->bNotFirst = 1;
3861 p->n = 0;
3862 return csv_read_one_field(p);
3863 }
3864 }
3865 }
3866 while( c!=EOF && c!=cSep && c!=rSep ){
3867 import_append_char(p, c);
3868 c = fgetc(p->in);
3869 }
3870 if( c==rSep ){
3871 p->nLine++;
3872 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3873 }
3874 p->cTerm = c;
3875 }
3876 if( p->z ) p->z[p->n] = 0;
3877 p->bNotFirst = 1;
3878 return p->z;
3879}
3880
3881/* Read a single field of ASCII delimited text.
3882**
3883** + Input comes from p->in.
3884** + Store results in p->z of length p->n. Space to hold p->z comes
3885** from sqlite3_malloc64().
3886** + Use p->cSep as the column separator. The default is "\x1F".
3887** + Use p->rSep as the row separator. The default is "\x1E".
3888** + Keep track of the row number in p->nLine.
3889** + Store the character that terminates the field in p->cTerm. Store
3890** EOF on end-of-file.
3891** + Report syntax errors on stderr
3892*/
3893static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3894 int c;
3895 int cSep = p->cColSep;
3896 int rSep = p->cRowSep;
3897 p->n = 0;
3898 c = fgetc(p->in);
3899 if( c==EOF || seenInterrupt ){
3900 p->cTerm = EOF;
3901 return 0;
3902 }
3903 while( c!=EOF && c!=cSep && c!=rSep ){
3904 import_append_char(p, c);
3905 c = fgetc(p->in);
3906 }
3907 if( c==rSep ){
3908 p->nLine++;
3909 }
3910 p->cTerm = c;
3911 if( p->z ) p->z[p->n] = 0;
3912 return p->z;
3913}
3914
3915/*
3916** Try to transfer data for table zTable. If an error is seen while
3917** moving forward, try to go backwards. The backwards movement won't
3918** work for WITHOUT ROWID tables.
3919*/
3920static void tryToCloneData(
3921 ShellState *p,
3922 sqlite3 *newDb,
3923 const char *zTable
3924){
3925 sqlite3_stmt *pQuery = 0;
3926 sqlite3_stmt *pInsert = 0;
3927 char *zQuery = 0;
3928 char *zInsert = 0;
3929 int rc;
3930 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00003931 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00003932 int k = 0;
3933 int cnt = 0;
3934 const int spinRate = 10000;
3935
3936 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3937 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3938 if( rc ){
3939 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3940 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3941 zQuery);
3942 goto end_data_xfer;
3943 }
3944 n = sqlite3_column_count(pQuery);
3945 zInsert = sqlite3_malloc64(200 + nTable + n*3);
3946 if( zInsert==0 ){
3947 raw_printf(stderr, "out of memory\n");
3948 goto end_data_xfer;
3949 }
3950 sqlite3_snprintf(200+nTable,zInsert,
3951 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00003952 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00003953 for(j=1; j<n; j++){
3954 memcpy(zInsert+i, ",?", 2);
3955 i += 2;
3956 }
3957 memcpy(zInsert+i, ");", 3);
3958 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3959 if( rc ){
3960 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3961 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3962 zQuery);
3963 goto end_data_xfer;
3964 }
3965 for(k=0; k<2; k++){
3966 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3967 for(i=0; i<n; i++){
3968 switch( sqlite3_column_type(pQuery, i) ){
3969 case SQLITE_NULL: {
3970 sqlite3_bind_null(pInsert, i+1);
3971 break;
3972 }
3973 case SQLITE_INTEGER: {
3974 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3975 break;
3976 }
3977 case SQLITE_FLOAT: {
3978 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3979 break;
3980 }
3981 case SQLITE_TEXT: {
3982 sqlite3_bind_text(pInsert, i+1,
3983 (const char*)sqlite3_column_text(pQuery,i),
3984 -1, SQLITE_STATIC);
3985 break;
3986 }
3987 case SQLITE_BLOB: {
3988 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3989 sqlite3_column_bytes(pQuery,i),
3990 SQLITE_STATIC);
3991 break;
3992 }
3993 }
3994 } /* End for */
3995 rc = sqlite3_step(pInsert);
3996 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3997 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3998 sqlite3_errmsg(newDb));
3999 }
4000 sqlite3_reset(pInsert);
4001 cnt++;
4002 if( (cnt%spinRate)==0 ){
4003 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4004 fflush(stdout);
4005 }
4006 } /* End while */
4007 if( rc==SQLITE_DONE ) break;
4008 sqlite3_finalize(pQuery);
4009 sqlite3_free(zQuery);
4010 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4011 zTable);
4012 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4013 if( rc ){
4014 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4015 break;
4016 }
4017 } /* End for(k=0...) */
4018
4019end_data_xfer:
4020 sqlite3_finalize(pQuery);
4021 sqlite3_finalize(pInsert);
4022 sqlite3_free(zQuery);
4023 sqlite3_free(zInsert);
4024}
4025
4026
4027/*
4028** Try to transfer all rows of the schema that match zWhere. For
4029** each row, invoke xForEach() on the object defined by that row.
4030** If an error is encountered while moving forward through the
4031** sqlite_master table, try again moving backwards.
4032*/
4033static void tryToCloneSchema(
4034 ShellState *p,
4035 sqlite3 *newDb,
4036 const char *zWhere,
4037 void (*xForEach)(ShellState*,sqlite3*,const char*)
4038){
4039 sqlite3_stmt *pQuery = 0;
4040 char *zQuery = 0;
4041 int rc;
4042 const unsigned char *zName;
4043 const unsigned char *zSql;
4044 char *zErrMsg = 0;
4045
4046 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4047 " WHERE %s", zWhere);
4048 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4049 if( rc ){
4050 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4051 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4052 zQuery);
4053 goto end_schema_xfer;
4054 }
4055 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4056 zName = sqlite3_column_text(pQuery, 0);
4057 zSql = sqlite3_column_text(pQuery, 1);
4058 printf("%s... ", zName); fflush(stdout);
4059 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4060 if( zErrMsg ){
4061 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4062 sqlite3_free(zErrMsg);
4063 zErrMsg = 0;
4064 }
4065 if( xForEach ){
4066 xForEach(p, newDb, (const char*)zName);
4067 }
4068 printf("done\n");
4069 }
4070 if( rc!=SQLITE_DONE ){
4071 sqlite3_finalize(pQuery);
4072 sqlite3_free(zQuery);
4073 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4074 " WHERE %s ORDER BY rowid DESC", zWhere);
4075 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4076 if( rc ){
4077 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4078 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4079 zQuery);
4080 goto end_schema_xfer;
4081 }
4082 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4083 zName = sqlite3_column_text(pQuery, 0);
4084 zSql = sqlite3_column_text(pQuery, 1);
4085 printf("%s... ", zName); fflush(stdout);
4086 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4087 if( zErrMsg ){
4088 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4089 sqlite3_free(zErrMsg);
4090 zErrMsg = 0;
4091 }
4092 if( xForEach ){
4093 xForEach(p, newDb, (const char*)zName);
4094 }
4095 printf("done\n");
4096 }
4097 }
4098end_schema_xfer:
4099 sqlite3_finalize(pQuery);
4100 sqlite3_free(zQuery);
4101}
4102
4103/*
4104** Open a new database file named "zNewDb". Try to recover as much information
4105** as possible out of the main database (which might be corrupt) and write it
4106** into zNewDb.
4107*/
4108static void tryToClone(ShellState *p, const char *zNewDb){
4109 int rc;
4110 sqlite3 *newDb = 0;
4111 if( access(zNewDb,0)==0 ){
4112 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4113 return;
4114 }
4115 rc = sqlite3_open(zNewDb, &newDb);
4116 if( rc ){
4117 utf8_printf(stderr, "Cannot create output database: %s\n",
4118 sqlite3_errmsg(newDb));
4119 }else{
4120 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4121 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4122 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4123 tryToCloneSchema(p, newDb, "type!='table'", 0);
4124 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4125 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4126 }
4127 sqlite3_close(newDb);
4128}
4129
4130/*
drh13c20932018-01-10 21:41:55 +00004131** Change the output file back to stdout.
4132**
4133** If the p->doXdgOpen flag is set, that means the output was being
4134** redirected to a temporary file named by p->zTempFile. In that case,
4135** launch start/open/xdg-open on that temporary file.
drh2ce15c32017-07-11 13:34:40 +00004136*/
4137static void output_reset(ShellState *p){
4138 if( p->outfile[0]=='|' ){
4139#ifndef SQLITE_OMIT_POPEN
4140 pclose(p->out);
4141#endif
4142 }else{
4143 output_file_close(p->out);
drh04a28c32018-01-31 01:38:44 +00004144#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00004145 if( p->doXdgOpen ){
4146 const char *zXdgOpenCmd =
4147#if defined(_WIN32)
4148 "start";
4149#elif defined(__APPLE__)
4150 "open";
4151#else
4152 "xdg-open";
4153#endif
4154 char *zCmd;
4155 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
drha92a01a2018-01-10 22:15:37 +00004156 if( system(zCmd) ){
4157 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4158 }
drh13c20932018-01-10 21:41:55 +00004159 sqlite3_free(zCmd);
drh3c484e82018-01-10 22:27:21 +00004160 outputModePop(p);
drh13c20932018-01-10 21:41:55 +00004161 p->doXdgOpen = 0;
4162 }
drh04a28c32018-01-31 01:38:44 +00004163#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00004164 }
4165 p->outfile[0] = 0;
4166 p->out = stdout;
4167}
4168
4169/*
4170** Run an SQL command and return the single integer result.
4171*/
4172static int db_int(ShellState *p, const char *zSql){
4173 sqlite3_stmt *pStmt;
4174 int res = 0;
4175 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4176 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4177 res = sqlite3_column_int(pStmt,0);
4178 }
4179 sqlite3_finalize(pStmt);
4180 return res;
4181}
4182
4183/*
4184** Convert a 2-byte or 4-byte big-endian integer into a native integer
4185*/
4186static unsigned int get2byteInt(unsigned char *a){
4187 return (a[0]<<8) + a[1];
4188}
4189static unsigned int get4byteInt(unsigned char *a){
4190 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4191}
4192
4193/*
4194** Implementation of the ".info" command.
4195**
4196** Return 1 on error, 2 to exit, and 0 otherwise.
4197*/
4198static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4199 static const struct { const char *zName; int ofst; } aField[] = {
4200 { "file change counter:", 24 },
4201 { "database page count:", 28 },
4202 { "freelist page count:", 36 },
4203 { "schema cookie:", 40 },
4204 { "schema format:", 44 },
4205 { "default cache size:", 48 },
4206 { "autovacuum top root:", 52 },
4207 { "incremental vacuum:", 64 },
4208 { "text encoding:", 56 },
4209 { "user version:", 60 },
4210 { "application id:", 68 },
4211 { "software version:", 96 },
4212 };
4213 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4214 { "number of tables:",
4215 "SELECT count(*) FROM %s WHERE type='table'" },
4216 { "number of indexes:",
4217 "SELECT count(*) FROM %s WHERE type='index'" },
4218 { "number of triggers:",
4219 "SELECT count(*) FROM %s WHERE type='trigger'" },
4220 { "number of views:",
4221 "SELECT count(*) FROM %s WHERE type='view'" },
4222 { "schema size:",
4223 "SELECT total(length(sql)) FROM %s" },
4224 };
drh2ce15c32017-07-11 13:34:40 +00004225 int i;
4226 char *zSchemaTab;
4227 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004228 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004229 unsigned char aHdr[100];
4230 open_db(p, 0);
4231 if( p->db==0 ) return 1;
drh512e6c32017-10-11 17:51:08 +00004232 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4233 -1, &pStmt, 0);
4234 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4235 if( sqlite3_step(pStmt)==SQLITE_ROW
4236 && sqlite3_column_bytes(pStmt,0)>100
4237 ){
4238 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4239 sqlite3_finalize(pStmt);
4240 }else{
drh2ce15c32017-07-11 13:34:40 +00004241 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004242 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004243 return 1;
4244 }
4245 i = get2byteInt(aHdr+16);
4246 if( i==1 ) i = 65536;
4247 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4248 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4249 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4250 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4251 for(i=0; i<ArraySize(aField); i++){
4252 int ofst = aField[i].ofst;
4253 unsigned int val = get4byteInt(aHdr + ofst);
4254 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4255 switch( ofst ){
4256 case 56: {
4257 if( val==1 ) raw_printf(p->out, " (utf8)");
4258 if( val==2 ) raw_printf(p->out, " (utf16le)");
4259 if( val==3 ) raw_printf(p->out, " (utf16be)");
4260 }
4261 }
4262 raw_printf(p->out, "\n");
4263 }
4264 if( zDb==0 ){
4265 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4266 }else if( strcmp(zDb,"temp")==0 ){
4267 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4268 }else{
4269 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4270 }
4271 for(i=0; i<ArraySize(aQuery); i++){
4272 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4273 int val = db_int(p, zSql);
4274 sqlite3_free(zSql);
4275 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4276 }
4277 sqlite3_free(zSchemaTab);
4278 return 0;
4279}
4280
4281/*
4282** Print the current sqlite3_errmsg() value to stderr and return 1.
4283*/
4284static int shellDatabaseError(sqlite3 *db){
4285 const char *zErr = sqlite3_errmsg(db);
4286 utf8_printf(stderr, "Error: %s\n", zErr);
4287 return 1;
4288}
4289
4290/*
4291** Print an out-of-memory message to stderr and return 1.
4292*/
4293static int shellNomemError(void){
4294 raw_printf(stderr, "Error: out of memory\n");
4295 return 1;
4296}
4297
4298/*
4299** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4300** if they match and FALSE (0) if they do not match.
4301**
4302** Globbing rules:
4303**
4304** '*' Matches any sequence of zero or more characters.
4305**
4306** '?' Matches exactly one character.
4307**
4308** [...] Matches one character from the enclosed list of
4309** characters.
4310**
4311** [^...] Matches one character not in the enclosed list.
4312**
4313** '#' Matches any sequence of one or more digits with an
4314** optional + or - sign in front
4315**
4316** ' ' Any span of whitespace matches any other span of
4317** whitespace.
4318**
4319** Extra whitespace at the end of z[] is ignored.
4320*/
4321static int testcase_glob(const char *zGlob, const char *z){
4322 int c, c2;
4323 int invert;
4324 int seen;
4325
4326 while( (c = (*(zGlob++)))!=0 ){
4327 if( IsSpace(c) ){
4328 if( !IsSpace(*z) ) return 0;
4329 while( IsSpace(*zGlob) ) zGlob++;
4330 while( IsSpace(*z) ) z++;
4331 }else if( c=='*' ){
4332 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4333 if( c=='?' && (*(z++))==0 ) return 0;
4334 }
4335 if( c==0 ){
4336 return 1;
4337 }else if( c=='[' ){
4338 while( *z && testcase_glob(zGlob-1,z)==0 ){
4339 z++;
4340 }
4341 return (*z)!=0;
4342 }
4343 while( (c2 = (*(z++)))!=0 ){
4344 while( c2!=c ){
4345 c2 = *(z++);
4346 if( c2==0 ) return 0;
4347 }
4348 if( testcase_glob(zGlob,z) ) return 1;
4349 }
4350 return 0;
4351 }else if( c=='?' ){
4352 if( (*(z++))==0 ) return 0;
4353 }else if( c=='[' ){
4354 int prior_c = 0;
4355 seen = 0;
4356 invert = 0;
4357 c = *(z++);
4358 if( c==0 ) return 0;
4359 c2 = *(zGlob++);
4360 if( c2=='^' ){
4361 invert = 1;
4362 c2 = *(zGlob++);
4363 }
4364 if( c2==']' ){
4365 if( c==']' ) seen = 1;
4366 c2 = *(zGlob++);
4367 }
4368 while( c2 && c2!=']' ){
4369 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4370 c2 = *(zGlob++);
4371 if( c>=prior_c && c<=c2 ) seen = 1;
4372 prior_c = 0;
4373 }else{
4374 if( c==c2 ){
4375 seen = 1;
4376 }
4377 prior_c = c2;
4378 }
4379 c2 = *(zGlob++);
4380 }
4381 if( c2==0 || (seen ^ invert)==0 ) return 0;
4382 }else if( c=='#' ){
4383 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4384 if( !IsDigit(z[0]) ) return 0;
4385 z++;
4386 while( IsDigit(z[0]) ){ z++; }
4387 }else{
4388 if( c!=(*(z++)) ) return 0;
4389 }
4390 }
4391 while( IsSpace(*z) ){ z++; }
4392 return *z==0;
4393}
4394
4395
4396/*
4397** Compare the string as a command-line option with either one or two
4398** initial "-" characters.
4399*/
4400static int optionMatch(const char *zStr, const char *zOpt){
4401 if( zStr[0]!='-' ) return 0;
4402 zStr++;
4403 if( zStr[0]=='-' ) zStr++;
4404 return strcmp(zStr, zOpt)==0;
4405}
4406
4407/*
4408** Delete a file.
4409*/
4410int shellDeleteFile(const char *zFilename){
4411 int rc;
4412#ifdef _WIN32
4413 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4414 rc = _wunlink(z);
4415 sqlite3_free(z);
4416#else
4417 rc = unlink(zFilename);
4418#endif
4419 return rc;
4420}
4421
drh13c20932018-01-10 21:41:55 +00004422/*
4423** Try to delete the temporary file (if there is one) and free the
4424** memory used to hold the name of the temp file.
4425*/
4426static void clearTempFile(ShellState *p){
4427 if( p->zTempFile==0 ) return;
drh536c3452018-01-11 00:38:39 +00004428 if( p->doXdgOpen ) return;
drh13c20932018-01-10 21:41:55 +00004429 if( shellDeleteFile(p->zTempFile) ) return;
4430 sqlite3_free(p->zTempFile);
4431 p->zTempFile = 0;
4432}
4433
4434/*
4435** Create a new temp file name with the given suffix.
4436*/
4437static void newTempFile(ShellState *p, const char *zSuffix){
4438 clearTempFile(p);
4439 sqlite3_free(p->zTempFile);
4440 p->zTempFile = 0;
drh7f3bf8a2018-01-10 21:50:08 +00004441 if( p->db ){
4442 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
4443 }
drh13c20932018-01-10 21:41:55 +00004444 if( p->zTempFile==0 ){
4445 sqlite3_uint64 r;
4446 sqlite3_randomness(sizeof(r), &r);
4447 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
4448 }else{
4449 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
4450 }
4451 if( p->zTempFile==0 ){
4452 raw_printf(stderr, "out of memory\n");
4453 exit(1);
4454 }
4455}
4456
drh2ce15c32017-07-11 13:34:40 +00004457
4458/*
4459** The implementation of SQL scalar function fkey_collate_clause(), used
4460** by the ".lint fkey-indexes" command. This scalar function is always
4461** called with four arguments - the parent table name, the parent column name,
4462** the child table name and the child column name.
4463**
4464** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4465**
4466** If either of the named tables or columns do not exist, this function
4467** returns an empty string. An empty string is also returned if both tables
4468** and columns exist but have the same default collation sequence. Or,
4469** if both exist but the default collation sequences are different, this
4470** function returns the string " COLLATE <parent-collation>", where
4471** <parent-collation> is the default collation sequence of the parent column.
4472*/
4473static void shellFkeyCollateClause(
4474 sqlite3_context *pCtx,
4475 int nVal,
4476 sqlite3_value **apVal
4477){
4478 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4479 const char *zParent;
4480 const char *zParentCol;
4481 const char *zParentSeq;
4482 const char *zChild;
4483 const char *zChildCol;
4484 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4485 int rc;
4486
4487 assert( nVal==4 );
4488 zParent = (const char*)sqlite3_value_text(apVal[0]);
4489 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4490 zChild = (const char*)sqlite3_value_text(apVal[2]);
4491 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4492
4493 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4494 rc = sqlite3_table_column_metadata(
4495 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4496 );
4497 if( rc==SQLITE_OK ){
4498 rc = sqlite3_table_column_metadata(
4499 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4500 );
4501 }
4502
4503 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4504 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4505 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4506 sqlite3_free(z);
4507 }
4508}
4509
4510
4511/*
4512** The implementation of dot-command ".lint fkey-indexes".
4513*/
4514static int lintFkeyIndexes(
4515 ShellState *pState, /* Current shell tool state */
4516 char **azArg, /* Array of arguments passed to dot command */
4517 int nArg /* Number of entries in azArg[] */
4518){
4519 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4520 FILE *out = pState->out; /* Stream to write non-error output to */
4521 int bVerbose = 0; /* If -verbose is present */
4522 int bGroupByParent = 0; /* If -groupbyparent is present */
4523 int i; /* To iterate through azArg[] */
4524 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4525 int rc; /* Return code */
4526 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4527
4528 /*
4529 ** This SELECT statement returns one row for each foreign key constraint
4530 ** in the schema of the main database. The column values are:
4531 **
4532 ** 0. The text of an SQL statement similar to:
4533 **
danf9679312017-12-01 18:40:18 +00004534 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00004535 **
danf9679312017-12-01 18:40:18 +00004536 ** This SELECT is similar to the one that the foreign keys implementation
4537 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00004538 ** be used to optimize this query, then it can also be used by the FK
4539 ** implementation to optimize DELETE or UPDATE statements on the parent
4540 ** table.
4541 **
4542 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4543 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4544 ** contains an index that can be used to optimize the query.
4545 **
4546 ** 2. Human readable text that describes the child table and columns. e.g.
4547 **
4548 ** "child_table(child_key1, child_key2)"
4549 **
4550 ** 3. Human readable text that describes the parent table and columns. e.g.
4551 **
4552 ** "parent_table(parent_key1, parent_key2)"
4553 **
4554 ** 4. A full CREATE INDEX statement for an index that could be used to
4555 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4556 **
4557 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4558 **
4559 ** 5. The name of the parent table.
4560 **
4561 ** These six values are used by the C logic below to generate the report.
4562 */
4563 const char *zSql =
4564 "SELECT "
danf9679312017-12-01 18:40:18 +00004565 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00004566 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4567 " || fkey_collate_clause("
4568 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4569 ", "
4570 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4571 " || group_concat('*=?', ' AND ') || ')'"
4572 ", "
4573 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4574 ", "
4575 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4576 ", "
4577 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4578 " || ' ON ' || quote(s.name) || '('"
4579 " || group_concat(quote(f.[from]) ||"
4580 " fkey_collate_clause("
4581 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4582 " || ');'"
4583 ", "
4584 " f.[table] "
4585 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4586 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4587 "GROUP BY s.name, f.id "
4588 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4589 ;
4590 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4591
4592 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00004593 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00004594 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4595 bVerbose = 1;
4596 }
4597 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4598 bGroupByParent = 1;
4599 zIndent = " ";
4600 }
4601 else{
4602 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4603 azArg[0], azArg[1]
4604 );
4605 return SQLITE_ERROR;
4606 }
4607 }
4608
4609 /* Register the fkey_collate_clause() SQL function */
4610 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4611 0, shellFkeyCollateClause, 0, 0
4612 );
4613
4614
4615 if( rc==SQLITE_OK ){
4616 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4617 }
4618 if( rc==SQLITE_OK ){
4619 sqlite3_bind_int(pSql, 1, bGroupByParent);
4620 }
4621
4622 if( rc==SQLITE_OK ){
4623 int rc2;
4624 char *zPrev = 0;
4625 while( SQLITE_ROW==sqlite3_step(pSql) ){
4626 int res = -1;
4627 sqlite3_stmt *pExplain = 0;
4628 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4629 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4630 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4631 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4632 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4633 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4634
4635 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4636 if( rc!=SQLITE_OK ) break;
4637 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4638 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4639 res = (
4640 0==sqlite3_strglob(zGlob, zPlan)
4641 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4642 );
4643 }
4644 rc = sqlite3_finalize(pExplain);
4645 if( rc!=SQLITE_OK ) break;
4646
4647 if( res<0 ){
4648 raw_printf(stderr, "Error: internal error");
4649 break;
4650 }else{
4651 if( bGroupByParent
4652 && (bVerbose || res==0)
4653 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4654 ){
4655 raw_printf(out, "-- Parent table %s\n", zParent);
4656 sqlite3_free(zPrev);
4657 zPrev = sqlite3_mprintf("%s", zParent);
4658 }
4659
4660 if( res==0 ){
4661 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4662 }else if( bVerbose ){
4663 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4664 zIndent, zFrom, zTarget
4665 );
4666 }
4667 }
4668 }
4669 sqlite3_free(zPrev);
4670
4671 if( rc!=SQLITE_OK ){
4672 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4673 }
4674
4675 rc2 = sqlite3_finalize(pSql);
4676 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4677 rc = rc2;
4678 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4679 }
4680 }else{
4681 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4682 }
4683
4684 return rc;
4685}
4686
4687/*
4688** Implementation of ".lint" dot command.
4689*/
4690static int lintDotCommand(
4691 ShellState *pState, /* Current shell tool state */
4692 char **azArg, /* Array of arguments passed to dot command */
4693 int nArg /* Number of entries in azArg[] */
4694){
4695 int n;
drhaf2770f2018-01-05 14:55:43 +00004696 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00004697 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4698 return lintFkeyIndexes(pState, azArg, nArg);
4699
4700 usage:
4701 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4702 raw_printf(stderr, "Where sub-commands are:\n");
4703 raw_printf(stderr, " fkey-indexes\n");
4704 return SQLITE_ERROR;
4705}
4706
drhe37c0e12018-01-06 19:19:50 +00004707#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4708/*********************************************************************************
4709** The ".archive" or ".ar" command.
4710*/
danfd0245d2017-12-07 15:44:29 +00004711static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00004712 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00004713 int *pRc,
4714 const char *zSql,
4715 sqlite3_stmt **ppStmt
4716){
4717 *ppStmt = 0;
4718 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004719 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00004720 if( rc!=SQLITE_OK ){
4721 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00004722 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00004723 );
4724 *pRc = rc;
4725 }
4726 }
4727}
4728
danac15e2d2017-12-14 19:15:07 +00004729static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00004730 sqlite3 *db,
4731 int *pRc,
danac15e2d2017-12-14 19:15:07 +00004732 sqlite3_stmt **ppStmt,
4733 const char *zFmt,
4734 ...
dan3f67ddf2017-12-13 20:04:53 +00004735){
danac15e2d2017-12-14 19:15:07 +00004736 *ppStmt = 0;
4737 if( *pRc==SQLITE_OK ){
4738 va_list ap;
4739 char *z;
4740 va_start(ap, zFmt);
4741 z = sqlite3_vmprintf(zFmt, ap);
dan3f67ddf2017-12-13 20:04:53 +00004742 if( z==0 ){
4743 *pRc = SQLITE_NOMEM;
4744 }else{
4745 shellPrepare(db, pRc, z, ppStmt);
4746 sqlite3_free(z);
4747 }
dan3f67ddf2017-12-13 20:04:53 +00004748 }
4749}
4750
danfd0245d2017-12-07 15:44:29 +00004751static void shellFinalize(
4752 int *pRc,
4753 sqlite3_stmt *pStmt
4754){
dan25c12182017-12-07 21:03:33 +00004755 if( pStmt ){
4756 sqlite3 *db = sqlite3_db_handle(pStmt);
4757 int rc = sqlite3_finalize(pStmt);
4758 if( *pRc==SQLITE_OK ){
4759 if( rc!=SQLITE_OK ){
4760 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4761 }
4762 *pRc = rc;
4763 }
4764 }
danfd0245d2017-12-07 15:44:29 +00004765}
4766
4767static void shellReset(
4768 int *pRc,
4769 sqlite3_stmt *pStmt
4770){
4771 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00004772 if( *pRc==SQLITE_OK ){
4773 if( rc!=SQLITE_OK ){
4774 sqlite3 *db = sqlite3_db_handle(pStmt);
4775 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4776 }
4777 *pRc = rc;
4778 }
danfd0245d2017-12-07 15:44:29 +00004779}
drhe37c0e12018-01-06 19:19:50 +00004780/*
dan88be0202017-12-09 17:58:02 +00004781** Structure representing a single ".ar" command.
4782*/
4783typedef struct ArCommand ArCommand;
4784struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00004785 u8 eCmd; /* An AR_CMD_* value */
4786 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00004787 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00004788 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00004789 u8 bAppend; /* True if --append */
drhb376b3d2018-01-10 13:11:51 +00004790 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00004791 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00004792 const char *zFile; /* --file argument, or NULL */
4793 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00004794 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00004795 ShellState *p; /* Shell state */
4796 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00004797};
4798
4799/*
4800** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4801*/
dan0d0547f2017-12-14 15:40:42 +00004802static int arUsage(FILE *f){
4803 raw_printf(f,
4804"\n"
4805"Usage: .ar [OPTION...] [FILE...]\n"
4806"The .ar command manages sqlar archives.\n"
4807"\n"
4808"Examples:\n"
4809" .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4810" .ar -tf archive.sar # List members of archive.sar\n"
4811" .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4812"\n"
4813"Each command line must feature exactly one command option:\n"
4814" -c, --create Create a new archive\n"
4815" -u, --update Update or add files to an existing archive\n"
4816" -t, --list List contents of archive\n"
4817" -x, --extract Extract files from archive\n"
4818"\n"
4819"And zero or more optional options:\n"
4820" -v, --verbose Print each filename as it is processed\n"
4821" -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
drhca7733b2018-01-10 18:09:20 +00004822" -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS\n"
dan0d0547f2017-12-14 15:40:42 +00004823" -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
drhb376b3d2018-01-10 13:11:51 +00004824" -n, --dryrun Show the SQL that would have occurred\n"
dan0d0547f2017-12-14 15:40:42 +00004825"\n"
4826"See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4827"\n"
4828);
4829 return SQLITE_ERROR;
4830}
4831
4832/*
4833** Print an error message for the .ar command to stderr and return
4834** SQLITE_ERROR.
4835*/
4836static int arErrorMsg(const char *zFmt, ...){
4837 va_list ap;
4838 char *z;
4839 va_start(ap, zFmt);
4840 z = sqlite3_vmprintf(zFmt, ap);
4841 va_end(ap);
4842 raw_printf(stderr, "Error: %s (try \".ar --help\")\n", z);
4843 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00004844 return SQLITE_ERROR;
4845}
4846
4847/*
4848** Values for ArCommand.eCmd.
4849*/
dand4b56e52017-12-12 20:04:59 +00004850#define AR_CMD_CREATE 1
4851#define AR_CMD_EXTRACT 2
4852#define AR_CMD_LIST 3
4853#define AR_CMD_UPDATE 4
dan0d0547f2017-12-14 15:40:42 +00004854#define AR_CMD_HELP 5
dand4b56e52017-12-12 20:04:59 +00004855
4856/*
4857** Other (non-command) switches.
4858*/
drhb376b3d2018-01-10 13:11:51 +00004859#define AR_SWITCH_VERBOSE 6
4860#define AR_SWITCH_FILE 7
4861#define AR_SWITCH_DIRECTORY 8
drha5676c42018-01-10 15:17:34 +00004862#define AR_SWITCH_APPEND 9
drhb376b3d2018-01-10 13:11:51 +00004863#define AR_SWITCH_DRYRUN 10
dand4b56e52017-12-12 20:04:59 +00004864
4865static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
4866 switch( eSwitch ){
4867 case AR_CMD_CREATE:
4868 case AR_CMD_EXTRACT:
4869 case AR_CMD_LIST:
4870 case AR_CMD_UPDATE:
dan0d0547f2017-12-14 15:40:42 +00004871 case AR_CMD_HELP:
4872 if( pAr->eCmd ){
4873 return arErrorMsg("multiple command options");
4874 }
dand4b56e52017-12-12 20:04:59 +00004875 pAr->eCmd = eSwitch;
4876 break;
4877
drhb376b3d2018-01-10 13:11:51 +00004878 case AR_SWITCH_DRYRUN:
4879 pAr->bDryRun = 1;
4880 break;
dand4b56e52017-12-12 20:04:59 +00004881 case AR_SWITCH_VERBOSE:
4882 pAr->bVerbose = 1;
4883 break;
drha5676c42018-01-10 15:17:34 +00004884 case AR_SWITCH_APPEND:
4885 pAr->bAppend = 1;
drhca7733b2018-01-10 18:09:20 +00004886 /* Fall thru into --file */
dand4b56e52017-12-12 20:04:59 +00004887 case AR_SWITCH_FILE:
4888 pAr->zFile = zArg;
4889 break;
4890 case AR_SWITCH_DIRECTORY:
4891 pAr->zDir = zArg;
4892 break;
4893 }
4894
4895 return SQLITE_OK;
4896}
dan88be0202017-12-09 17:58:02 +00004897
4898/*
4899** Parse the command line for an ".ar" command. The results are written into
4900** structure (*pAr). SQLITE_OK is returned if the command line is parsed
4901** successfully, otherwise an error message is written to stderr and
4902** SQLITE_ERROR returned.
4903*/
4904static int arParseCommand(
4905 char **azArg, /* Array of arguments passed to dot command */
4906 int nArg, /* Number of entries in azArg[] */
4907 ArCommand *pAr /* Populate this object */
4908){
dand4b56e52017-12-12 20:04:59 +00004909 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00004910 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00004911 char cShort;
4912 u8 eSwitch;
4913 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00004914 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00004915 { "create", 'c', AR_CMD_CREATE, 0 },
4916 { "extract", 'x', AR_CMD_EXTRACT, 0 },
4917 { "list", 't', AR_CMD_LIST, 0 },
4918 { "update", 'u', AR_CMD_UPDATE, 0 },
4919 { "help", 'h', AR_CMD_HELP, 0 },
4920 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
4921 { "file", 'f', AR_SWITCH_FILE, 1 },
drhca7733b2018-01-10 18:09:20 +00004922 { "append", 'a', AR_SWITCH_APPEND, 1 },
drhb376b3d2018-01-10 13:11:51 +00004923 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drhb376b3d2018-01-10 13:11:51 +00004924 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00004925 };
4926 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
4927 struct ArSwitch *pEnd = &aSwitch[nSwitch];
4928
dan88be0202017-12-09 17:58:02 +00004929 if( nArg<=1 ){
dan0d0547f2017-12-14 15:40:42 +00004930 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00004931 }else{
4932 char *z = azArg[1];
4933 memset(pAr, 0, sizeof(ArCommand));
4934
4935 if( z[0]!='-' ){
4936 /* Traditional style [tar] invocation */
4937 int i;
4938 int iArg = 2;
4939 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00004940 const char *zArg = 0;
4941 struct ArSwitch *pOpt;
4942 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4943 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00004944 }
dan0d0547f2017-12-14 15:40:42 +00004945 if( pOpt==pEnd ){
4946 return arErrorMsg("unrecognized option: %c", z[i]);
4947 }
dand4b56e52017-12-12 20:04:59 +00004948 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00004949 if( iArg>=nArg ){
4950 return arErrorMsg("option requires an argument: %c",z[i]);
4951 }
dand4b56e52017-12-12 20:04:59 +00004952 zArg = azArg[iArg++];
4953 }
4954 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00004955 }
dan88be0202017-12-09 17:58:02 +00004956 pAr->nArg = nArg-iArg;
4957 if( pAr->nArg>0 ){
4958 pAr->azArg = &azArg[iArg];
4959 }
dand4b56e52017-12-12 20:04:59 +00004960 }else{
4961 /* Non-traditional invocation */
4962 int iArg;
4963 for(iArg=1; iArg<nArg; iArg++){
4964 int n;
4965 z = azArg[iArg];
4966 if( z[0]!='-' ){
4967 /* All remaining command line words are command arguments. */
4968 pAr->azArg = &azArg[iArg];
4969 pAr->nArg = nArg-iArg;
4970 break;
4971 }
drhaf2770f2018-01-05 14:55:43 +00004972 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00004973
4974 if( z[1]!='-' ){
4975 int i;
4976 /* One or more short options */
4977 for(i=1; i<n; i++){
4978 const char *zArg = 0;
4979 struct ArSwitch *pOpt;
4980 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4981 if( z[i]==pOpt->cShort ) break;
4982 }
dan0d0547f2017-12-14 15:40:42 +00004983 if( pOpt==pEnd ){
4984 return arErrorMsg("unrecognized option: %c\n", z[i]);
4985 }
dand4b56e52017-12-12 20:04:59 +00004986 if( pOpt->bArg ){
4987 if( i<(n-1) ){
4988 zArg = &z[i+1];
4989 i = n;
4990 }else{
dan0d0547f2017-12-14 15:40:42 +00004991 if( iArg>=(nArg-1) ){
4992 return arErrorMsg("option requires an argument: %c\n",z[i]);
4993 }
dand4b56e52017-12-12 20:04:59 +00004994 zArg = azArg[++iArg];
4995 }
4996 }
4997 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
4998 }
4999 }else if( z[2]=='\0' ){
5000 /* A -- option, indicating that all remaining command line words
5001 ** are command arguments. */
5002 pAr->azArg = &azArg[iArg+1];
5003 pAr->nArg = nArg-iArg-1;
5004 break;
5005 }else{
5006 /* A long option */
5007 const char *zArg = 0; /* Argument for option, if any */
5008 struct ArSwitch *pMatch = 0; /* Matching option */
5009 struct ArSwitch *pOpt; /* Iterator */
5010 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5011 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00005012 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00005013 if( pMatch ){
dan0d0547f2017-12-14 15:40:42 +00005014 return arErrorMsg("ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00005015 }else{
5016 pMatch = pOpt;
5017 }
5018 }
5019 }
5020
5021 if( pMatch==0 ){
dan0d0547f2017-12-14 15:40:42 +00005022 return arErrorMsg("unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00005023 }
5024 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005025 if( iArg>=(nArg-1) ){
5026 return arErrorMsg("option requires an argument: %s", z);
5027 }
dand4b56e52017-12-12 20:04:59 +00005028 zArg = azArg[++iArg];
5029 }
5030 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5031 }
5032 }
dan88be0202017-12-09 17:58:02 +00005033 }
5034 }
5035
5036 return SQLITE_OK;
5037}
5038
5039/*
dan3f67ddf2017-12-13 20:04:53 +00005040** This function assumes that all arguments within the ArCommand.azArg[]
5041** array refer to archive members, as for the --extract or --list commands.
5042** It checks that each of them are present. If any specified file is not
5043** present in the archive, an error is printed to stderr and an error
5044** code returned. Otherwise, if all specified arguments are present in
5045** the archive, SQLITE_OK is returned.
5046**
5047** This function strips any trailing '/' characters from each argument.
5048** This is consistent with the way the [tar] command seems to work on
5049** Linux.
5050*/
drhb376b3d2018-01-10 13:11:51 +00005051static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00005052 int rc = SQLITE_OK;
5053 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00005054 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00005055 sqlite3_stmt *pTest = 0;
5056
drhb376b3d2018-01-10 13:11:51 +00005057 shellPreparePrintf(pAr->db, &rc, &pTest,
5058 "SELECT name FROM %s WHERE name=$name",
5059 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00005060 );
drhb376b3d2018-01-10 13:11:51 +00005061 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00005062 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5063 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00005064 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00005065 int bOk = 0;
5066 while( n>0 && z[n-1]=='/' ) n--;
5067 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00005068 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00005069 if( SQLITE_ROW==sqlite3_step(pTest) ){
5070 bOk = 1;
5071 }
5072 shellReset(&rc, pTest);
5073 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00005074 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00005075 rc = SQLITE_ERROR;
5076 }
5077 }
5078 shellFinalize(&rc, pTest);
5079 }
dan3f67ddf2017-12-13 20:04:53 +00005080 return rc;
5081}
5082
5083/*
5084** Format a WHERE clause that can be used against the "sqlar" table to
5085** identify all archive members that match the command arguments held
5086** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5087** The caller is responsible for eventually calling sqlite3_free() on
5088** any non-NULL (*pzWhere) value.
5089*/
5090static void arWhereClause(
5091 int *pRc,
5092 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00005093 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00005094){
5095 char *zWhere = 0;
5096 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00005097 if( pAr->nArg==0 ){
5098 zWhere = sqlite3_mprintf("1");
5099 }else{
5100 int i;
5101 const char *zSep = "";
5102 for(i=0; i<pAr->nArg; i++){
5103 const char *z = pAr->azArg[i];
5104 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00005105 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5106 zWhere, zSep, z, strlen30(z)+1, z
5107 );
danac15e2d2017-12-14 19:15:07 +00005108 if( zWhere==0 ){
5109 *pRc = SQLITE_NOMEM;
5110 break;
5111 }
5112 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00005113 }
dan3f67ddf2017-12-13 20:04:53 +00005114 }
5115 }
5116 *pzWhere = zWhere;
5117}
5118
5119/*
dan88be0202017-12-09 17:58:02 +00005120** Implementation of .ar "lisT" command.
5121*/
drhb376b3d2018-01-10 13:11:51 +00005122static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00005123 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00005124 const char *azCols[] = {
5125 "name",
drh410cad92018-01-10 17:19:16 +00005126 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00005127 };
dan5a78b812017-12-27 18:54:11 +00005128
dan3f67ddf2017-12-13 20:04:53 +00005129 char *zWhere = 0;
5130 sqlite3_stmt *pSql = 0;
5131 int rc;
5132
drhb376b3d2018-01-10 13:11:51 +00005133 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005134 arWhereClause(&rc, pAr, &zWhere);
5135
drhb376b3d2018-01-10 13:11:51 +00005136 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5137 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00005138 if( pAr->bDryRun ){
5139 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5140 }else{
5141 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5142 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00005143 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5144 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00005145 sqlite3_column_int(pSql, 1),
5146 sqlite3_column_text(pSql, 2),
5147 sqlite3_column_text(pSql, 3)
5148 );
5149 }else{
5150 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5151 }
danb5090e42017-12-27 21:13:21 +00005152 }
dan3f67ddf2017-12-13 20:04:53 +00005153 }
dan5a78b812017-12-27 18:54:11 +00005154 shellFinalize(&rc, pSql);
dan3f67ddf2017-12-13 20:04:53 +00005155 return rc;
dan88be0202017-12-09 17:58:02 +00005156}
5157
5158
danfd0245d2017-12-07 15:44:29 +00005159/*
5160** Implementation of .ar "eXtract" command.
5161*/
drhb376b3d2018-01-10 13:11:51 +00005162static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00005163 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00005164 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00005165 " ($dir || name),"
5166 " writefile(($dir || name), %s, mode, mtime) "
5167 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)";
dan5a78b812017-12-27 18:54:11 +00005168
5169 const char *azExtraArg[] = {
5170 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00005171 "data"
dan5a78b812017-12-27 18:54:11 +00005172 };
dan5a78b812017-12-27 18:54:11 +00005173
danfd0245d2017-12-07 15:44:29 +00005174 sqlite3_stmt *pSql = 0;
5175 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00005176 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00005177 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00005178 int i, j;
dan2ad09492017-12-09 18:28:22 +00005179
dan3f67ddf2017-12-13 20:04:53 +00005180 /* If arguments are specified, check that they actually exist within
5181 ** the archive before proceeding. And formulate a WHERE clause to
5182 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00005183 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005184 arWhereClause(&rc, pAr, &zWhere);
5185
5186 if( rc==SQLITE_OK ){
5187 if( pAr->zDir ){
5188 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5189 }else{
5190 zDir = sqlite3_mprintf("");
5191 }
5192 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00005193 }
danfd0245d2017-12-07 15:44:29 +00005194
drhb376b3d2018-01-10 13:11:51 +00005195 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5196 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00005197 );
5198
dan2ad09492017-12-09 18:28:22 +00005199 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005200 j = sqlite3_bind_parameter_index(pSql, "$dir");
5201 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00005202
danac15e2d2017-12-14 19:15:07 +00005203 /* Run the SELECT statement twice. The first time, writefile() is called
5204 ** for all archive members that should be extracted. The second time,
5205 ** only for the directories. This is because the timestamps for
5206 ** extracted directories must be reset after they are populated (as
5207 ** populating them changes the timestamp). */
5208 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00005209 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5210 sqlite3_bind_int(pSql, j, i);
5211 if( pAr->bDryRun ){
5212 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5213 }else{
5214 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5215 if( i==0 && pAr->bVerbose ){
5216 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5217 }
danac15e2d2017-12-14 19:15:07 +00005218 }
5219 }
5220 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005221 }
danac15e2d2017-12-14 19:15:07 +00005222 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005223 }
dan25c12182017-12-07 21:03:33 +00005224
dan2ad09492017-12-09 18:28:22 +00005225 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00005226 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00005227 return rc;
5228}
5229
drhb376b3d2018-01-10 13:11:51 +00005230/*
5231** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5232*/
5233static int arExecSql(ArCommand *pAr, const char *zSql){
5234 int rc;
5235 if( pAr->bDryRun ){
5236 utf8_printf(pAr->p->out, "%s\n", zSql);
5237 rc = SQLITE_OK;
5238 }else{
drh410cad92018-01-10 17:19:16 +00005239 char *zErr = 0;
5240 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5241 if( zErr ){
5242 utf8_printf(stdout, "ERROR: %s\n", zErr);
5243 sqlite3_free(zErr);
5244 }
drhb376b3d2018-01-10 13:11:51 +00005245 }
5246 return rc;
5247}
5248
dan1ad3f612017-12-11 20:22:02 +00005249
danfd0245d2017-12-07 15:44:29 +00005250/*
dan06741a32017-12-13 20:17:18 +00005251** Implementation of .ar "create" and "update" commands.
danfd0245d2017-12-07 15:44:29 +00005252**
5253** Create the "sqlar" table in the database if it does not already exist.
5254** Then add each file in the azFile[] array to the archive. Directories
5255** are added recursively. If argument bVerbose is non-zero, a message is
5256** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00005257**
5258** The create command is the same as update, except that it drops
5259** any existing "sqlar" table before beginning.
danfd0245d2017-12-07 15:44:29 +00005260*/
drhb376b3d2018-01-10 13:11:51 +00005261static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00005262 ArCommand *pAr, /* Command arguments and options */
drhb376b3d2018-01-10 13:11:51 +00005263 int bUpdate /* true for a --create. false for --update */
danfd0245d2017-12-07 15:44:29 +00005264){
dand4b56e52017-12-12 20:04:59 +00005265 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00005266 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5267 " name TEXT PRIMARY KEY, -- name of the file\n"
5268 " mode INT, -- access permissions\n"
5269 " mtime INT, -- last modification time\n"
5270 " sz INT, -- original file size\n"
5271 " data BLOB -- compressed content\n"
5272 ")";
dand4b56e52017-12-12 20:04:59 +00005273 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh1bf208c2018-03-09 21:54:01 +00005274 const char *zInsertFmt[2] = {
5275 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
drh634c70f2018-01-10 16:50:18 +00005276 " SELECT\n"
5277 " %s,\n"
5278 " mode,\n"
5279 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00005280 " CASE substr(lsmode(mode),1,1)\n"
5281 " WHEN '-' THEN length(data)\n"
5282 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00005283 " ELSE -1 END,\n"
drh69d2d352018-03-09 22:18:53 +00005284 " sqlar_compress(data)\n"
drh634c70f2018-01-10 16:50:18 +00005285 " FROM fsdir(%Q,%Q)\n"
drh1bf208c2018-03-09 21:54:01 +00005286 " WHERE lsmode(mode) NOT LIKE '?%%';",
5287 "REPLACE INTO %s(name,mode,mtime,data)\n"
5288 " SELECT\n"
5289 " %s,\n"
5290 " mode,\n"
5291 " mtime,\n"
5292 " data\n"
5293 " FROM fsdir(%Q,%Q)\n"
5294 " WHERE lsmode(mode) NOT LIKE '?%%';"
5295 };
danfd0245d2017-12-07 15:44:29 +00005296 int i; /* For iterating through azFile[] */
5297 int rc; /* Return code */
drh1bf208c2018-03-09 21:54:01 +00005298 const char *zTab = 0; /* SQL table into which to insert */
5299 char *zSql;
5300 char zTemp[50];
danfd0245d2017-12-07 15:44:29 +00005301
drh1bf208c2018-03-09 21:54:01 +00005302 arExecSql(pAr, "PRAGMA page_size=512");
drhb376b3d2018-01-10 13:11:51 +00005303 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00005304 if( rc!=SQLITE_OK ) return rc;
drh1bf208c2018-03-09 21:54:01 +00005305 zTemp[0] = 0;
5306 if( pAr->bZip ){
5307 /* Initialize the zipfile virtual table, if necessary */
5308 if( pAr->zFile ){
5309 sqlite3_uint64 r;
5310 sqlite3_randomness(sizeof(r),&r);
5311 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5312 zTab = zTemp;
5313 zSql = sqlite3_mprintf(
5314 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5315 zTab, pAr->zFile
5316 );
5317 rc = arExecSql(pAr, zSql);
5318 sqlite3_free(zSql);
5319 }else{
5320 zTab = "zip";
5321 }
5322 }else{
5323 /* Initialize the table for an SQLAR */
5324 zTab = "sqlar";
5325 if( bUpdate==0 ){
5326 rc = arExecSql(pAr, zDrop);
5327 if( rc!=SQLITE_OK ) goto end_ar_transaction;
5328 }
5329 rc = arExecSql(pAr, zCreate);
dan06741a32017-12-13 20:17:18 +00005330 }
dan88be0202017-12-09 17:58:02 +00005331 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
drh1bf208c2018-03-09 21:54:01 +00005332 char *zSql = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
drh634c70f2018-01-10 16:50:18 +00005333 pAr->bVerbose ? "shell_putsnl(name)" : "name",
5334 pAr->azArg[i], pAr->zDir);
5335 rc = arExecSql(pAr, zSql);
5336 sqlite3_free(zSql);
danfd0245d2017-12-07 15:44:29 +00005337 }
drh1bf208c2018-03-09 21:54:01 +00005338end_ar_transaction:
danfd0245d2017-12-07 15:44:29 +00005339 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005340 arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
danfd0245d2017-12-07 15:44:29 +00005341 }else{
drhb376b3d2018-01-10 13:11:51 +00005342 rc = arExecSql(pAr, "RELEASE ar;");
drh1bf208c2018-03-09 21:54:01 +00005343 if( pAr->bZip && pAr->zFile ){
5344 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
5345 arExecSql(pAr, zSql);
5346 sqlite3_free(zSql);
5347 }
danfd0245d2017-12-07 15:44:29 +00005348 }
danfd0245d2017-12-07 15:44:29 +00005349 return rc;
5350}
5351
5352/*
5353** Implementation of ".ar" dot command.
5354*/
5355static int arDotCommand(
5356 ShellState *pState, /* Current shell tool state */
5357 char **azArg, /* Array of arguments passed to dot command */
5358 int nArg /* Number of entries in azArg[] */
5359){
dan88be0202017-12-09 17:58:02 +00005360 ArCommand cmd;
5361 int rc;
drh34660642018-01-10 17:39:54 +00005362 memset(&cmd, 0, sizeof(cmd));
dan88be0202017-12-09 17:58:02 +00005363 rc = arParseCommand(azArg, nArg, &cmd);
5364 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00005365 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00005366 cmd.p = pState;
5367 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00005368 if( cmd.zFile ){
drh1bf208c2018-03-09 21:54:01 +00005369 eDbType = deduceDatabaseType(cmd.zFile, 1);
drha5676c42018-01-10 15:17:34 +00005370 }else{
5371 eDbType = pState->openMode;
5372 }
5373 if( eDbType==SHELL_OPEN_ZIPFILE ){
drh1bf208c2018-03-09 21:54:01 +00005374 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
5375 if( cmd.zFile==0 ){
5376 cmd.zSrcTable = sqlite3_mprintf("zip");
5377 }else{
5378 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
5379 }
dan5a78b812017-12-27 18:54:11 +00005380 }
drha5676c42018-01-10 15:17:34 +00005381 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00005382 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00005383 int flags;
drha5676c42018-01-10 15:17:34 +00005384 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
dand4b56e52017-12-12 20:04:59 +00005385 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
5386 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
5387 }else{
5388 flags = SQLITE_OPEN_READONLY;
5389 }
drha82c95b2018-01-10 14:00:00 +00005390 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00005391 if( cmd.bDryRun ){
5392 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
5393 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
5394 }
5395 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
5396 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00005397 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005398 utf8_printf(stderr, "cannot open file: %s (%s)\n",
5399 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00005400 );
drha5676c42018-01-10 15:17:34 +00005401 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00005402 }
drhb376b3d2018-01-10 13:11:51 +00005403 sqlite3_fileio_init(cmd.db, 0, 0);
drhb376b3d2018-01-10 13:11:51 +00005404 sqlite3_sqlar_init(cmd.db, 0, 0);
drh34660642018-01-10 17:39:54 +00005405 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
5406 shellPutsFunc, 0, 0);
5407
dand4b56e52017-12-12 20:04:59 +00005408 }
drh1bf208c2018-03-09 21:54:01 +00005409 if( cmd.zSrcTable==0 && cmd.bZip==0 ){
drh634c70f2018-01-10 16:50:18 +00005410 if( cmd.eCmd!=AR_CMD_CREATE
5411 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
5412 ){
drha5676c42018-01-10 15:17:34 +00005413 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
5414 rc = SQLITE_ERROR;
5415 goto end_ar_command;
5416 }
5417 cmd.zSrcTable = sqlite3_mprintf("sqlar");
5418 }
dand4b56e52017-12-12 20:04:59 +00005419
dan88be0202017-12-09 17:58:02 +00005420 switch( cmd.eCmd ){
5421 case AR_CMD_CREATE:
drhb376b3d2018-01-10 13:11:51 +00005422 rc = arCreateOrUpdateCommand(&cmd, 0);
dan88be0202017-12-09 17:58:02 +00005423 break;
danfd0245d2017-12-07 15:44:29 +00005424
dan88be0202017-12-09 17:58:02 +00005425 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00005426 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005427 break;
5428
5429 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00005430 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005431 break;
5432
dan0d0547f2017-12-14 15:40:42 +00005433 case AR_CMD_HELP:
5434 arUsage(pState->out);
5435 break;
5436
dan88be0202017-12-09 17:58:02 +00005437 default:
5438 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb376b3d2018-01-10 13:11:51 +00005439 rc = arCreateOrUpdateCommand(&cmd, 1);
dan88be0202017-12-09 17:58:02 +00005440 break;
danfd0245d2017-12-07 15:44:29 +00005441 }
5442 }
drha5676c42018-01-10 15:17:34 +00005443end_ar_command:
5444 if( cmd.db!=pState->db ){
5445 sqlite3_close(cmd.db);
5446 }
5447 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00005448
dan88be0202017-12-09 17:58:02 +00005449 return rc;
danfd0245d2017-12-07 15:44:29 +00005450}
drhe37c0e12018-01-06 19:19:50 +00005451/* End of the ".archive" or ".ar" command logic
5452**********************************************************************************/
5453#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00005454
drh2ce15c32017-07-11 13:34:40 +00005455
5456/*
5457** If an input line begins with "." then invoke this routine to
5458** process that line.
5459**
5460** Return 1 on error, 2 to exit, and 0 otherwise.
5461*/
5462static int do_meta_command(char *zLine, ShellState *p){
5463 int h = 1;
5464 int nArg = 0;
5465 int n, c;
5466 int rc = 0;
5467 char *azArg[50];
5468
dan6b046be2018-01-09 15:25:55 +00005469#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00005470 if( p->expert.pExpert ){
5471 expertFinish(p, 1, 0);
5472 }
dan6b046be2018-01-09 15:25:55 +00005473#endif
dan43efc182017-12-19 17:42:13 +00005474
drh2ce15c32017-07-11 13:34:40 +00005475 /* Parse the input line into tokens.
5476 */
5477 while( zLine[h] && nArg<ArraySize(azArg) ){
5478 while( IsSpace(zLine[h]) ){ h++; }
5479 if( zLine[h]==0 ) break;
5480 if( zLine[h]=='\'' || zLine[h]=='"' ){
5481 int delim = zLine[h++];
5482 azArg[nArg++] = &zLine[h];
5483 while( zLine[h] && zLine[h]!=delim ){
5484 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5485 h++;
5486 }
5487 if( zLine[h]==delim ){
5488 zLine[h++] = 0;
5489 }
5490 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5491 }else{
5492 azArg[nArg++] = &zLine[h];
5493 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5494 if( zLine[h] ) zLine[h++] = 0;
5495 resolve_backslashes(azArg[nArg-1]);
5496 }
5497 }
5498
5499 /* Process the input line.
5500 */
5501 if( nArg==0 ) return 0; /* no tokens, no error */
5502 n = strlen30(azArg[0]);
5503 c = azArg[0][0];
drh13c20932018-01-10 21:41:55 +00005504 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00005505
5506#ifndef SQLITE_OMIT_AUTHORIZATION
5507 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5508 if( nArg!=2 ){
5509 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5510 rc = 1;
5511 goto meta_command_exit;
5512 }
5513 open_db(p, 0);
5514 if( booleanValue(azArg[1]) ){
5515 sqlite3_set_authorizer(p->db, shellAuth, p);
5516 }else{
5517 sqlite3_set_authorizer(p->db, 0, 0);
5518 }
5519 }else
5520#endif
5521
drhe37c0e12018-01-06 19:19:50 +00005522#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5523 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00005524 open_db(p, 0);
5525 rc = arDotCommand(p, azArg, nArg);
5526 }else
5527#endif
5528
drh2ce15c32017-07-11 13:34:40 +00005529 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5530 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5531 ){
5532 const char *zDestFile = 0;
5533 const char *zDb = 0;
5534 sqlite3 *pDest;
5535 sqlite3_backup *pBackup;
5536 int j;
5537 for(j=1; j<nArg; j++){
5538 const char *z = azArg[j];
5539 if( z[0]=='-' ){
5540 while( z[0]=='-' ) z++;
5541 /* No options to process at this time */
5542 {
5543 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
5544 return 1;
5545 }
5546 }else if( zDestFile==0 ){
5547 zDestFile = azArg[j];
5548 }else if( zDb==0 ){
5549 zDb = zDestFile;
5550 zDestFile = azArg[j];
5551 }else{
5552 raw_printf(stderr, "too many arguments to .backup\n");
5553 return 1;
5554 }
5555 }
5556 if( zDestFile==0 ){
5557 raw_printf(stderr, "missing FILENAME argument on .backup\n");
5558 return 1;
5559 }
5560 if( zDb==0 ) zDb = "main";
5561 rc = sqlite3_open(zDestFile, &pDest);
5562 if( rc!=SQLITE_OK ){
5563 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
5564 sqlite3_close(pDest);
5565 return 1;
5566 }
5567 open_db(p, 0);
5568 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5569 if( pBackup==0 ){
5570 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5571 sqlite3_close(pDest);
5572 return 1;
5573 }
5574 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5575 sqlite3_backup_finish(pBackup);
5576 if( rc==SQLITE_DONE ){
5577 rc = 0;
5578 }else{
5579 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5580 rc = 1;
5581 }
5582 sqlite3_close(pDest);
5583 }else
5584
5585 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5586 if( nArg==2 ){
5587 bail_on_error = booleanValue(azArg[1]);
5588 }else{
5589 raw_printf(stderr, "Usage: .bail on|off\n");
5590 rc = 1;
5591 }
5592 }else
5593
5594 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5595 if( nArg==2 ){
5596 if( booleanValue(azArg[1]) ){
5597 setBinaryMode(p->out, 1);
5598 }else{
5599 setTextMode(p->out, 1);
5600 }
5601 }else{
5602 raw_printf(stderr, "Usage: .binary on|off\n");
5603 rc = 1;
5604 }
5605 }else
5606
5607 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5608 if( nArg==2 ){
5609#if defined(_WIN32) || defined(WIN32)
5610 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5611 rc = !SetCurrentDirectoryW(z);
5612 sqlite3_free(z);
5613#else
5614 rc = chdir(azArg[1]);
5615#endif
5616 if( rc ){
5617 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5618 rc = 1;
5619 }
5620 }else{
5621 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5622 rc = 1;
5623 }
5624 }else
5625
5626 /* The undocumented ".breakpoint" command causes a call to the no-op
5627 ** routine named test_breakpoint().
5628 */
5629 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5630 test_breakpoint();
5631 }else
5632
5633 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5634 if( nArg==2 ){
5635 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
5636 }else{
5637 raw_printf(stderr, "Usage: .changes on|off\n");
5638 rc = 1;
5639 }
5640 }else
5641
5642 /* Cancel output redirection, if it is currently set (by .testcase)
5643 ** Then read the content of the testcase-out.txt file and compare against
5644 ** azArg[1]. If there are differences, report an error and exit.
5645 */
5646 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5647 char *zRes = 0;
5648 output_reset(p);
5649 if( nArg!=2 ){
5650 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
5651 rc = 2;
5652 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
5653 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5654 rc = 2;
5655 }else if( testcase_glob(azArg[1],zRes)==0 ){
5656 utf8_printf(stderr,
5657 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5658 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00005659 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00005660 }else{
5661 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
5662 p->nCheck++;
5663 }
5664 sqlite3_free(zRes);
5665 }else
5666
5667 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5668 if( nArg==2 ){
5669 tryToClone(p, azArg[1]);
5670 }else{
5671 raw_printf(stderr, "Usage: .clone FILENAME\n");
5672 rc = 1;
5673 }
5674 }else
5675
5676 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
5677 ShellState data;
5678 char *zErrMsg = 0;
5679 open_db(p, 0);
5680 memcpy(&data, p, sizeof(data));
5681 data.showHeader = 0;
5682 data.cMode = data.mode = MODE_List;
5683 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
5684 data.cnt = 0;
5685 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5686 callback, &data, &zErrMsg);
5687 if( zErrMsg ){
5688 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5689 sqlite3_free(zErrMsg);
5690 rc = 1;
5691 }
5692 }else
5693
5694 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
5695 rc = shell_dbinfo_command(p, nArg, azArg);
5696 }else
5697
5698 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
5699 const char *zLike = 0;
5700 int i;
5701 int savedShowHeader = p->showHeader;
5702 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
5703 for(i=1; i<nArg; i++){
5704 if( azArg[i][0]=='-' ){
5705 const char *z = azArg[i]+1;
5706 if( z[0]=='-' ) z++;
5707 if( strcmp(z,"preserve-rowids")==0 ){
5708#ifdef SQLITE_OMIT_VIRTUALTABLE
5709 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5710 " with SQLITE_OMIT_VIRTUALTABLE\n");
5711 rc = 1;
5712 goto meta_command_exit;
5713#else
5714 ShellSetFlag(p, SHFLG_PreserveRowid);
5715#endif
5716 }else
5717 if( strcmp(z,"newlines")==0 ){
5718 ShellSetFlag(p, SHFLG_Newlines);
5719 }else
5720 {
5721 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
5722 rc = 1;
5723 goto meta_command_exit;
5724 }
5725 }else if( zLike ){
5726 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
5727 "?--newlines? ?LIKE-PATTERN?\n");
5728 rc = 1;
5729 goto meta_command_exit;
5730 }else{
5731 zLike = azArg[i];
5732 }
5733 }
5734 open_db(p, 0);
5735 /* When playing back a "dump", the content might appear in an order
5736 ** which causes immediate foreign key constraints to be violated.
5737 ** So disable foreign-key constraint enforcement to prevent problems. */
5738 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
5739 raw_printf(p->out, "BEGIN TRANSACTION;\n");
5740 p->writableSchema = 0;
5741 p->showHeader = 0;
5742 /* Set writable_schema=ON since doing so forces SQLite to initialize
5743 ** as much of the schema as it can even if the sqlite_master table is
5744 ** corrupt. */
5745 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5746 p->nErr = 0;
5747 if( zLike==0 ){
5748 run_schema_dump_query(p,
5749 "SELECT name, type, sql FROM sqlite_master "
5750 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5751 );
5752 run_schema_dump_query(p,
5753 "SELECT name, type, sql FROM sqlite_master "
5754 "WHERE name=='sqlite_sequence'"
5755 );
5756 run_table_dump_query(p,
5757 "SELECT sql FROM sqlite_master "
5758 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5759 );
5760 }else{
5761 char *zSql;
5762 zSql = sqlite3_mprintf(
5763 "SELECT name, type, sql FROM sqlite_master "
5764 "WHERE tbl_name LIKE %Q AND type=='table'"
5765 " AND sql NOT NULL", zLike);
5766 run_schema_dump_query(p,zSql);
5767 sqlite3_free(zSql);
5768 zSql = sqlite3_mprintf(
5769 "SELECT sql FROM sqlite_master "
5770 "WHERE sql NOT NULL"
5771 " AND type IN ('index','trigger','view')"
5772 " AND tbl_name LIKE %Q", zLike);
5773 run_table_dump_query(p, zSql, 0);
5774 sqlite3_free(zSql);
5775 }
5776 if( p->writableSchema ){
5777 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
5778 p->writableSchema = 0;
5779 }
5780 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5781 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
5782 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5783 p->showHeader = savedShowHeader;
5784 }else
5785
5786 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5787 if( nArg==2 ){
5788 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
5789 }else{
5790 raw_printf(stderr, "Usage: .echo on|off\n");
5791 rc = 1;
5792 }
5793 }else
5794
5795 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5796 if( nArg==2 ){
5797 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00005798 p->autoEQP = AUTOEQP_full;
5799 }else if( strcmp(azArg[1],"trigger")==0 ){
5800 p->autoEQP = AUTOEQP_trigger;
drh2ce15c32017-07-11 13:34:40 +00005801 }else{
mistachkinb71aa092018-01-23 00:05:18 +00005802 p->autoEQP = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00005803 }
5804 }else{
drhada70452017-12-21 21:02:27 +00005805 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00005806 rc = 1;
5807 }
5808 }else
5809
5810 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
5811 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
5812 rc = 2;
5813 }else
5814
5815 /* The ".explain" command is automatic now. It is largely pointless. It
5816 ** retained purely for backwards compatibility */
5817 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
5818 int val = 1;
5819 if( nArg>=2 ){
5820 if( strcmp(azArg[1],"auto")==0 ){
5821 val = 99;
5822 }else{
5823 val = booleanValue(azArg[1]);
5824 }
5825 }
5826 if( val==1 && p->mode!=MODE_Explain ){
5827 p->normalMode = p->mode;
5828 p->mode = MODE_Explain;
5829 p->autoExplain = 0;
5830 }else if( val==0 ){
5831 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5832 p->autoExplain = 0;
5833 }else if( val==99 ){
5834 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5835 p->autoExplain = 1;
5836 }
5837 }else
5838
dan6b046be2018-01-09 15:25:55 +00005839#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00005840 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
5841 open_db(p, 0);
5842 expertDotCommand(p, azArg, nArg);
5843 }else
dan6b046be2018-01-09 15:25:55 +00005844#endif
dan43efc182017-12-19 17:42:13 +00005845
drh2ce15c32017-07-11 13:34:40 +00005846 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
5847 ShellState data;
5848 char *zErrMsg = 0;
5849 int doStats = 0;
5850 memcpy(&data, p, sizeof(data));
5851 data.showHeader = 0;
5852 data.cMode = data.mode = MODE_Semi;
5853 if( nArg==2 && optionMatch(azArg[1], "indent") ){
5854 data.cMode = data.mode = MODE_Pretty;
5855 nArg = 1;
5856 }
5857 if( nArg!=1 ){
5858 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
5859 rc = 1;
5860 goto meta_command_exit;
5861 }
5862 open_db(p, 0);
5863 rc = sqlite3_exec(p->db,
5864 "SELECT sql FROM"
5865 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5866 " FROM sqlite_master UNION ALL"
5867 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5868 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
5869 "ORDER BY rowid",
5870 callback, &data, &zErrMsg
5871 );
5872 if( rc==SQLITE_OK ){
5873 sqlite3_stmt *pStmt;
5874 rc = sqlite3_prepare_v2(p->db,
5875 "SELECT rowid FROM sqlite_master"
5876 " WHERE name GLOB 'sqlite_stat[134]'",
5877 -1, &pStmt, 0);
5878 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5879 sqlite3_finalize(pStmt);
5880 }
5881 if( doStats==0 ){
5882 raw_printf(p->out, "/* No STAT tables available */\n");
5883 }else{
5884 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5885 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5886 callback, &data, &zErrMsg);
5887 data.cMode = data.mode = MODE_Insert;
5888 data.zDestTable = "sqlite_stat1";
drha10b9992018-03-09 15:24:33 +00005889 shell_exec(p, "SELECT * FROM sqlite_stat1", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00005890 data.zDestTable = "sqlite_stat3";
drha10b9992018-03-09 15:24:33 +00005891 shell_exec(p, "SELECT * FROM sqlite_stat3", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00005892 data.zDestTable = "sqlite_stat4";
drha10b9992018-03-09 15:24:33 +00005893 shell_exec(p, "SELECT * FROM sqlite_stat4", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00005894 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5895 }
5896 }else
5897
5898 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5899 if( nArg==2 ){
5900 p->showHeader = booleanValue(azArg[1]);
5901 }else{
5902 raw_printf(stderr, "Usage: .headers on|off\n");
5903 rc = 1;
5904 }
5905 }else
5906
5907 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
5908 utf8_printf(p->out, "%s", zHelp);
5909 }else
5910
5911 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
5912 char *zTable; /* Insert data into this table */
5913 char *zFile; /* Name of file to extra content from */
5914 sqlite3_stmt *pStmt = NULL; /* A statement */
5915 int nCol; /* Number of columns in the table */
5916 int nByte; /* Number of bytes in an SQL string */
5917 int i, j; /* Loop counters */
5918 int needCommit; /* True to COMMIT or ROLLBACK at end */
5919 int nSep; /* Number of bytes in p->colSeparator[] */
5920 char *zSql; /* An SQL statement */
5921 ImportCtx sCtx; /* Reader context */
5922 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5923 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
5924
5925 if( nArg!=3 ){
5926 raw_printf(stderr, "Usage: .import FILE TABLE\n");
5927 goto meta_command_exit;
5928 }
5929 zFile = azArg[1];
5930 zTable = azArg[2];
5931 seenInterrupt = 0;
5932 memset(&sCtx, 0, sizeof(sCtx));
5933 open_db(p, 0);
5934 nSep = strlen30(p->colSeparator);
5935 if( nSep==0 ){
5936 raw_printf(stderr,
5937 "Error: non-null column separator required for import\n");
5938 return 1;
5939 }
5940 if( nSep>1 ){
5941 raw_printf(stderr, "Error: multi-character column separators not allowed"
5942 " for import\n");
5943 return 1;
5944 }
5945 nSep = strlen30(p->rowSeparator);
5946 if( nSep==0 ){
5947 raw_printf(stderr, "Error: non-null row separator required for import\n");
5948 return 1;
5949 }
5950 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5951 /* When importing CSV (only), if the row separator is set to the
5952 ** default output row separator, change it to the default input
5953 ** row separator. This avoids having to maintain different input
5954 ** and output row separators. */
5955 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5956 nSep = strlen30(p->rowSeparator);
5957 }
5958 if( nSep>1 ){
5959 raw_printf(stderr, "Error: multi-character row separators not allowed"
5960 " for import\n");
5961 return 1;
5962 }
5963 sCtx.zFile = zFile;
5964 sCtx.nLine = 1;
5965 if( sCtx.zFile[0]=='|' ){
5966#ifdef SQLITE_OMIT_POPEN
5967 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
5968 return 1;
5969#else
5970 sCtx.in = popen(sCtx.zFile+1, "r");
5971 sCtx.zFile = "<pipe>";
5972 xCloser = pclose;
5973#endif
5974 }else{
5975 sCtx.in = fopen(sCtx.zFile, "rb");
5976 xCloser = fclose;
5977 }
5978 if( p->mode==MODE_Ascii ){
5979 xRead = ascii_read_one_field;
5980 }else{
5981 xRead = csv_read_one_field;
5982 }
5983 if( sCtx.in==0 ){
5984 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5985 return 1;
5986 }
5987 sCtx.cColSep = p->colSeparator[0];
5988 sCtx.cRowSep = p->rowSeparator[0];
5989 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
5990 if( zSql==0 ){
5991 raw_printf(stderr, "Error: out of memory\n");
5992 xCloser(sCtx.in);
5993 return 1;
5994 }
5995 nByte = strlen30(zSql);
5996 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5997 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
5998 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
5999 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
6000 char cSep = '(';
6001 while( xRead(&sCtx) ){
6002 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
6003 cSep = ',';
6004 if( sCtx.cTerm!=sCtx.cColSep ) break;
6005 }
6006 if( cSep=='(' ){
6007 sqlite3_free(zCreate);
6008 sqlite3_free(sCtx.z);
6009 xCloser(sCtx.in);
6010 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
6011 return 1;
6012 }
6013 zCreate = sqlite3_mprintf("%z\n)", zCreate);
6014 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
6015 sqlite3_free(zCreate);
6016 if( rc ){
6017 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
6018 sqlite3_errmsg(p->db));
6019 sqlite3_free(sCtx.z);
6020 xCloser(sCtx.in);
6021 return 1;
6022 }
6023 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6024 }
6025 sqlite3_free(zSql);
6026 if( rc ){
6027 if (pStmt) sqlite3_finalize(pStmt);
6028 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
6029 xCloser(sCtx.in);
6030 return 1;
6031 }
6032 nCol = sqlite3_column_count(pStmt);
6033 sqlite3_finalize(pStmt);
6034 pStmt = 0;
6035 if( nCol==0 ) return 0; /* no columns, no error */
6036 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
6037 if( zSql==0 ){
6038 raw_printf(stderr, "Error: out of memory\n");
6039 xCloser(sCtx.in);
6040 return 1;
6041 }
6042 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
6043 j = strlen30(zSql);
6044 for(i=1; i<nCol; i++){
6045 zSql[j++] = ',';
6046 zSql[j++] = '?';
6047 }
6048 zSql[j++] = ')';
6049 zSql[j] = 0;
6050 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6051 sqlite3_free(zSql);
6052 if( rc ){
6053 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6054 if (pStmt) sqlite3_finalize(pStmt);
6055 xCloser(sCtx.in);
6056 return 1;
6057 }
6058 needCommit = sqlite3_get_autocommit(p->db);
6059 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
6060 do{
6061 int startLine = sCtx.nLine;
6062 for(i=0; i<nCol; i++){
6063 char *z = xRead(&sCtx);
6064 /*
6065 ** Did we reach end-of-file before finding any columns?
6066 ** If so, stop instead of NULL filling the remaining columns.
6067 */
6068 if( z==0 && i==0 ) break;
6069 /*
6070 ** Did we reach end-of-file OR end-of-line before finding any
6071 ** columns in ASCII mode? If so, stop instead of NULL filling
6072 ** the remaining columns.
6073 */
6074 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
6075 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
6076 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
6077 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6078 "filling the rest with NULL\n",
6079 sCtx.zFile, startLine, nCol, i+1);
6080 i += 2;
6081 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
6082 }
6083 }
6084 if( sCtx.cTerm==sCtx.cColSep ){
6085 do{
6086 xRead(&sCtx);
6087 i++;
6088 }while( sCtx.cTerm==sCtx.cColSep );
6089 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6090 "extras ignored\n",
6091 sCtx.zFile, startLine, nCol, i);
6092 }
6093 if( i>=nCol ){
6094 sqlite3_step(pStmt);
6095 rc = sqlite3_reset(pStmt);
6096 if( rc!=SQLITE_OK ){
6097 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
6098 startLine, sqlite3_errmsg(p->db));
6099 }
6100 }
6101 }while( sCtx.cTerm!=EOF );
6102
6103 xCloser(sCtx.in);
6104 sqlite3_free(sCtx.z);
6105 sqlite3_finalize(pStmt);
6106 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
6107 }else
6108
6109#ifndef SQLITE_UNTESTABLE
6110 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
6111 char *zSql;
6112 char *zCollist = 0;
6113 sqlite3_stmt *pStmt;
6114 int tnum = 0;
6115 int i;
6116 if( nArg!=3 ){
6117 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
6118 rc = 1;
6119 goto meta_command_exit;
6120 }
6121 open_db(p, 0);
6122 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6123 " WHERE name='%q' AND type='index'", azArg[1]);
6124 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6125 sqlite3_free(zSql);
6126 if( sqlite3_step(pStmt)==SQLITE_ROW ){
6127 tnum = sqlite3_column_int(pStmt, 0);
6128 }
6129 sqlite3_finalize(pStmt);
6130 if( tnum==0 ){
6131 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
6132 rc = 1;
6133 goto meta_command_exit;
6134 }
6135 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
6136 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6137 sqlite3_free(zSql);
6138 i = 0;
6139 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6140 char zLabel[20];
6141 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
6142 i++;
6143 if( zCol==0 ){
6144 if( sqlite3_column_int(pStmt,1)==-1 ){
6145 zCol = "_ROWID_";
6146 }else{
6147 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
6148 zCol = zLabel;
6149 }
6150 }
6151 if( zCollist==0 ){
6152 zCollist = sqlite3_mprintf("\"%w\"", zCol);
6153 }else{
6154 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
6155 }
6156 }
6157 sqlite3_finalize(pStmt);
6158 zSql = sqlite3_mprintf(
6159 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6160 azArg[2], zCollist, zCollist);
6161 sqlite3_free(zCollist);
6162 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
6163 if( rc==SQLITE_OK ){
6164 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
6165 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
6166 if( rc ){
6167 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
6168 }else{
6169 utf8_printf(stdout, "%s;\n", zSql);
6170 raw_printf(stdout,
6171 "WARNING: writing to an imposter table will corrupt the index!\n"
6172 );
6173 }
6174 }else{
6175 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
6176 rc = 1;
6177 }
6178 sqlite3_free(zSql);
6179 }else
6180#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6181
6182#ifdef SQLITE_ENABLE_IOTRACE
6183 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
6184 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
6185 if( iotrace && iotrace!=stdout ) fclose(iotrace);
6186 iotrace = 0;
6187 if( nArg<2 ){
6188 sqlite3IoTrace = 0;
6189 }else if( strcmp(azArg[1], "-")==0 ){
6190 sqlite3IoTrace = iotracePrintf;
6191 iotrace = stdout;
6192 }else{
6193 iotrace = fopen(azArg[1], "w");
6194 if( iotrace==0 ){
6195 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
6196 sqlite3IoTrace = 0;
6197 rc = 1;
6198 }else{
6199 sqlite3IoTrace = iotracePrintf;
6200 }
6201 }
6202 }else
6203#endif
6204
6205 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
6206 static const struct {
6207 const char *zLimitName; /* Name of a limit */
6208 int limitCode; /* Integer code for that limit */
6209 } aLimit[] = {
6210 { "length", SQLITE_LIMIT_LENGTH },
6211 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
6212 { "column", SQLITE_LIMIT_COLUMN },
6213 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
6214 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
6215 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
6216 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
6217 { "attached", SQLITE_LIMIT_ATTACHED },
6218 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
6219 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
6220 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
6221 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
6222 };
6223 int i, n2;
6224 open_db(p, 0);
6225 if( nArg==1 ){
6226 for(i=0; i<ArraySize(aLimit); i++){
6227 printf("%20s %d\n", aLimit[i].zLimitName,
6228 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
6229 }
6230 }else if( nArg>3 ){
6231 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
6232 rc = 1;
6233 goto meta_command_exit;
6234 }else{
6235 int iLimit = -1;
6236 n2 = strlen30(azArg[1]);
6237 for(i=0; i<ArraySize(aLimit); i++){
6238 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
6239 if( iLimit<0 ){
6240 iLimit = i;
6241 }else{
6242 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
6243 rc = 1;
6244 goto meta_command_exit;
6245 }
6246 }
6247 }
6248 if( iLimit<0 ){
6249 utf8_printf(stderr, "unknown limit: \"%s\"\n"
6250 "enter \".limits\" with no arguments for a list.\n",
6251 azArg[1]);
6252 rc = 1;
6253 goto meta_command_exit;
6254 }
6255 if( nArg==3 ){
6256 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
6257 (int)integerValue(azArg[2]));
6258 }
6259 printf("%20s %d\n", aLimit[iLimit].zLimitName,
6260 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
6261 }
6262 }else
6263
6264 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
6265 open_db(p, 0);
6266 lintDotCommand(p, azArg, nArg);
6267 }else
6268
6269#ifndef SQLITE_OMIT_LOAD_EXTENSION
6270 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
6271 const char *zFile, *zProc;
6272 char *zErrMsg = 0;
6273 if( nArg<2 ){
6274 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
6275 rc = 1;
6276 goto meta_command_exit;
6277 }
6278 zFile = azArg[1];
6279 zProc = nArg>=3 ? azArg[2] : 0;
6280 open_db(p, 0);
6281 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
6282 if( rc!=SQLITE_OK ){
6283 utf8_printf(stderr, "Error: %s\n", zErrMsg);
6284 sqlite3_free(zErrMsg);
6285 rc = 1;
6286 }
6287 }else
6288#endif
6289
6290 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
6291 if( nArg!=2 ){
6292 raw_printf(stderr, "Usage: .log FILENAME\n");
6293 rc = 1;
6294 }else{
6295 const char *zFile = azArg[1];
6296 output_file_close(p->pLog);
drha92a01a2018-01-10 22:15:37 +00006297 p->pLog = output_file_open(zFile, 0);
drh2ce15c32017-07-11 13:34:40 +00006298 }
6299 }else
6300
6301 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6302 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00006303 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00006304 int c2 = zMode[0];
6305 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
6306 p->mode = MODE_Line;
6307 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6308 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
6309 p->mode = MODE_Column;
6310 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6311 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
6312 p->mode = MODE_List;
6313 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6314 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6315 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
6316 p->mode = MODE_Html;
6317 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
6318 p->mode = MODE_Tcl;
6319 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
6320 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6321 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
6322 p->mode = MODE_Csv;
6323 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6324 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6325 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
6326 p->mode = MODE_List;
6327 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
6328 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
6329 p->mode = MODE_Insert;
6330 set_table_name(p, nArg>=3 ? azArg[2] : "table");
6331 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6332 p->mode = MODE_Quote;
6333 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6334 p->mode = MODE_Ascii;
6335 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6336 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
6337 }else if( nArg==1 ){
6338 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6339 }else{
6340 raw_printf(stderr, "Error: mode should be one of: "
6341 "ascii column csv html insert line list quote tabs tcl\n");
6342 rc = 1;
6343 }
6344 p->cMode = p->mode;
6345 }else
6346
6347 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6348 if( nArg==2 ){
6349 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6350 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
6351 }else{
6352 raw_printf(stderr, "Usage: .nullvalue STRING\n");
6353 rc = 1;
6354 }
6355 }else
6356
6357 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
6358 char *zNewFilename; /* Name of the database file to open */
6359 int iName = 1; /* Index in azArg[] of the filename */
6360 int newFlag = 0; /* True to delete file before opening */
6361 /* Close the existing database */
6362 session_close_all(p);
6363 sqlite3_close(p->db);
6364 p->db = 0;
6365 p->zDbFilename = 0;
6366 sqlite3_free(p->zFreeOnClose);
6367 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00006368 p->openMode = SHELL_OPEN_UNSPEC;
drh2ce15c32017-07-11 13:34:40 +00006369 /* Check for command-line arguments */
6370 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6371 const char *z = azArg[iName];
6372 if( optionMatch(z,"new") ){
6373 newFlag = 1;
drh3baed312018-03-08 18:14:41 +00006374#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00006375 }else if( optionMatch(z, "zip") ){
6376 p->openMode = SHELL_OPEN_ZIPFILE;
6377#endif
6378 }else if( optionMatch(z, "append") ){
6379 p->openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00006380 }else if( optionMatch(z, "readonly") ){
6381 p->openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +00006382 }else if( z[0]=='-' ){
6383 utf8_printf(stderr, "unknown option: %s\n", z);
6384 rc = 1;
6385 goto meta_command_exit;
6386 }
6387 }
6388 /* If a filename is specified, try to open it first */
6389 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
6390 if( zNewFilename ){
6391 if( newFlag ) shellDeleteFile(zNewFilename);
6392 p->zDbFilename = zNewFilename;
6393 open_db(p, 1);
6394 if( p->db==0 ){
6395 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6396 sqlite3_free(zNewFilename);
6397 }else{
6398 p->zFreeOnClose = zNewFilename;
6399 }
6400 }
6401 if( p->db==0 ){
6402 /* As a fall-back open a TEMP database */
6403 p->zDbFilename = 0;
6404 open_db(p, 0);
6405 }
6406 }else
6407
drh13c20932018-01-10 21:41:55 +00006408 if( (c=='o'
6409 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
6410 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
drh2ce15c32017-07-11 13:34:40 +00006411 ){
6412 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
drha92a01a2018-01-10 22:15:37 +00006413 int bTxtMode = 0;
drh13c20932018-01-10 21:41:55 +00006414 if( azArg[0][0]=='e' ){
6415 /* Transform the ".excel" command into ".once -x" */
6416 nArg = 2;
6417 azArg[0] = "once";
6418 zFile = azArg[1] = "-x";
6419 n = 4;
6420 }
drh2ce15c32017-07-11 13:34:40 +00006421 if( nArg>2 ){
drh13c20932018-01-10 21:41:55 +00006422 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00006423 rc = 1;
6424 goto meta_command_exit;
6425 }
6426 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6427 if( nArg<2 ){
drh13c20932018-01-10 21:41:55 +00006428 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
drh2ce15c32017-07-11 13:34:40 +00006429 rc = 1;
6430 goto meta_command_exit;
6431 }
6432 p->outCount = 2;
6433 }else{
6434 p->outCount = 0;
6435 }
6436 output_reset(p);
drh13c20932018-01-10 21:41:55 +00006437 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
drh04a28c32018-01-31 01:38:44 +00006438#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00006439 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
drh3c484e82018-01-10 22:27:21 +00006440 p->doXdgOpen = 1;
6441 outputModePush(p);
drh13c20932018-01-10 21:41:55 +00006442 if( zFile[1]=='x' ){
6443 newTempFile(p, "csv");
6444 p->mode = MODE_Csv;
6445 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6446 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6447 }else{
6448 newTempFile(p, "txt");
drha92a01a2018-01-10 22:15:37 +00006449 bTxtMode = 1;
drh13c20932018-01-10 21:41:55 +00006450 }
6451 zFile = p->zTempFile;
6452 }
drh04a28c32018-01-31 01:38:44 +00006453#endif /* SQLITE_NOHAVE_SYSTEM */
drh2ce15c32017-07-11 13:34:40 +00006454 if( zFile[0]=='|' ){
6455#ifdef SQLITE_OMIT_POPEN
6456 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6457 rc = 1;
6458 p->out = stdout;
6459#else
6460 p->out = popen(zFile + 1, "w");
6461 if( p->out==0 ){
6462 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
6463 p->out = stdout;
6464 rc = 1;
6465 }else{
6466 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6467 }
6468#endif
6469 }else{
drha92a01a2018-01-10 22:15:37 +00006470 p->out = output_file_open(zFile, bTxtMode);
drh2ce15c32017-07-11 13:34:40 +00006471 if( p->out==0 ){
6472 if( strcmp(zFile,"off")!=0 ){
6473 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
6474 }
6475 p->out = stdout;
6476 rc = 1;
6477 } else {
6478 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6479 }
6480 }
6481 }else
6482
6483 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6484 int i;
6485 for(i=1; i<nArg; i++){
6486 if( i>1 ) raw_printf(p->out, " ");
6487 utf8_printf(p->out, "%s", azArg[i]);
6488 }
6489 raw_printf(p->out, "\n");
6490 }else
6491
6492 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
6493 if( nArg >= 2) {
6494 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6495 }
6496 if( nArg >= 3) {
6497 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6498 }
6499 }else
6500
6501 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
6502 rc = 2;
6503 }else
6504
6505 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6506 FILE *alt;
6507 if( nArg!=2 ){
6508 raw_printf(stderr, "Usage: .read FILE\n");
6509 rc = 1;
6510 goto meta_command_exit;
6511 }
6512 alt = fopen(azArg[1], "rb");
6513 if( alt==0 ){
6514 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6515 rc = 1;
6516 }else{
6517 rc = process_input(p, alt);
6518 fclose(alt);
6519 }
6520 }else
6521
6522 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
6523 const char *zSrcFile;
6524 const char *zDb;
6525 sqlite3 *pSrc;
6526 sqlite3_backup *pBackup;
6527 int nTimeout = 0;
6528
6529 if( nArg==2 ){
6530 zSrcFile = azArg[1];
6531 zDb = "main";
6532 }else if( nArg==3 ){
6533 zSrcFile = azArg[2];
6534 zDb = azArg[1];
6535 }else{
6536 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
6537 rc = 1;
6538 goto meta_command_exit;
6539 }
6540 rc = sqlite3_open(zSrcFile, &pSrc);
6541 if( rc!=SQLITE_OK ){
6542 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
6543 sqlite3_close(pSrc);
6544 return 1;
6545 }
6546 open_db(p, 0);
6547 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6548 if( pBackup==0 ){
6549 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6550 sqlite3_close(pSrc);
6551 return 1;
6552 }
6553 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6554 || rc==SQLITE_BUSY ){
6555 if( rc==SQLITE_BUSY ){
6556 if( nTimeout++ >= 3 ) break;
6557 sqlite3_sleep(100);
6558 }
6559 }
6560 sqlite3_backup_finish(pBackup);
6561 if( rc==SQLITE_DONE ){
6562 rc = 0;
6563 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
6564 raw_printf(stderr, "Error: source database is busy\n");
6565 rc = 1;
6566 }else{
6567 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6568 rc = 1;
6569 }
6570 sqlite3_close(pSrc);
6571 }else
6572
drh2ce15c32017-07-11 13:34:40 +00006573 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6574 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00006575 p->scanstatsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00006576#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6577 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
6578#endif
6579 }else{
6580 raw_printf(stderr, "Usage: .scanstats on|off\n");
6581 rc = 1;
6582 }
6583 }else
6584
6585 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
6586 ShellText sSelect;
6587 ShellState data;
6588 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00006589 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00006590 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00006591 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00006592 int bDebug = 0;
6593 int ii;
drh2ce15c32017-07-11 13:34:40 +00006594
6595 open_db(p, 0);
6596 memcpy(&data, p, sizeof(data));
6597 data.showHeader = 0;
6598 data.cMode = data.mode = MODE_Semi;
6599 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00006600 for(ii=1; ii<nArg; ii++){
6601 if( optionMatch(azArg[ii],"indent") ){
6602 data.cMode = data.mode = MODE_Pretty;
6603 }else if( optionMatch(azArg[ii],"debug") ){
6604 bDebug = 1;
6605 }else if( zName==0 ){
6606 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00006607 }else{
drhceba7922018-01-01 21:28:25 +00006608 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6609 rc = 1;
6610 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00006611 }
drh2ce15c32017-07-11 13:34:40 +00006612 }
drhceba7922018-01-01 21:28:25 +00006613 if( zName!=0 ){
drh667a2a22018-01-02 00:04:37 +00006614 int isMaster = sqlite3_strlike(zName, "sqlite_master", 0)==0;
6615 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master",0)==0 ){
drh2ce15c32017-07-11 13:34:40 +00006616 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00006617 new_argv[0] = sqlite3_mprintf(
6618 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00006619 " type text,\n"
6620 " name text,\n"
6621 " tbl_name text,\n"
6622 " rootpage integer,\n"
6623 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00006624 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00006625 new_argv[1] = 0;
6626 new_colv[0] = "sql";
6627 new_colv[1] = 0;
6628 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00006629 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00006630 }
drh2ce15c32017-07-11 13:34:40 +00006631 }
6632 if( zDiv ){
6633 sqlite3_stmt *pStmt = 0;
6634 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6635 -1, &pStmt, 0);
6636 if( rc ){
6637 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6638 sqlite3_finalize(pStmt);
6639 rc = 1;
6640 goto meta_command_exit;
6641 }
6642 appendText(&sSelect, "SELECT sql FROM", 0);
6643 iSchema = 0;
6644 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6645 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6646 char zScNum[30];
6647 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6648 appendText(&sSelect, zDiv, 0);
6649 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00006650 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
6651 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00006652 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00006653 }else{
drhceba7922018-01-01 21:28:25 +00006654 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00006655 }
drhceba7922018-01-01 21:28:25 +00006656 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6657 appendText(&sSelect, zScNum, 0);
6658 appendText(&sSelect, " AS snum, ", 0);
6659 appendText(&sSelect, zDb, '\'');
6660 appendText(&sSelect, " AS sname FROM ", 0);
6661 appendText(&sSelect, zDb, '"');
6662 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00006663 }
6664 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00006665#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00006666 if( zName ){
6667 appendText(&sSelect,
6668 " UNION ALL SELECT shell_module_schema(name),"
6669 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6670 }
drhcde7b772018-01-02 12:50:40 +00006671#endif
drh2ce15c32017-07-11 13:34:40 +00006672 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00006673 if( zName ){
6674 char *zQarg = sqlite3_mprintf("%Q", zName);
6675 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00006676 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6677 }else{
6678 appendText(&sSelect, "lower(tbl_name)", 0);
6679 }
drhceba7922018-01-01 21:28:25 +00006680 appendText(&sSelect, strchr(zName, '*') ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00006681 appendText(&sSelect, zQarg, 0);
6682 appendText(&sSelect, " AND ", 0);
6683 sqlite3_free(zQarg);
6684 }
6685 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6686 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00006687 if( bDebug ){
6688 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
6689 }else{
6690 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6691 }
drh2ce15c32017-07-11 13:34:40 +00006692 freeText(&sSelect);
6693 }
6694 if( zErrMsg ){
6695 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6696 sqlite3_free(zErrMsg);
6697 rc = 1;
6698 }else if( rc != SQLITE_OK ){
6699 raw_printf(stderr,"Error: querying schema information\n");
6700 rc = 1;
6701 }else{
6702 rc = 0;
6703 }
6704 }else
6705
6706#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6707 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
6708 sqlite3SelectTrace = (int)integerValue(azArg[1]);
6709 }else
6710#endif
6711
6712#if defined(SQLITE_ENABLE_SESSION)
6713 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
6714 OpenSession *pSession = &p->aSession[0];
6715 char **azCmd = &azArg[1];
6716 int iSes = 0;
6717 int nCmd = nArg - 1;
6718 int i;
6719 if( nArg<=1 ) goto session_syntax_error;
6720 open_db(p, 0);
6721 if( nArg>=3 ){
6722 for(iSes=0; iSes<p->nSession; iSes++){
6723 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
6724 }
6725 if( iSes<p->nSession ){
6726 pSession = &p->aSession[iSes];
6727 azCmd++;
6728 nCmd--;
6729 }else{
6730 pSession = &p->aSession[0];
6731 iSes = 0;
6732 }
6733 }
6734
6735 /* .session attach TABLE
6736 ** Invoke the sqlite3session_attach() interface to attach a particular
6737 ** table so that it is never filtered.
6738 */
6739 if( strcmp(azCmd[0],"attach")==0 ){
6740 if( nCmd!=2 ) goto session_syntax_error;
6741 if( pSession->p==0 ){
6742 session_not_open:
6743 raw_printf(stderr, "ERROR: No sessions are open\n");
6744 }else{
6745 rc = sqlite3session_attach(pSession->p, azCmd[1]);
6746 if( rc ){
6747 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
6748 rc = 0;
6749 }
6750 }
6751 }else
6752
6753 /* .session changeset FILE
6754 ** .session patchset FILE
6755 ** Write a changeset or patchset into a file. The file is overwritten.
6756 */
6757 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
6758 FILE *out = 0;
6759 if( nCmd!=2 ) goto session_syntax_error;
6760 if( pSession->p==0 ) goto session_not_open;
6761 out = fopen(azCmd[1], "wb");
6762 if( out==0 ){
6763 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
6764 }else{
6765 int szChng;
6766 void *pChng;
6767 if( azCmd[0][0]=='c' ){
6768 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
6769 }else{
6770 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
6771 }
6772 if( rc ){
6773 printf("Error: error code %d\n", rc);
6774 rc = 0;
6775 }
6776 if( pChng
6777 && fwrite(pChng, szChng, 1, out)!=1 ){
6778 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
6779 szChng);
6780 }
6781 sqlite3_free(pChng);
6782 fclose(out);
6783 }
6784 }else
6785
6786 /* .session close
6787 ** Close the identified session
6788 */
6789 if( strcmp(azCmd[0], "close")==0 ){
6790 if( nCmd!=1 ) goto session_syntax_error;
6791 if( p->nSession ){
6792 session_close(pSession);
6793 p->aSession[iSes] = p->aSession[--p->nSession];
6794 }
6795 }else
6796
6797 /* .session enable ?BOOLEAN?
6798 ** Query or set the enable flag
6799 */
6800 if( strcmp(azCmd[0], "enable")==0 ){
6801 int ii;
6802 if( nCmd>2 ) goto session_syntax_error;
6803 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6804 if( p->nSession ){
6805 ii = sqlite3session_enable(pSession->p, ii);
6806 utf8_printf(p->out, "session %s enable flag = %d\n",
6807 pSession->zName, ii);
6808 }
6809 }else
6810
6811 /* .session filter GLOB ....
6812 ** Set a list of GLOB patterns of table names to be excluded.
6813 */
6814 if( strcmp(azCmd[0], "filter")==0 ){
6815 int ii, nByte;
6816 if( nCmd<2 ) goto session_syntax_error;
6817 if( p->nSession ){
6818 for(ii=0; ii<pSession->nFilter; ii++){
6819 sqlite3_free(pSession->azFilter[ii]);
6820 }
6821 sqlite3_free(pSession->azFilter);
6822 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6823 pSession->azFilter = sqlite3_malloc( nByte );
6824 if( pSession->azFilter==0 ){
6825 raw_printf(stderr, "Error: out or memory\n");
6826 exit(1);
6827 }
6828 for(ii=1; ii<nCmd; ii++){
6829 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
6830 }
6831 pSession->nFilter = ii-1;
6832 }
6833 }else
6834
6835 /* .session indirect ?BOOLEAN?
6836 ** Query or set the indirect flag
6837 */
6838 if( strcmp(azCmd[0], "indirect")==0 ){
6839 int ii;
6840 if( nCmd>2 ) goto session_syntax_error;
6841 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6842 if( p->nSession ){
6843 ii = sqlite3session_indirect(pSession->p, ii);
6844 utf8_printf(p->out, "session %s indirect flag = %d\n",
6845 pSession->zName, ii);
6846 }
6847 }else
6848
6849 /* .session isempty
6850 ** Determine if the session is empty
6851 */
6852 if( strcmp(azCmd[0], "isempty")==0 ){
6853 int ii;
6854 if( nCmd!=1 ) goto session_syntax_error;
6855 if( p->nSession ){
6856 ii = sqlite3session_isempty(pSession->p);
6857 utf8_printf(p->out, "session %s isempty flag = %d\n",
6858 pSession->zName, ii);
6859 }
6860 }else
6861
6862 /* .session list
6863 ** List all currently open sessions
6864 */
6865 if( strcmp(azCmd[0],"list")==0 ){
6866 for(i=0; i<p->nSession; i++){
6867 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
6868 }
6869 }else
6870
6871 /* .session open DB NAME
6872 ** Open a new session called NAME on the attached database DB.
6873 ** DB is normally "main".
6874 */
6875 if( strcmp(azCmd[0],"open")==0 ){
6876 char *zName;
6877 if( nCmd!=3 ) goto session_syntax_error;
6878 zName = azCmd[2];
6879 if( zName[0]==0 ) goto session_syntax_error;
6880 for(i=0; i<p->nSession; i++){
6881 if( strcmp(p->aSession[i].zName,zName)==0 ){
6882 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
6883 goto meta_command_exit;
6884 }
6885 }
6886 if( p->nSession>=ArraySize(p->aSession) ){
6887 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
6888 goto meta_command_exit;
6889 }
6890 pSession = &p->aSession[p->nSession];
6891 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
6892 if( rc ){
6893 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
6894 rc = 0;
6895 goto meta_command_exit;
6896 }
6897 pSession->nFilter = 0;
6898 sqlite3session_table_filter(pSession->p, session_filter, pSession);
6899 p->nSession++;
6900 pSession->zName = sqlite3_mprintf("%s", zName);
6901 }else
6902 /* If no command name matches, show a syntax error */
6903 session_syntax_error:
6904 session_help(p);
6905 }else
6906#endif
6907
6908#ifdef SQLITE_DEBUG
6909 /* Undocumented commands for internal testing. Subject to change
6910 ** without notice. */
6911 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
6912 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
6913 int i, v;
6914 for(i=1; i<nArg; i++){
6915 v = booleanValue(azArg[i]);
6916 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
6917 }
6918 }
6919 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
6920 int i; sqlite3_int64 v;
6921 for(i=1; i<nArg; i++){
6922 char zBuf[200];
6923 v = integerValue(azArg[i]);
6924 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
6925 utf8_printf(p->out, "%s", zBuf);
6926 }
6927 }
6928 }else
6929#endif
6930
6931 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6932 int bIsInit = 0; /* True to initialize the SELFTEST table */
6933 int bVerbose = 0; /* Verbose output */
6934 int bSelftestExists; /* True if SELFTEST already exists */
6935 int i, k; /* Loop counters */
6936 int nTest = 0; /* Number of tests runs */
6937 int nErr = 0; /* Number of errors seen */
6938 ShellText str; /* Answer for a query */
6939 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
6940
6941 open_db(p,0);
6942 for(i=1; i<nArg; i++){
6943 const char *z = azArg[i];
6944 if( z[0]=='-' && z[1]=='-' ) z++;
6945 if( strcmp(z,"-init")==0 ){
6946 bIsInit = 1;
6947 }else
6948 if( strcmp(z,"-v")==0 ){
6949 bVerbose++;
6950 }else
6951 {
6952 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6953 azArg[i], azArg[0]);
6954 raw_printf(stderr, "Should be one of: --init -v\n");
6955 rc = 1;
6956 goto meta_command_exit;
6957 }
6958 }
6959 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6960 != SQLITE_OK ){
6961 bSelftestExists = 0;
6962 }else{
6963 bSelftestExists = 1;
6964 }
6965 if( bIsInit ){
6966 createSelftestTable(p);
6967 bSelftestExists = 1;
6968 }
6969 initText(&str);
6970 appendText(&str, "x", 0);
6971 for(k=bSelftestExists; k>=0; k--){
6972 if( k==1 ){
6973 rc = sqlite3_prepare_v2(p->db,
6974 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6975 -1, &pStmt, 0);
6976 }else{
6977 rc = sqlite3_prepare_v2(p->db,
6978 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6979 " (1,'run','PRAGMA integrity_check','ok')",
6980 -1, &pStmt, 0);
6981 }
6982 if( rc ){
6983 raw_printf(stderr, "Error querying the selftest table\n");
6984 rc = 1;
6985 sqlite3_finalize(pStmt);
6986 goto meta_command_exit;
6987 }
6988 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6989 int tno = sqlite3_column_int(pStmt, 0);
6990 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6991 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6992 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
6993
6994 k = 0;
6995 if( bVerbose>0 ){
6996 char *zQuote = sqlite3_mprintf("%q", zSql);
6997 printf("%d: %s %s\n", tno, zOp, zSql);
6998 sqlite3_free(zQuote);
6999 }
7000 if( strcmp(zOp,"memo")==0 ){
7001 utf8_printf(p->out, "%s\n", zSql);
7002 }else
7003 if( strcmp(zOp,"run")==0 ){
7004 char *zErrMsg = 0;
7005 str.n = 0;
7006 str.z[0] = 0;
7007 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
7008 nTest++;
7009 if( bVerbose ){
7010 utf8_printf(p->out, "Result: %s\n", str.z);
7011 }
7012 if( rc || zErrMsg ){
7013 nErr++;
7014 rc = 1;
7015 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
7016 sqlite3_free(zErrMsg);
7017 }else if( strcmp(zAns,str.z)!=0 ){
7018 nErr++;
7019 rc = 1;
7020 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
7021 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
7022 }
7023 }else
7024 {
7025 utf8_printf(stderr,
7026 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
7027 rc = 1;
7028 break;
7029 }
7030 } /* End loop over rows of content from SELFTEST */
7031 sqlite3_finalize(pStmt);
7032 } /* End loop over k */
7033 freeText(&str);
7034 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
7035 }else
7036
7037 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
7038 if( nArg<2 || nArg>3 ){
7039 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
7040 rc = 1;
7041 }
7042 if( nArg>=2 ){
7043 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
7044 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
7045 }
7046 if( nArg>=3 ){
7047 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
7048 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
7049 }
7050 }else
7051
7052 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
7053 const char *zLike = 0; /* Which table to checksum. 0 means everything */
7054 int i; /* Loop counter */
7055 int bSchema = 0; /* Also hash the schema */
7056 int bSeparate = 0; /* Hash each table separately */
7057 int iSize = 224; /* Hash algorithm to use */
7058 int bDebug = 0; /* Only show the query that would have run */
7059 sqlite3_stmt *pStmt; /* For querying tables names */
7060 char *zSql; /* SQL to be run */
7061 char *zSep; /* Separator */
7062 ShellText sSql; /* Complete SQL for the query to run the hash */
7063 ShellText sQuery; /* Set of queries used to read all content */
7064 open_db(p, 0);
7065 for(i=1; i<nArg; i++){
7066 const char *z = azArg[i];
7067 if( z[0]=='-' ){
7068 z++;
7069 if( z[0]=='-' ) z++;
7070 if( strcmp(z,"schema")==0 ){
7071 bSchema = 1;
7072 }else
7073 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
7074 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
7075 ){
7076 iSize = atoi(&z[5]);
7077 }else
7078 if( strcmp(z,"debug")==0 ){
7079 bDebug = 1;
7080 }else
7081 {
7082 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7083 azArg[i], azArg[0]);
7084 raw_printf(stderr, "Should be one of: --schema"
7085 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
7086 rc = 1;
7087 goto meta_command_exit;
7088 }
7089 }else if( zLike ){
7090 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7091 rc = 1;
7092 goto meta_command_exit;
7093 }else{
7094 zLike = z;
7095 bSeparate = 1;
7096 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
7097 }
7098 }
7099 if( bSchema ){
7100 zSql = "SELECT lower(name) FROM sqlite_master"
7101 " WHERE type='table' AND coalesce(rootpage,0)>1"
7102 " UNION ALL SELECT 'sqlite_master'"
7103 " ORDER BY 1 collate nocase";
7104 }else{
7105 zSql = "SELECT lower(name) FROM sqlite_master"
7106 " WHERE type='table' AND coalesce(rootpage,0)>1"
7107 " AND name NOT LIKE 'sqlite_%'"
7108 " ORDER BY 1 collate nocase";
7109 }
7110 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7111 initText(&sQuery);
7112 initText(&sSql);
7113 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
7114 zSep = "VALUES(";
7115 while( SQLITE_ROW==sqlite3_step(pStmt) ){
7116 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
7117 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
7118 if( strncmp(zTab, "sqlite_",7)!=0 ){
7119 appendText(&sQuery,"SELECT * FROM ", 0);
7120 appendText(&sQuery,zTab,'"');
7121 appendText(&sQuery," NOT INDEXED;", 0);
7122 }else if( strcmp(zTab, "sqlite_master")==0 ){
7123 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7124 " ORDER BY name;", 0);
7125 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
7126 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
7127 " ORDER BY name;", 0);
7128 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
7129 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
7130 " ORDER BY tbl,idx;", 0);
7131 }else if( strcmp(zTab, "sqlite_stat3")==0
7132 || strcmp(zTab, "sqlite_stat4")==0 ){
7133 appendText(&sQuery, "SELECT * FROM ", 0);
7134 appendText(&sQuery, zTab, 0);
7135 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
7136 }
7137 appendText(&sSql, zSep, 0);
7138 appendText(&sSql, sQuery.z, '\'');
7139 sQuery.n = 0;
7140 appendText(&sSql, ",", 0);
7141 appendText(&sSql, zTab, '\'');
7142 zSep = "),(";
7143 }
7144 sqlite3_finalize(pStmt);
7145 if( bSeparate ){
7146 zSql = sqlite3_mprintf(
7147 "%s))"
7148 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7149 " FROM [sha3sum$query]",
7150 sSql.z, iSize);
7151 }else{
7152 zSql = sqlite3_mprintf(
7153 "%s))"
7154 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7155 " FROM [sha3sum$query]",
7156 sSql.z, iSize);
7157 }
7158 freeText(&sQuery);
7159 freeText(&sSql);
7160 if( bDebug ){
7161 utf8_printf(p->out, "%s\n", zSql);
7162 }else{
drha10b9992018-03-09 15:24:33 +00007163 shell_exec(p, zSql, 0);
drh2ce15c32017-07-11 13:34:40 +00007164 }
7165 sqlite3_free(zSql);
7166 }else
7167
drh04a28c32018-01-31 01:38:44 +00007168#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00007169 if( c=='s'
7170 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
7171 ){
7172 char *zCmd;
7173 int i, x;
7174 if( nArg<2 ){
7175 raw_printf(stderr, "Usage: .system COMMAND\n");
7176 rc = 1;
7177 goto meta_command_exit;
7178 }
7179 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
7180 for(i=2; i<nArg; i++){
7181 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
7182 zCmd, azArg[i]);
7183 }
7184 x = system(zCmd);
7185 sqlite3_free(zCmd);
7186 if( x ) raw_printf(stderr, "System command returns %d\n", x);
7187 }else
drh04a28c32018-01-31 01:38:44 +00007188#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00007189
7190 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00007191 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00007192 int i;
7193 if( nArg!=1 ){
7194 raw_printf(stderr, "Usage: .show\n");
7195 rc = 1;
7196 goto meta_command_exit;
7197 }
7198 utf8_printf(p->out, "%12.12s: %s\n","echo",
7199 azBool[ShellHasFlag(p, SHFLG_Echo)]);
7200 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
7201 utf8_printf(p->out, "%12.12s: %s\n","explain",
7202 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
7203 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
7204 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
7205 utf8_printf(p->out, "%12.12s: ", "nullvalue");
7206 output_c_string(p->out, p->nullValue);
7207 raw_printf(p->out, "\n");
7208 utf8_printf(p->out,"%12.12s: %s\n","output",
7209 strlen30(p->outfile) ? p->outfile : "stdout");
7210 utf8_printf(p->out,"%12.12s: ", "colseparator");
7211 output_c_string(p->out, p->colSeparator);
7212 raw_printf(p->out, "\n");
7213 utf8_printf(p->out,"%12.12s: ", "rowseparator");
7214 output_c_string(p->out, p->rowSeparator);
7215 raw_printf(p->out, "\n");
7216 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
7217 utf8_printf(p->out, "%12.12s: ", "width");
7218 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
7219 raw_printf(p->out, "%d ", p->colWidth[i]);
7220 }
7221 raw_printf(p->out, "\n");
7222 utf8_printf(p->out, "%12.12s: %s\n", "filename",
7223 p->zDbFilename ? p->zDbFilename : "");
7224 }else
7225
7226 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
7227 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00007228 p->statsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007229 }else if( nArg==1 ){
7230 display_stats(p->db, p, 0);
7231 }else{
7232 raw_printf(stderr, "Usage: .stats ?on|off?\n");
7233 rc = 1;
7234 }
7235 }else
7236
7237 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
7238 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
7239 || strncmp(azArg[0], "indexes", n)==0) )
7240 ){
7241 sqlite3_stmt *pStmt;
7242 char **azResult;
7243 int nRow, nAlloc;
7244 int ii;
7245 ShellText s;
7246 initText(&s);
7247 open_db(p, 0);
7248 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
7249 if( rc ) return shellDatabaseError(p->db);
7250
7251 if( nArg>2 && c=='i' ){
7252 /* It is an historical accident that the .indexes command shows an error
7253 ** when called with the wrong number of arguments whereas the .tables
7254 ** command does not. */
7255 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
7256 rc = 1;
7257 goto meta_command_exit;
7258 }
7259 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
7260 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
7261 if( zDbName==0 ) continue;
7262 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
7263 if( sqlite3_stricmp(zDbName, "main")==0 ){
7264 appendText(&s, "SELECT name FROM ", 0);
7265 }else{
7266 appendText(&s, "SELECT ", 0);
7267 appendText(&s, zDbName, '\'');
7268 appendText(&s, "||'.'||name FROM ", 0);
7269 }
7270 appendText(&s, zDbName, '"');
7271 appendText(&s, ".sqlite_master ", 0);
7272 if( c=='t' ){
7273 appendText(&s," WHERE type IN ('table','view')"
7274 " AND name NOT LIKE 'sqlite_%'"
7275 " AND name LIKE ?1", 0);
7276 }else{
7277 appendText(&s," WHERE type='index'"
7278 " AND tbl_name LIKE ?1", 0);
7279 }
7280 }
7281 rc = sqlite3_finalize(pStmt);
7282 appendText(&s, " ORDER BY 1", 0);
7283 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
7284 freeText(&s);
7285 if( rc ) return shellDatabaseError(p->db);
7286
7287 /* Run the SQL statement prepared by the above block. Store the results
7288 ** as an array of nul-terminated strings in azResult[]. */
7289 nRow = nAlloc = 0;
7290 azResult = 0;
7291 if( nArg>1 ){
7292 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
7293 }else{
7294 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
7295 }
7296 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7297 if( nRow>=nAlloc ){
7298 char **azNew;
7299 int n2 = nAlloc*2 + 10;
7300 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
7301 if( azNew==0 ){
7302 rc = shellNomemError();
7303 break;
7304 }
7305 nAlloc = n2;
7306 azResult = azNew;
7307 }
7308 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
7309 if( 0==azResult[nRow] ){
7310 rc = shellNomemError();
7311 break;
7312 }
7313 nRow++;
7314 }
7315 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
7316 rc = shellDatabaseError(p->db);
7317 }
7318
7319 /* Pretty-print the contents of array azResult[] to the output */
7320 if( rc==0 && nRow>0 ){
7321 int len, maxlen = 0;
7322 int i, j;
7323 int nPrintCol, nPrintRow;
7324 for(i=0; i<nRow; i++){
7325 len = strlen30(azResult[i]);
7326 if( len>maxlen ) maxlen = len;
7327 }
7328 nPrintCol = 80/(maxlen+2);
7329 if( nPrintCol<1 ) nPrintCol = 1;
7330 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
7331 for(i=0; i<nPrintRow; i++){
7332 for(j=i; j<nRow; j+=nPrintRow){
7333 char *zSp = j<nPrintRow ? "" : " ";
7334 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
7335 azResult[j] ? azResult[j]:"");
7336 }
7337 raw_printf(p->out, "\n");
7338 }
7339 }
7340
7341 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
7342 sqlite3_free(azResult);
7343 }else
7344
7345 /* Begin redirecting output to the file "testcase-out.txt" */
7346 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
7347 output_reset(p);
drha92a01a2018-01-10 22:15:37 +00007348 p->out = output_file_open("testcase-out.txt", 0);
drh2ce15c32017-07-11 13:34:40 +00007349 if( p->out==0 ){
7350 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
7351 }
7352 if( nArg>=2 ){
7353 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
7354 }else{
7355 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
7356 }
7357 }else
7358
7359#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00007360 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007361 static const struct {
7362 const char *zCtrlName; /* Name of a test-control option */
7363 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00007364 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00007365 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00007366 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
7367 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
7368 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7369 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7370 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
7371 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7372 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
7373#ifdef SQLITE_N_KEYWORD
7374 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD, "IDENTIFIER" },
7375#endif
7376 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
7377 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
7378 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00007379#ifdef YYCOVERAGE
7380 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
7381#endif
drhef302e82017-11-15 19:14:08 +00007382 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
7383 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
7384 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
7385 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
7386 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00007387 };
7388 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00007389 int iCtrl = -1;
7390 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7391 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00007392 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00007393 const char *zCmd = 0;
7394
drh2ce15c32017-07-11 13:34:40 +00007395 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00007396 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00007397
7398 /* The argument can optionally begin with "-" or "--" */
7399 if( zCmd[0]=='-' && zCmd[1] ){
7400 zCmd++;
7401 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7402 }
7403
7404 /* --help lists all test-controls */
7405 if( strcmp(zCmd,"help")==0 ){
7406 utf8_printf(p->out, "Available test-controls:\n");
7407 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00007408 utf8_printf(p->out, " .testctrl %s %s\n",
7409 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00007410 }
7411 rc = 1;
7412 goto meta_command_exit;
7413 }
drh2ce15c32017-07-11 13:34:40 +00007414
7415 /* convert testctrl text option to value. allow any unique prefix
7416 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00007417 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00007418 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00007419 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007420 if( testctrl<0 ){
7421 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00007422 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00007423 }else{
drh35f51a42017-11-15 17:07:22 +00007424 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
7425 "Use \".testctrl --help\" for help\n", zCmd);
7426 rc = 1;
7427 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00007428 }
7429 }
7430 }
drhef302e82017-11-15 19:14:08 +00007431 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00007432 utf8_printf(stderr,"Error: unknown test-control: %s\n"
7433 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00007434 }else{
7435 switch(testctrl){
7436
7437 /* sqlite3_test_control(int, db, int) */
7438 case SQLITE_TESTCTRL_OPTIMIZATIONS:
7439 case SQLITE_TESTCTRL_RESERVE:
7440 if( nArg==3 ){
7441 int opt = (int)strtol(azArg[2], 0, 0);
7442 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00007443 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007444 }
7445 break;
7446
7447 /* sqlite3_test_control(int) */
7448 case SQLITE_TESTCTRL_PRNG_SAVE:
7449 case SQLITE_TESTCTRL_PRNG_RESTORE:
7450 case SQLITE_TESTCTRL_PRNG_RESET:
7451 case SQLITE_TESTCTRL_BYTEORDER:
7452 if( nArg==2 ){
7453 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00007454 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00007455 }
7456 break;
7457
7458 /* sqlite3_test_control(int, uint) */
7459 case SQLITE_TESTCTRL_PENDING_BYTE:
7460 if( nArg==3 ){
7461 unsigned int opt = (unsigned int)integerValue(azArg[2]);
7462 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007463 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007464 }
7465 break;
7466
7467 /* sqlite3_test_control(int, int) */
7468 case SQLITE_TESTCTRL_ASSERT:
7469 case SQLITE_TESTCTRL_ALWAYS:
drhef302e82017-11-15 19:14:08 +00007470 if( nArg==3 ){
7471 int opt = booleanValue(azArg[2]);
7472 rc2 = sqlite3_test_control(testctrl, opt);
7473 isOk = 1;
7474 }
7475 break;
7476
7477 /* sqlite3_test_control(int, int) */
7478 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00007479 case SQLITE_TESTCTRL_NEVER_CORRUPT:
7480 if( nArg==3 ){
7481 int opt = booleanValue(azArg[2]);
7482 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007483 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007484 }
7485 break;
7486
7487 /* sqlite3_test_control(int, char *) */
7488#ifdef SQLITE_N_KEYWORD
7489 case SQLITE_TESTCTRL_ISKEYWORD:
7490 if( nArg==3 ){
7491 const char *opt = azArg[2];
7492 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007493 isOk = 1;
drh2ce15c32017-07-11 13:34:40 +00007494 }
7495 break;
7496#endif
7497
7498 case SQLITE_TESTCTRL_IMPOSTER:
7499 if( nArg==5 ){
7500 rc2 = sqlite3_test_control(testctrl, p->db,
7501 azArg[2],
7502 integerValue(azArg[3]),
7503 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00007504 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007505 }
7506 break;
drh0d9de992017-12-26 18:04:23 +00007507
7508#ifdef YYCOVERAGE
7509 case SQLITE_TESTCTRL_PARSER_COVERAGE:
7510 if( nArg==2 ){
7511 sqlite3_test_control(testctrl, p->out);
7512 isOk = 3;
7513 }
7514#endif
drh2ce15c32017-07-11 13:34:40 +00007515 }
7516 }
drhef302e82017-11-15 19:14:08 +00007517 if( isOk==0 && iCtrl>=0 ){
7518 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
7519 rc = 1;
7520 }else if( isOk==1 ){
7521 raw_printf(p->out, "%d\n", rc2);
7522 }else if( isOk==2 ){
7523 raw_printf(p->out, "0x%08x\n", rc2);
7524 }
drh2ce15c32017-07-11 13:34:40 +00007525 }else
7526#endif /* !defined(SQLITE_UNTESTABLE) */
7527
7528 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
7529 open_db(p, 0);
7530 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
7531 }else
7532
7533 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7534 if( nArg==2 ){
7535 enableTimer = booleanValue(azArg[1]);
7536 if( enableTimer && !HAS_TIMER ){
7537 raw_printf(stderr, "Error: timer not available on this system.\n");
7538 enableTimer = 0;
7539 }
7540 }else{
7541 raw_printf(stderr, "Usage: .timer on|off\n");
7542 rc = 1;
7543 }
7544 }else
7545
7546 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
7547 open_db(p, 0);
7548 if( nArg!=2 ){
7549 raw_printf(stderr, "Usage: .trace FILE|off\n");
7550 rc = 1;
7551 goto meta_command_exit;
7552 }
7553 output_file_close(p->traceOut);
drha92a01a2018-01-10 22:15:37 +00007554 p->traceOut = output_file_open(azArg[1], 0);
drh2ce15c32017-07-11 13:34:40 +00007555#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7556 if( p->traceOut==0 ){
7557 sqlite3_trace_v2(p->db, 0, 0, 0);
7558 }else{
7559 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
7560 }
7561#endif
7562 }else
7563
7564#if SQLITE_USER_AUTHENTICATION
7565 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7566 if( nArg<2 ){
7567 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
7568 rc = 1;
7569 goto meta_command_exit;
7570 }
7571 open_db(p, 0);
7572 if( strcmp(azArg[1],"login")==0 ){
7573 if( nArg!=4 ){
7574 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
7575 rc = 1;
7576 goto meta_command_exit;
7577 }
drhaf2770f2018-01-05 14:55:43 +00007578 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00007579 if( rc ){
7580 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
7581 rc = 1;
7582 }
7583 }else if( strcmp(azArg[1],"add")==0 ){
7584 if( nArg!=5 ){
7585 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
7586 rc = 1;
7587 goto meta_command_exit;
7588 }
drhaf2770f2018-01-05 14:55:43 +00007589 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007590 booleanValue(azArg[4]));
7591 if( rc ){
7592 raw_printf(stderr, "User-Add failed: %d\n", rc);
7593 rc = 1;
7594 }
7595 }else if( strcmp(azArg[1],"edit")==0 ){
7596 if( nArg!=5 ){
7597 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
7598 rc = 1;
7599 goto meta_command_exit;
7600 }
drhaf2770f2018-01-05 14:55:43 +00007601 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007602 booleanValue(azArg[4]));
7603 if( rc ){
7604 raw_printf(stderr, "User-Edit failed: %d\n", rc);
7605 rc = 1;
7606 }
7607 }else if( strcmp(azArg[1],"delete")==0 ){
7608 if( nArg!=3 ){
7609 raw_printf(stderr, "Usage: .user delete USER\n");
7610 rc = 1;
7611 goto meta_command_exit;
7612 }
7613 rc = sqlite3_user_delete(p->db, azArg[2]);
7614 if( rc ){
7615 raw_printf(stderr, "User-Delete failed: %d\n", rc);
7616 rc = 1;
7617 }
7618 }else{
7619 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
7620 rc = 1;
7621 goto meta_command_exit;
7622 }
7623 }else
7624#endif /* SQLITE_USER_AUTHENTICATION */
7625
7626 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
7627 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
7628 sqlite3_libversion(), sqlite3_sourceid());
drh0ed2fd82018-01-16 20:05:27 +00007629#if SQLITE_HAVE_ZLIB
7630 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
7631#endif
7632#define CTIMEOPT_VAL_(opt) #opt
7633#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
7634#if defined(__clang__) && defined(__clang_major__)
7635 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
7636 CTIMEOPT_VAL(__clang_minor__) "."
7637 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
7638#elif defined(_MSC_VER)
7639 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
7640#elif defined(__GNUC__) && defined(__VERSION__)
7641 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
7642#endif
drh2ce15c32017-07-11 13:34:40 +00007643 }else
7644
7645 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7646 const char *zDbName = nArg==2 ? azArg[1] : "main";
7647 sqlite3_vfs *pVfs = 0;
7648 if( p->db ){
7649 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7650 if( pVfs ){
7651 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7652 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7653 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7654 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7655 }
7656 }
7657 }else
7658
7659 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7660 sqlite3_vfs *pVfs;
7661 sqlite3_vfs *pCurrent = 0;
7662 if( p->db ){
7663 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7664 }
7665 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7666 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7667 pVfs==pCurrent ? " <--- CURRENT" : "");
7668 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7669 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7670 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7671 if( pVfs->pNext ){
7672 raw_printf(p->out, "-----------------------------------\n");
7673 }
7674 }
7675 }else
7676
7677 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7678 const char *zDbName = nArg==2 ? azArg[1] : "main";
7679 char *zVfsName = 0;
7680 if( p->db ){
7681 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7682 if( zVfsName ){
7683 utf8_printf(p->out, "%s\n", zVfsName);
7684 sqlite3_free(zVfsName);
7685 }
7686 }
7687 }else
7688
7689#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7690 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
7691 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
7692 }else
7693#endif
7694
7695 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
7696 int j;
7697 assert( nArg<=ArraySize(azArg) );
7698 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
7699 p->colWidth[j-1] = (int)integerValue(azArg[j]);
7700 }
7701 }else
7702
7703 {
7704 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
7705 " \"%s\". Enter \".help\" for help\n", azArg[0]);
7706 rc = 1;
7707 }
7708
7709meta_command_exit:
7710 if( p->outCount ){
7711 p->outCount--;
7712 if( p->outCount==0 ) output_reset(p);
7713 }
7714 return rc;
7715}
7716
7717/*
7718** Return TRUE if a semicolon occurs anywhere in the first N characters
7719** of string z[].
7720*/
7721static int line_contains_semicolon(const char *z, int N){
7722 int i;
7723 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
7724 return 0;
7725}
7726
7727/*
7728** Test to see if a line consists entirely of whitespace.
7729*/
7730static int _all_whitespace(const char *z){
7731 for(; *z; z++){
7732 if( IsSpace(z[0]) ) continue;
7733 if( *z=='/' && z[1]=='*' ){
7734 z += 2;
7735 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
7736 if( *z==0 ) return 0;
7737 z++;
7738 continue;
7739 }
7740 if( *z=='-' && z[1]=='-' ){
7741 z += 2;
7742 while( *z && *z!='\n' ){ z++; }
7743 if( *z==0 ) return 1;
7744 continue;
7745 }
7746 return 0;
7747 }
7748 return 1;
7749}
7750
7751/*
7752** Return TRUE if the line typed in is an SQL command terminator other
7753** than a semi-colon. The SQL Server style "go" command is understood
7754** as is the Oracle "/".
7755*/
7756static int line_is_command_terminator(const char *zLine){
7757 while( IsSpace(zLine[0]) ){ zLine++; };
7758 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
7759 return 1; /* Oracle */
7760 }
7761 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
7762 && _all_whitespace(&zLine[2]) ){
7763 return 1; /* SQL Server */
7764 }
7765 return 0;
7766}
7767
7768/*
drh56f17742018-01-24 01:58:49 +00007769** We need a default sqlite3_complete() implementation to use in case
7770** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
7771** any arbitrary text is a complete SQL statement. This is not very
7772** user-friendly, but it does seem to work.
7773*/
7774#ifdef SQLITE_OMIT_COMPLETE
7775int sqlite3_complete(const char *zSql){ return 1; }
7776#endif
7777
7778/*
drh2ce15c32017-07-11 13:34:40 +00007779** Return true if zSql is a complete SQL statement. Return false if it
7780** ends in the middle of a string literal or C-style comment.
7781*/
7782static int line_is_complete(char *zSql, int nSql){
7783 int rc;
7784 if( zSql==0 ) return 1;
7785 zSql[nSql] = ';';
7786 zSql[nSql+1] = 0;
7787 rc = sqlite3_complete(zSql);
7788 zSql[nSql] = 0;
7789 return rc;
7790}
7791
7792/*
7793** Run a single line of SQL
7794*/
7795static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
7796 int rc;
7797 char *zErrMsg = 0;
7798
7799 open_db(p, 0);
7800 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
7801 BEGIN_TIMER;
drha10b9992018-03-09 15:24:33 +00007802 rc = shell_exec(p, zSql, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007803 END_TIMER;
7804 if( rc || zErrMsg ){
7805 char zPrefix[100];
7806 if( in!=0 || !stdin_is_interactive ){
7807 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
7808 "Error: near line %d:", startline);
7809 }else{
7810 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
7811 }
7812 if( zErrMsg!=0 ){
7813 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
7814 sqlite3_free(zErrMsg);
7815 zErrMsg = 0;
7816 }else{
7817 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
7818 }
7819 return 1;
7820 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
7821 raw_printf(p->out, "changes: %3d total_changes: %d\n",
7822 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
7823 }
7824 return 0;
7825}
7826
7827
7828/*
7829** Read input from *in and process it. If *in==0 then input
7830** is interactive - the user is typing it it. Otherwise, input
7831** is coming from a file or device. A prompt is issued and history
7832** is saved only if input is interactive. An interrupt signal will
7833** cause this routine to exit immediately, unless input is interactive.
7834**
7835** Return the number of errors.
7836*/
7837static int process_input(ShellState *p, FILE *in){
7838 char *zLine = 0; /* A single input line */
7839 char *zSql = 0; /* Accumulated SQL text */
7840 int nLine; /* Length of current line */
7841 int nSql = 0; /* Bytes of zSql[] used */
7842 int nAlloc = 0; /* Allocated zSql[] space */
7843 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
7844 int rc; /* Error code */
7845 int errCnt = 0; /* Number of errors seen */
7846 int lineno = 0; /* Current line number */
7847 int startline = 0; /* Line number for start of current input */
7848
7849 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
7850 fflush(p->out);
7851 zLine = one_input_line(in, zLine, nSql>0);
7852 if( zLine==0 ){
7853 /* End of input */
7854 if( in==0 && stdin_is_interactive ) printf("\n");
7855 break;
7856 }
7857 if( seenInterrupt ){
7858 if( in!=0 ) break;
7859 seenInterrupt = 0;
7860 }
7861 lineno++;
7862 if( nSql==0 && _all_whitespace(zLine) ){
7863 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7864 continue;
7865 }
7866 if( zLine && zLine[0]=='.' && nSql==0 ){
7867 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7868 rc = do_meta_command(zLine, p);
7869 if( rc==2 ){ /* exit requested */
7870 break;
7871 }else if( rc ){
7872 errCnt++;
7873 }
7874 continue;
7875 }
7876 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
7877 memcpy(zLine,";",2);
7878 }
7879 nLine = strlen30(zLine);
7880 if( nSql+nLine+2>=nAlloc ){
7881 nAlloc = nSql+nLine+100;
7882 zSql = realloc(zSql, nAlloc);
7883 if( zSql==0 ){
7884 raw_printf(stderr, "Error: out of memory\n");
7885 exit(1);
7886 }
7887 }
7888 nSqlPrior = nSql;
7889 if( nSql==0 ){
7890 int i;
7891 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
7892 assert( nAlloc>0 && zSql!=0 );
7893 memcpy(zSql, zLine+i, nLine+1-i);
7894 startline = lineno;
7895 nSql = nLine-i;
7896 }else{
7897 zSql[nSql++] = '\n';
7898 memcpy(zSql+nSql, zLine, nLine+1);
7899 nSql += nLine;
7900 }
7901 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
7902 && sqlite3_complete(zSql) ){
7903 errCnt += runOneSqlLine(p, zSql, in, startline);
7904 nSql = 0;
7905 if( p->outCount ){
7906 output_reset(p);
7907 p->outCount = 0;
drh13c20932018-01-10 21:41:55 +00007908 }else{
7909 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00007910 }
7911 }else if( nSql && _all_whitespace(zSql) ){
7912 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
7913 nSql = 0;
7914 }
7915 }
7916 if( nSql && !_all_whitespace(zSql) ){
7917 runOneSqlLine(p, zSql, in, startline);
7918 }
7919 free(zSql);
7920 free(zLine);
7921 return errCnt>0;
7922}
7923
7924/*
7925** Return a pathname which is the user's home directory. A
7926** 0 return indicates an error of some kind.
7927*/
7928static char *find_home_dir(int clearFlag){
7929 static char *home_dir = NULL;
7930 if( clearFlag ){
7931 free(home_dir);
7932 home_dir = 0;
7933 return 0;
7934 }
7935 if( home_dir ) return home_dir;
7936
7937#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7938 && !defined(__RTP__) && !defined(_WRS_KERNEL)
7939 {
7940 struct passwd *pwent;
7941 uid_t uid = getuid();
7942 if( (pwent=getpwuid(uid)) != NULL) {
7943 home_dir = pwent->pw_dir;
7944 }
7945 }
7946#endif
7947
7948#if defined(_WIN32_WCE)
7949 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7950 */
7951 home_dir = "/";
7952#else
7953
7954#if defined(_WIN32) || defined(WIN32)
7955 if (!home_dir) {
7956 home_dir = getenv("USERPROFILE");
7957 }
7958#endif
7959
7960 if (!home_dir) {
7961 home_dir = getenv("HOME");
7962 }
7963
7964#if defined(_WIN32) || defined(WIN32)
7965 if (!home_dir) {
7966 char *zDrive, *zPath;
7967 int n;
7968 zDrive = getenv("HOMEDRIVE");
7969 zPath = getenv("HOMEPATH");
7970 if( zDrive && zPath ){
7971 n = strlen30(zDrive) + strlen30(zPath) + 1;
7972 home_dir = malloc( n );
7973 if( home_dir==0 ) return 0;
7974 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7975 return home_dir;
7976 }
7977 home_dir = "c:\\";
7978 }
7979#endif
7980
7981#endif /* !_WIN32_WCE */
7982
7983 if( home_dir ){
7984 int n = strlen30(home_dir) + 1;
7985 char *z = malloc( n );
7986 if( z ) memcpy(z, home_dir, n);
7987 home_dir = z;
7988 }
7989
7990 return home_dir;
7991}
7992
7993/*
7994** Read input from the file given by sqliterc_override. Or if that
7995** parameter is NULL, take input from ~/.sqliterc
7996**
7997** Returns the number of errors.
7998*/
7999static void process_sqliterc(
8000 ShellState *p, /* Configuration data */
8001 const char *sqliterc_override /* Name of config file. NULL to use default */
8002){
8003 char *home_dir = NULL;
8004 const char *sqliterc = sqliterc_override;
8005 char *zBuf = 0;
8006 FILE *in = NULL;
8007
8008 if (sqliterc == NULL) {
8009 home_dir = find_home_dir(0);
8010 if( home_dir==0 ){
8011 raw_printf(stderr, "-- warning: cannot find home directory;"
8012 " cannot read ~/.sqliterc\n");
8013 return;
8014 }
8015 sqlite3_initialize();
8016 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
8017 sqliterc = zBuf;
8018 }
8019 in = fopen(sqliterc,"rb");
8020 if( in ){
8021 if( stdin_is_interactive ){
8022 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
8023 }
8024 process_input(p,in);
8025 fclose(in);
8026 }
8027 sqlite3_free(zBuf);
8028}
8029
8030/*
8031** Show available command line options
8032*/
8033static const char zOptions[] =
drhda57d962018-03-05 19:34:05 +00008034#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhad7fd5d2018-03-05 20:21:50 +00008035 " -A ARGS... run \".archive ARGS\" and exit\n"
drhda57d962018-03-05 19:34:05 +00008036#endif
drh3baed312018-03-08 18:14:41 +00008037 " -append append the database to the end of the file\n"
drh2ce15c32017-07-11 13:34:40 +00008038 " -ascii set output mode to 'ascii'\n"
8039 " -bail stop after hitting an error\n"
8040 " -batch force batch I/O\n"
8041 " -column set output mode to 'column'\n"
8042 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
8043 " -csv set output mode to 'csv'\n"
8044 " -echo print commands before execution\n"
8045 " -init FILENAME read/process named file\n"
8046 " -[no]header turn headers on or off\n"
8047#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8048 " -heap SIZE Size of heap for memsys3 or memsys5\n"
8049#endif
8050 " -help show this message\n"
8051 " -html set output mode to HTML\n"
8052 " -interactive force interactive I/O\n"
8053 " -line set output mode to 'line'\n"
8054 " -list set output mode to 'list'\n"
8055 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
8056 " -mmap N default mmap size set to N\n"
8057#ifdef SQLITE_ENABLE_MULTIPLEX
8058 " -multiplex enable the multiplexor VFS\n"
8059#endif
8060 " -newline SEP set output row separator. Default: '\\n'\n"
8061 " -nullvalue TEXT set text string for NULL values. Default ''\n"
8062 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
8063 " -quote set output mode to 'quote'\n"
drhee269a62018-02-14 23:27:43 +00008064 " -readonly open the database read-only\n"
drh2ce15c32017-07-11 13:34:40 +00008065 " -separator SEP set output column separator. Default: '|'\n"
8066 " -stats print memory stats before each finalize\n"
8067 " -version show SQLite version\n"
8068 " -vfs NAME use NAME as the default VFS\n"
8069#ifdef SQLITE_ENABLE_VFSTRACE
8070 " -vfstrace enable tracing of all VFS calls\n"
8071#endif
drh3baed312018-03-08 18:14:41 +00008072#ifdef SQLITE_HAVE_ZLIB
8073 " -zip open the file as a ZIP Archive\n"
8074#endif
drh2ce15c32017-07-11 13:34:40 +00008075;
8076static void usage(int showDetail){
8077 utf8_printf(stderr,
8078 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8079 "FILENAME is the name of an SQLite database. A new database is created\n"
8080 "if the file does not previously exist.\n", Argv0);
8081 if( showDetail ){
8082 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
8083 }else{
8084 raw_printf(stderr, "Use the -help option for additional information\n");
8085 }
8086 exit(1);
8087}
8088
8089/*
8090** Initialize the state information in data
8091*/
8092static void main_init(ShellState *data) {
8093 memset(data, 0, sizeof(*data));
8094 data->normalMode = data->cMode = data->mode = MODE_List;
8095 data->autoExplain = 1;
8096 memcpy(data->colSeparator,SEP_Column, 2);
8097 memcpy(data->rowSeparator,SEP_Row, 2);
8098 data->showHeader = 0;
8099 data->shellFlgs = SHFLG_Lookaside;
8100 sqlite3_config(SQLITE_CONFIG_URI, 1);
8101 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
8102 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
8103 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
8104 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
8105}
8106
8107/*
8108** Output text to the console in a font that attracts extra attention.
8109*/
8110#ifdef _WIN32
8111static void printBold(const char *zText){
8112 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
8113 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
8114 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
8115 SetConsoleTextAttribute(out,
8116 FOREGROUND_RED|FOREGROUND_INTENSITY
8117 );
8118 printf("%s", zText);
8119 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
8120}
8121#else
8122static void printBold(const char *zText){
8123 printf("\033[1m%s\033[0m", zText);
8124}
8125#endif
8126
8127/*
8128** Get the argument to an --option. Throw an error and die if no argument
8129** is available.
8130*/
8131static char *cmdline_option_value(int argc, char **argv, int i){
8132 if( i==argc ){
8133 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
8134 argv[0], argv[argc-1]);
8135 exit(1);
8136 }
8137 return argv[i];
8138}
8139
8140#ifndef SQLITE_SHELL_IS_UTF8
8141# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8142# define SQLITE_SHELL_IS_UTF8 (0)
8143# else
8144# define SQLITE_SHELL_IS_UTF8 (1)
8145# endif
8146#endif
8147
8148#if SQLITE_SHELL_IS_UTF8
8149int SQLITE_CDECL main(int argc, char **argv){
8150#else
8151int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
8152 char **argv;
8153#endif
8154 char *zErrMsg = 0;
8155 ShellState data;
8156 const char *zInitFile = 0;
8157 int i;
8158 int rc = 0;
8159 int warnInmemoryDb = 0;
8160 int readStdin = 1;
8161 int nCmd = 0;
8162 char **azCmd = 0;
8163
8164 setBinaryMode(stdin, 0);
8165 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
8166 stdin_is_interactive = isatty(0);
8167 stdout_is_console = isatty(1);
8168
8169#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00008170 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00008171 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
8172 sqlite3_sourceid(), SQLITE_SOURCE_ID);
8173 exit(1);
8174 }
8175#endif
8176 main_init(&data);
drh501ea052018-02-15 01:03:37 +00008177
8178 /* On Windows, we must translate command-line arguments into UTF-8.
8179 ** The SQLite memory allocator subsystem has to be enabled in order to
8180 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
8181 ** subsequent sqlite3_config() calls will work. So copy all results into
8182 ** memory that does not come from the SQLite memory allocator.
8183 */
drh4b18c1d2018-02-04 20:33:13 +00008184#if !SQLITE_SHELL_IS_UTF8
drh501ea052018-02-15 01:03:37 +00008185 sqlite3_initialize();
8186 argv = malloc(sizeof(argv[0])*argc);
drh2ce15c32017-07-11 13:34:40 +00008187 if( argv==0 ){
8188 raw_printf(stderr, "out of memory\n");
8189 exit(1);
8190 }
8191 for(i=0; i<argc; i++){
drh501ea052018-02-15 01:03:37 +00008192 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
8193 int n;
8194 if( z==0 ){
8195 raw_printf(stderr, "out of memory\n");
8196 exit(1);
8197 }
8198 n = (int)strlen(z);
8199 argv[i] = malloc( n+1 );
drh2ce15c32017-07-11 13:34:40 +00008200 if( argv[i]==0 ){
8201 raw_printf(stderr, "out of memory\n");
8202 exit(1);
8203 }
drh501ea052018-02-15 01:03:37 +00008204 memcpy(argv[i], z, n+1);
8205 sqlite3_free(z);
drh2ce15c32017-07-11 13:34:40 +00008206 }
drh501ea052018-02-15 01:03:37 +00008207 sqlite3_shutdown();
drh2ce15c32017-07-11 13:34:40 +00008208#endif
drh501ea052018-02-15 01:03:37 +00008209
drh2ce15c32017-07-11 13:34:40 +00008210 assert( argc>=1 && argv && argv[0] );
8211 Argv0 = argv[0];
8212
8213 /* Make sure we have a valid signal handler early, before anything
8214 ** else is done.
8215 */
8216#ifdef SIGINT
8217 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00008218#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
8219 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00008220#endif
8221
8222#ifdef SQLITE_SHELL_DBNAME_PROC
8223 {
8224 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8225 ** of a C-function that will provide the name of the database file. Use
8226 ** this compile-time option to embed this shell program in larger
8227 ** applications. */
8228 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8229 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
8230 warnInmemoryDb = 0;
8231 }
8232#endif
8233
8234 /* Do an initial pass through the command-line argument to locate
8235 ** the name of the database file, the name of the initialization file,
8236 ** the size of the alternative malloc heap,
8237 ** and the first command to execute.
8238 */
8239 for(i=1; i<argc; i++){
8240 char *z;
8241 z = argv[i];
8242 if( z[0]!='-' ){
8243 if( data.zDbFilename==0 ){
8244 data.zDbFilename = z;
8245 }else{
8246 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8247 ** mean that nothing is read from stdin */
8248 readStdin = 0;
8249 nCmd++;
8250 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
8251 if( azCmd==0 ){
8252 raw_printf(stderr, "out of memory\n");
8253 exit(1);
8254 }
8255 azCmd[nCmd-1] = z;
8256 }
8257 }
8258 if( z[1]=='-' ) z++;
8259 if( strcmp(z,"-separator")==0
8260 || strcmp(z,"-nullvalue")==0
8261 || strcmp(z,"-newline")==0
8262 || strcmp(z,"-cmd")==0
8263 ){
8264 (void)cmdline_option_value(argc, argv, ++i);
8265 }else if( strcmp(z,"-init")==0 ){
8266 zInitFile = cmdline_option_value(argc, argv, ++i);
8267 }else if( strcmp(z,"-batch")==0 ){
8268 /* Need to check for batch mode here to so we can avoid printing
8269 ** informational messages (like from process_sqliterc) before
8270 ** we do the actual processing of arguments later in a second pass.
8271 */
8272 stdin_is_interactive = 0;
8273 }else if( strcmp(z,"-heap")==0 ){
8274#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8275 const char *zSize;
8276 sqlite3_int64 szHeap;
8277
8278 zSize = cmdline_option_value(argc, argv, ++i);
8279 szHeap = integerValue(zSize);
8280 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
8281 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
8282#else
8283 (void)cmdline_option_value(argc, argv, ++i);
8284#endif
drh2ce15c32017-07-11 13:34:40 +00008285 }else if( strcmp(z,"-pagecache")==0 ){
8286 int n, sz;
8287 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8288 if( sz>70000 ) sz = 70000;
8289 if( sz<0 ) sz = 0;
8290 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8291 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
8292 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
8293 data.shellFlgs |= SHFLG_Pagecache;
8294 }else if( strcmp(z,"-lookaside")==0 ){
8295 int n, sz;
8296 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8297 if( sz<0 ) sz = 0;
8298 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8299 if( n<0 ) n = 0;
8300 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
8301 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
8302#ifdef SQLITE_ENABLE_VFSTRACE
8303 }else if( strcmp(z,"-vfstrace")==0 ){
8304 extern int vfstrace_register(
8305 const char *zTraceName,
8306 const char *zOldVfsName,
8307 int (*xOut)(const char*,void*),
8308 void *pOutArg,
8309 int makeDefault
8310 );
8311 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
8312#endif
8313#ifdef SQLITE_ENABLE_MULTIPLEX
8314 }else if( strcmp(z,"-multiplex")==0 ){
8315 extern int sqlite3_multiple_initialize(const char*,int);
8316 sqlite3_multiplex_initialize(0, 1);
8317#endif
8318 }else if( strcmp(z,"-mmap")==0 ){
8319 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8320 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
8321 }else if( strcmp(z,"-vfs")==0 ){
8322 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
8323 if( pVfs ){
8324 sqlite3_vfs_register(pVfs, 1);
8325 }else{
8326 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
8327 exit(1);
8328 }
drh3baed312018-03-08 18:14:41 +00008329#ifdef SQLITE_HAVE_ZLIB
drh8682e122018-01-07 20:38:10 +00008330 }else if( strcmp(z,"-zip")==0 ){
8331 data.openMode = SHELL_OPEN_ZIPFILE;
8332#endif
8333 }else if( strcmp(z,"-append")==0 ){
8334 data.openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00008335 }else if( strcmp(z,"-readonly")==0 ){
8336 data.openMode = SHELL_OPEN_READONLY;
drhda57d962018-03-05 19:34:05 +00008337#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00008338 }else if( strncmp(z, "-A",2)==0 ){
drhda57d962018-03-05 19:34:05 +00008339 /* All remaining command-line arguments are passed to the ".archive"
8340 ** command, so ignore them */
8341 break;
8342#endif
drh2ce15c32017-07-11 13:34:40 +00008343 }
8344 }
8345 if( data.zDbFilename==0 ){
8346#ifndef SQLITE_OMIT_MEMORYDB
8347 data.zDbFilename = ":memory:";
8348 warnInmemoryDb = argc==1;
8349#else
8350 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
8351 return 1;
8352#endif
8353 }
8354 data.out = stdout;
drh8682e122018-01-07 20:38:10 +00008355 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +00008356
8357 /* Go ahead and open the database file if it already exists. If the
8358 ** file does not exist, delay opening it. This prevents empty database
8359 ** files from being created if a user mistypes the database name argument
8360 ** to the sqlite command-line tool.
8361 */
8362 if( access(data.zDbFilename, 0)==0 ){
8363 open_db(&data, 0);
8364 }
8365
8366 /* Process the initialization file if there is one. If no -init option
8367 ** is given on the command line, look for a file named ~/.sqliterc and
8368 ** try to process it.
8369 */
8370 process_sqliterc(&data,zInitFile);
8371
8372 /* Make a second pass through the command-line argument and set
8373 ** options. This second pass is delayed until after the initialization
8374 ** file is processed so that the command-line arguments will override
8375 ** settings in the initialization file.
8376 */
8377 for(i=1; i<argc; i++){
8378 char *z = argv[i];
8379 if( z[0]!='-' ) continue;
8380 if( z[1]=='-' ){ z++; }
8381 if( strcmp(z,"-init")==0 ){
8382 i++;
8383 }else if( strcmp(z,"-html")==0 ){
8384 data.mode = MODE_Html;
8385 }else if( strcmp(z,"-list")==0 ){
8386 data.mode = MODE_List;
8387 }else if( strcmp(z,"-quote")==0 ){
8388 data.mode = MODE_Quote;
8389 }else if( strcmp(z,"-line")==0 ){
8390 data.mode = MODE_Line;
8391 }else if( strcmp(z,"-column")==0 ){
8392 data.mode = MODE_Column;
8393 }else if( strcmp(z,"-csv")==0 ){
8394 data.mode = MODE_Csv;
8395 memcpy(data.colSeparator,",",2);
drh3baed312018-03-08 18:14:41 +00008396#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00008397 }else if( strcmp(z,"-zip")==0 ){
8398 data.openMode = SHELL_OPEN_ZIPFILE;
8399#endif
8400 }else if( strcmp(z,"-append")==0 ){
8401 data.openMode = SHELL_OPEN_APPENDVFS;
drh2ce15c32017-07-11 13:34:40 +00008402 }else if( strcmp(z,"-ascii")==0 ){
8403 data.mode = MODE_Ascii;
8404 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8405 SEP_Unit);
8406 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8407 SEP_Record);
8408 }else if( strcmp(z,"-separator")==0 ){
8409 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
8410 "%s",cmdline_option_value(argc,argv,++i));
8411 }else if( strcmp(z,"-newline")==0 ){
8412 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
8413 "%s",cmdline_option_value(argc,argv,++i));
8414 }else if( strcmp(z,"-nullvalue")==0 ){
8415 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
8416 "%s",cmdline_option_value(argc,argv,++i));
8417 }else if( strcmp(z,"-header")==0 ){
8418 data.showHeader = 1;
8419 }else if( strcmp(z,"-noheader")==0 ){
8420 data.showHeader = 0;
8421 }else if( strcmp(z,"-echo")==0 ){
8422 ShellSetFlag(&data, SHFLG_Echo);
8423 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +00008424 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +00008425 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +00008426 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +00008427 }else if( strcmp(z,"-stats")==0 ){
8428 data.statsOn = 1;
8429 }else if( strcmp(z,"-scanstats")==0 ){
8430 data.scanstatsOn = 1;
8431 }else if( strcmp(z,"-backslash")==0 ){
8432 /* Undocumented command-line option: -backslash
8433 ** Causes C-style backslash escapes to be evaluated in SQL statements
8434 ** prior to sending the SQL into SQLite. Useful for injecting
8435 ** crazy bytes in the middle of SQL statements for testing and debugging.
8436 */
8437 ShellSetFlag(&data, SHFLG_Backslash);
8438 }else if( strcmp(z,"-bail")==0 ){
8439 bail_on_error = 1;
8440 }else if( strcmp(z,"-version")==0 ){
8441 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8442 return 0;
8443 }else if( strcmp(z,"-interactive")==0 ){
8444 stdin_is_interactive = 1;
8445 }else if( strcmp(z,"-batch")==0 ){
8446 stdin_is_interactive = 0;
8447 }else if( strcmp(z,"-heap")==0 ){
8448 i++;
drh2ce15c32017-07-11 13:34:40 +00008449 }else if( strcmp(z,"-pagecache")==0 ){
8450 i+=2;
8451 }else if( strcmp(z,"-lookaside")==0 ){
8452 i+=2;
8453 }else if( strcmp(z,"-mmap")==0 ){
8454 i++;
8455 }else if( strcmp(z,"-vfs")==0 ){
8456 i++;
8457#ifdef SQLITE_ENABLE_VFSTRACE
8458 }else if( strcmp(z,"-vfstrace")==0 ){
8459 i++;
8460#endif
8461#ifdef SQLITE_ENABLE_MULTIPLEX
8462 }else if( strcmp(z,"-multiplex")==0 ){
8463 i++;
8464#endif
8465 }else if( strcmp(z,"-help")==0 ){
8466 usage(1);
8467 }else if( strcmp(z,"-cmd")==0 ){
8468 /* Run commands that follow -cmd first and separately from commands
8469 ** that simply appear on the command-line. This seems goofy. It would
8470 ** be better if all commands ran in the order that they appear. But
8471 ** we retain the goofy behavior for historical compatibility. */
8472 if( i==argc-1 ) break;
8473 z = cmdline_option_value(argc,argv,++i);
8474 if( z[0]=='.' ){
8475 rc = do_meta_command(z, &data);
8476 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
8477 }else{
8478 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00008479 rc = shell_exec(&data, z, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008480 if( zErrMsg!=0 ){
8481 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8482 if( bail_on_error ) return rc!=0 ? rc : 1;
8483 }else if( rc!=0 ){
8484 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
8485 if( bail_on_error ) return rc;
8486 }
8487 }
drhda57d962018-03-05 19:34:05 +00008488#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00008489 }else if( strncmp(z, "-A", 2)==0 ){
drhda57d962018-03-05 19:34:05 +00008490 if( nCmd>0 ){
8491 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
8492 " with \"%s\"\n", z);
8493 return 1;
8494 }
drh93b77312018-03-05 20:20:22 +00008495 open_db(&data, 0);
8496 if( z[2] ){
8497 argv[i] = &z[2];
8498 arDotCommand(&data, argv+(i-1), argc-(i-1));
8499 }else{
8500 arDotCommand(&data, argv+i, argc-i);
8501 }
drhda57d962018-03-05 19:34:05 +00008502 readStdin = 0;
8503 break;
8504#endif
drh2ce15c32017-07-11 13:34:40 +00008505 }else{
8506 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
8507 raw_printf(stderr,"Use -help for a list of options.\n");
8508 return 1;
8509 }
8510 data.cMode = data.mode;
8511 }
8512
8513 if( !readStdin ){
8514 /* Run all arguments that do not begin with '-' as if they were separate
8515 ** command-line inputs, except for the argToSkip argument which contains
8516 ** the database filename.
8517 */
8518 for(i=0; i<nCmd; i++){
8519 if( azCmd[i][0]=='.' ){
8520 rc = do_meta_command(azCmd[i], &data);
8521 if( rc ) return rc==2 ? 0 : rc;
8522 }else{
8523 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00008524 rc = shell_exec(&data, azCmd[i], &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008525 if( zErrMsg!=0 ){
8526 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8527 return rc!=0 ? rc : 1;
8528 }else if( rc!=0 ){
8529 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
8530 return rc;
8531 }
8532 }
8533 }
8534 free(azCmd);
8535 }else{
8536 /* Run commands received from standard input
8537 */
8538 if( stdin_is_interactive ){
8539 char *zHome;
8540 char *zHistory = 0;
8541 int nHistory;
8542 printf(
8543 "SQLite version %s %.19s\n" /*extra-version-info*/
8544 "Enter \".help\" for usage hints.\n",
8545 sqlite3_libversion(), sqlite3_sourceid()
8546 );
8547 if( warnInmemoryDb ){
8548 printf("Connected to a ");
8549 printBold("transient in-memory database");
8550 printf(".\nUse \".open FILENAME\" to reopen on a "
8551 "persistent database.\n");
8552 }
8553 zHome = find_home_dir(0);
8554 if( zHome ){
8555 nHistory = strlen30(zHome) + 20;
8556 if( (zHistory = malloc(nHistory))!=0 ){
8557 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8558 }
8559 }
8560 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +00008561#if HAVE_READLINE || HAVE_EDITLINE
8562 rl_attempted_completion_function = readline_completion;
8563#elif HAVE_LINENOISE
8564 linenoiseSetCompletionCallback(linenoise_completion);
8565#endif
drh2ce15c32017-07-11 13:34:40 +00008566 rc = process_input(&data, 0);
8567 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +00008568 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +00008569 shell_write_history(zHistory);
8570 free(zHistory);
8571 }
8572 }else{
8573 rc = process_input(&data, stdin);
8574 }
8575 }
8576 set_table_name(&data, 0);
8577 if( data.db ){
8578 session_close_all(&data);
8579 sqlite3_close(data.db);
8580 }
8581 sqlite3_free(data.zFreeOnClose);
8582 find_home_dir(1);
drh536c3452018-01-11 00:38:39 +00008583 output_reset(&data);
8584 data.doXdgOpen = 0;
drh13c20932018-01-10 21:41:55 +00008585 clearTempFile(&data);
drh2ce15c32017-07-11 13:34:40 +00008586#if !SQLITE_SHELL_IS_UTF8
mistachkinf7e867c2018-02-26 16:49:20 +00008587 for(i=0; i<argc; i++) free(argv[i]);
8588 free(argv);
drh2ce15c32017-07-11 13:34:40 +00008589#endif
8590 return rc;
8591}