blob: 05ce02d605d75f20e98c6be2cfb06c487441809b [file] [log] [blame]
drh2ce15c32017-07-11 13:34:40 +00001/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Warning pragmas copied from msvc.h in the core.
22*/
23#if defined(_MSC_VER)
24#pragma warning(disable : 4054)
25#pragma warning(disable : 4055)
26#pragma warning(disable : 4100)
27#pragma warning(disable : 4127)
28#pragma warning(disable : 4130)
29#pragma warning(disable : 4152)
30#pragma warning(disable : 4189)
31#pragma warning(disable : 4206)
32#pragma warning(disable : 4210)
33#pragma warning(disable : 4232)
34#pragma warning(disable : 4244)
35#pragma warning(disable : 4305)
36#pragma warning(disable : 4306)
37#pragma warning(disable : 4702)
38#pragma warning(disable : 4706)
39#endif /* defined(_MSC_VER) */
40
41/*
42** No support for loadable extensions in VxWorks.
43*/
44#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45# define SQLITE_OMIT_LOAD_EXTENSION 1
46#endif
47
48/*
49** Enable large-file support for fopen() and friends on unix.
50*/
51#ifndef SQLITE_DISABLE_LFS
52# define _LARGE_FILE 1
53# ifndef _FILE_OFFSET_BITS
54# define _FILE_OFFSET_BITS 64
55# endif
56# define _LARGEFILE_SOURCE 1
57#endif
58
59#include <stdlib.h>
60#include <string.h>
61#include <stdio.h>
62#include <assert.h>
63#include "sqlite3.h"
drh1e506b52018-01-05 21:01:37 +000064typedef sqlite3_int64 i64;
65typedef sqlite3_uint64 u64;
drh1fa6d9f2018-01-06 21:46:01 +000066typedef unsigned char u8;
drh2ce15c32017-07-11 13:34:40 +000067#if SQLITE_USER_AUTHENTICATION
68# include "sqlite3userauth.h"
69#endif
70#include <ctype.h>
71#include <stdarg.h>
72
73#if !defined(_WIN32) && !defined(WIN32)
74# include <signal.h>
75# if !defined(__RTP__) && !defined(_WRS_KERNEL)
76# include <pwd.h>
77# endif
mistachkinacae8c32018-01-05 20:08:46 +000078#endif
mistachkin562f0c82018-01-09 00:28:24 +000079#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
drh2ce15c32017-07-11 13:34:40 +000080# include <unistd.h>
mistachkinacae8c32018-01-05 20:08:46 +000081# include <dirent.h>
mistachkin1e8487d2018-07-22 06:25:35 +000082# define GETPID getpid
mistachkin562f0c82018-01-09 00:28:24 +000083# if defined(__MINGW32__)
mistachkinacae8c32018-01-05 20:08:46 +000084# define DIRENT dirent
mistachkin2f74b3c2018-01-05 20:26:06 +000085# ifndef S_ISLNK
86# define S_ISLNK(mode) (0)
87# endif
mistachkinacae8c32018-01-05 20:08:46 +000088# endif
mistachkin1e8487d2018-07-22 06:25:35 +000089#else
90# define GETPID (int)GetCurrentProcessId
drh2ce15c32017-07-11 13:34:40 +000091#endif
mistachkindfdfd8c2018-01-04 22:46:08 +000092#include <sys/types.h>
93#include <sys/stat.h>
drh2ce15c32017-07-11 13:34:40 +000094
95#if HAVE_READLINE
96# include <readline/readline.h>
97# include <readline/history.h>
98#endif
99
100#if HAVE_EDITLINE
101# include <editline/readline.h>
102#endif
103
104#if HAVE_EDITLINE || HAVE_READLINE
105
106# define shell_add_history(X) add_history(X)
107# define shell_read_history(X) read_history(X)
108# define shell_write_history(X) write_history(X)
109# define shell_stifle_history(X) stifle_history(X)
110# define shell_readline(X) readline(X)
111
112#elif HAVE_LINENOISE
113
114# include "linenoise.h"
115# define shell_add_history(X) linenoiseHistoryAdd(X)
116# define shell_read_history(X) linenoiseHistoryLoad(X)
117# define shell_write_history(X) linenoiseHistorySave(X)
118# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
119# define shell_readline(X) linenoise(X)
120
121#else
122
123# define shell_read_history(X)
124# define shell_write_history(X)
125# define shell_stifle_history(X)
126
127# define SHELL_USE_LOCAL_GETLINE 1
128#endif
129
130
131#if defined(_WIN32) || defined(WIN32)
132# include <io.h>
133# include <fcntl.h>
134# define isatty(h) _isatty(h)
135# ifndef access
136# define access(f,m) _access((f),(m))
137# endif
mistachkince2052b2018-03-23 00:31:53 +0000138# ifndef unlink
139# define unlink _unlink
140# endif
drhc5ea2d42019-01-22 16:44:59 +0000141# ifndef strdup
142# define strdup _strdup
143# endif
drh2ce15c32017-07-11 13:34:40 +0000144# undef popen
145# define popen _popen
146# undef pclose
147# define pclose _pclose
148#else
149 /* Make sure isatty() has a prototype. */
150 extern int isatty(int);
151
152# if !defined(__RTP__) && !defined(_WRS_KERNEL)
153 /* popen and pclose are not C89 functions and so are
154 ** sometimes omitted from the <stdio.h> header */
155 extern FILE *popen(const char*,const char*);
156 extern int pclose(FILE*);
157# else
158# define SQLITE_OMIT_POPEN 1
159# endif
160#endif
161
162#if defined(_WIN32_WCE)
163/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
164 * thus we always assume that we have a console. That can be
165 * overridden with the -batch command line option.
166 */
167#define isatty(x) 1
168#endif
169
170/* ctype macros that work with signed characters */
171#define IsSpace(X) isspace((unsigned char)X)
172#define IsDigit(X) isdigit((unsigned char)X)
173#define ToLower(X) (char)tolower((unsigned char)X)
174
175#if defined(_WIN32) || defined(WIN32)
176#include <windows.h>
177
178/* string conversion routines only needed on Win32 */
179extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
180extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
181extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
182extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
183#endif
184
185/* On Windows, we normally run with output mode of TEXT so that \n characters
186** are automatically translated into \r\n. However, this behavior needs
187** to be disabled in some cases (ex: when generating CSV output and when
188** rendering quoted strings that contain \n characters). The following
189** routines take care of that.
190*/
191#if defined(_WIN32) || defined(WIN32)
192static void setBinaryMode(FILE *file, int isOutput){
193 if( isOutput ) fflush(file);
194 _setmode(_fileno(file), _O_BINARY);
195}
196static void setTextMode(FILE *file, int isOutput){
197 if( isOutput ) fflush(file);
198 _setmode(_fileno(file), _O_TEXT);
199}
200#else
201# define setBinaryMode(X,Y)
202# define setTextMode(X,Y)
203#endif
204
205
206/* True if the timer is enabled */
207static int enableTimer = 0;
208
209/* Return the current wall-clock time */
210static sqlite3_int64 timeOfDay(void){
211 static sqlite3_vfs *clockVfs = 0;
212 sqlite3_int64 t;
213 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
214 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
215 clockVfs->xCurrentTimeInt64(clockVfs, &t);
216 }else{
217 double r;
218 clockVfs->xCurrentTime(clockVfs, &r);
219 t = (sqlite3_int64)(r*86400000.0);
220 }
221 return t;
222}
223
224#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
225#include <sys/time.h>
226#include <sys/resource.h>
227
228/* VxWorks does not support getrusage() as far as we can determine */
229#if defined(_WRS_KERNEL) || defined(__RTP__)
230struct rusage {
231 struct timeval ru_utime; /* user CPU time used */
232 struct timeval ru_stime; /* system CPU time used */
233};
234#define getrusage(A,B) memset(B,0,sizeof(*B))
235#endif
236
237/* Saved resource information for the beginning of an operation */
238static struct rusage sBegin; /* CPU time at start */
239static sqlite3_int64 iBegin; /* Wall-clock time at start */
240
241/*
242** Begin timing an operation
243*/
244static void beginTimer(void){
245 if( enableTimer ){
246 getrusage(RUSAGE_SELF, &sBegin);
247 iBegin = timeOfDay();
248 }
249}
250
251/* Return the difference of two time_structs in seconds */
252static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
253 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
254 (double)(pEnd->tv_sec - pStart->tv_sec);
255}
256
257/*
258** Print the timing results.
259*/
260static void endTimer(void){
261 if( enableTimer ){
262 sqlite3_int64 iEnd = timeOfDay();
263 struct rusage sEnd;
264 getrusage(RUSAGE_SELF, &sEnd);
265 printf("Run Time: real %.3f user %f sys %f\n",
266 (iEnd - iBegin)*0.001,
267 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
268 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
269 }
270}
271
272#define BEGIN_TIMER beginTimer()
273#define END_TIMER endTimer()
274#define HAS_TIMER 1
275
276#elif (defined(_WIN32) || defined(WIN32))
277
278/* Saved resource information for the beginning of an operation */
279static HANDLE hProcess;
280static FILETIME ftKernelBegin;
281static FILETIME ftUserBegin;
282static sqlite3_int64 ftWallBegin;
283typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
284 LPFILETIME, LPFILETIME);
285static GETPROCTIMES getProcessTimesAddr = NULL;
286
287/*
288** Check to see if we have timer support. Return 1 if necessary
289** support found (or found previously).
290*/
291static int hasTimer(void){
292 if( getProcessTimesAddr ){
293 return 1;
294 } else {
295 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
296 ** versions. See if the version we are running on has it, and if it
297 ** does, save off a pointer to it and the current process handle.
298 */
299 hProcess = GetCurrentProcess();
300 if( hProcess ){
301 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
302 if( NULL != hinstLib ){
303 getProcessTimesAddr =
304 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
305 if( NULL != getProcessTimesAddr ){
306 return 1;
307 }
308 FreeLibrary(hinstLib);
309 }
310 }
311 }
312 return 0;
313}
314
315/*
316** Begin timing an operation
317*/
318static void beginTimer(void){
319 if( enableTimer && getProcessTimesAddr ){
320 FILETIME ftCreation, ftExit;
321 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
322 &ftKernelBegin,&ftUserBegin);
323 ftWallBegin = timeOfDay();
324 }
325}
326
327/* Return the difference of two FILETIME structs in seconds */
328static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
329 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
330 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
331 return (double) ((i64End - i64Start) / 10000000.0);
332}
333
334/*
335** Print the timing results.
336*/
337static void endTimer(void){
338 if( enableTimer && getProcessTimesAddr){
339 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
340 sqlite3_int64 ftWallEnd = timeOfDay();
341 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
342 printf("Run Time: real %.3f user %f sys %f\n",
343 (ftWallEnd - ftWallBegin)*0.001,
344 timeDiff(&ftUserBegin, &ftUserEnd),
345 timeDiff(&ftKernelBegin, &ftKernelEnd));
346 }
347}
348
349#define BEGIN_TIMER beginTimer()
350#define END_TIMER endTimer()
351#define HAS_TIMER hasTimer()
352
353#else
354#define BEGIN_TIMER
355#define END_TIMER
356#define HAS_TIMER 0
357#endif
358
359/*
360** Used to prevent warnings about unused parameters
361*/
362#define UNUSED_PARAMETER(x) (void)(x)
363
364/*
drh5af06982018-01-10 00:53:55 +0000365** Number of elements in an array
366*/
367#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
368
369/*
drh2ce15c32017-07-11 13:34:40 +0000370** If the following flag is set, then command execution stops
371** at an error if we are not interactive.
372*/
373static int bail_on_error = 0;
374
375/*
376** Threat stdin as an interactive input if the following variable
377** is true. Otherwise, assume stdin is connected to a file or pipe.
378*/
379static int stdin_is_interactive = 1;
380
381/*
382** On Windows systems we have to know if standard output is a console
383** in order to translate UTF-8 into MBCS. The following variable is
384** true if translation is required.
385*/
386static int stdout_is_console = 1;
387
388/*
389** The following is the open SQLite database. We make a pointer
390** to this database a static variable so that it can be accessed
391** by the SIGINT handler to interrupt database processing.
392*/
393static sqlite3 *globalDb = 0;
394
395/*
396** True if an interrupt (Control-C) has been received.
397*/
398static volatile int seenInterrupt = 0;
399
400/*
401** This is the name of our program. It is set in main(), used
402** in a number of other places, mostly for error messages.
403*/
404static char *Argv0;
405
406/*
407** Prompt strings. Initialized in main. Settable with
408** .prompt main continue
409*/
410static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
411static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
412
413/*
414** Render output like fprintf(). Except, if the output is going to the
415** console and if this is running on a Windows machine, translate the
416** output from UTF-8 into MBCS.
417*/
418#if defined(_WIN32) || defined(WIN32)
419void utf8_printf(FILE *out, const char *zFormat, ...){
420 va_list ap;
421 va_start(ap, zFormat);
422 if( stdout_is_console && (out==stdout || out==stderr) ){
423 char *z1 = sqlite3_vmprintf(zFormat, ap);
424 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
425 sqlite3_free(z1);
426 fputs(z2, out);
427 sqlite3_free(z2);
428 }else{
429 vfprintf(out, zFormat, ap);
430 }
431 va_end(ap);
432}
433#elif !defined(utf8_printf)
434# define utf8_printf fprintf
435#endif
436
437/*
438** Render output like fprintf(). This should not be used on anything that
439** includes string formatting (e.g. "%s").
440*/
441#if !defined(raw_printf)
442# define raw_printf fprintf
443#endif
444
drh4b5345c2018-04-24 13:07:40 +0000445/* Indicate out-of-memory and exit. */
446static void shell_out_of_memory(void){
447 raw_printf(stderr,"Error: out of memory\n");
448 exit(1);
449}
450
drh2ce15c32017-07-11 13:34:40 +0000451/*
452** Write I/O traces to the following stream.
453*/
454#ifdef SQLITE_ENABLE_IOTRACE
455static FILE *iotrace = 0;
456#endif
457
458/*
459** This routine works like printf in that its first argument is a
460** format string and subsequent arguments are values to be substituted
461** in place of % fields. The result of formatting this string
462** is written to iotrace.
463*/
464#ifdef SQLITE_ENABLE_IOTRACE
465static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
466 va_list ap;
467 char *z;
468 if( iotrace==0 ) return;
469 va_start(ap, zFormat);
470 z = sqlite3_vmprintf(zFormat, ap);
471 va_end(ap);
472 utf8_printf(iotrace, "%s", z);
473 sqlite3_free(z);
474}
475#endif
476
477/*
478** Output string zUtf to stream pOut as w characters. If w is negative,
479** then right-justify the text. W is the width in UTF-8 characters, not
480** in bytes. This is different from the %*.*s specification in printf
481** since with %*.*s the width is measured in bytes, not characters.
482*/
483static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
484 int i;
485 int n;
486 int aw = w<0 ? -w : w;
487 char zBuf[1000];
488 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
489 for(i=n=0; zUtf[i]; i++){
490 if( (zUtf[i]&0xc0)!=0x80 ){
491 n++;
492 if( n==aw ){
493 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
494 break;
495 }
496 }
497 }
498 if( n>=aw ){
499 utf8_printf(pOut, "%.*s", i, zUtf);
500 }else if( w<0 ){
501 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
502 }else{
503 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
504 }
505}
506
507
508/*
509** Determines if a string is a number of not.
510*/
511static int isNumber(const char *z, int *realnum){
512 if( *z=='-' || *z=='+' ) z++;
513 if( !IsDigit(*z) ){
514 return 0;
515 }
516 z++;
517 if( realnum ) *realnum = 0;
518 while( IsDigit(*z) ){ z++; }
519 if( *z=='.' ){
520 z++;
521 if( !IsDigit(*z) ) return 0;
522 while( IsDigit(*z) ){ z++; }
523 if( realnum ) *realnum = 1;
524 }
525 if( *z=='e' || *z=='E' ){
526 z++;
527 if( *z=='+' || *z=='-' ) z++;
528 if( !IsDigit(*z) ) return 0;
529 while( IsDigit(*z) ){ z++; }
530 if( realnum ) *realnum = 1;
531 }
532 return *z==0;
533}
534
535/*
536** Compute a string length that is limited to what can be stored in
537** lower 30 bits of a 32-bit signed integer.
538*/
539static int strlen30(const char *z){
540 const char *z2 = z;
541 while( *z2 ){ z2++; }
542 return 0x3fffffff & (int)(z2 - z);
543}
544
545/*
546** Return the length of a string in characters. Multibyte UTF8 characters
547** count as a single character.
548*/
549static int strlenChar(const char *z){
550 int n = 0;
551 while( *z ){
552 if( (0xc0&*(z++))!=0x80 ) n++;
553 }
554 return n;
555}
556
557/*
558** This routine reads a line of text from FILE in, stores
559** the text in memory obtained from malloc() and returns a pointer
560** to the text. NULL is returned at end of file, or if malloc()
561** fails.
562**
563** If zLine is not NULL then it is a malloced buffer returned from
564** a previous call to this routine that may be reused.
565*/
566static char *local_getline(char *zLine, FILE *in){
567 int nLine = zLine==0 ? 0 : 100;
568 int n = 0;
569
570 while( 1 ){
571 if( n+100>nLine ){
572 nLine = nLine*2 + 100;
573 zLine = realloc(zLine, nLine);
drh884406b2018-07-29 18:56:35 +0000574 if( zLine==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000575 }
576 if( fgets(&zLine[n], nLine - n, in)==0 ){
577 if( n==0 ){
578 free(zLine);
579 return 0;
580 }
581 zLine[n] = 0;
582 break;
583 }
584 while( zLine[n] ) n++;
585 if( n>0 && zLine[n-1]=='\n' ){
586 n--;
587 if( n>0 && zLine[n-1]=='\r' ) n--;
588 zLine[n] = 0;
589 break;
590 }
591 }
592#if defined(_WIN32) || defined(WIN32)
593 /* For interactive input on Windows systems, translate the
594 ** multi-byte characterset characters into UTF-8. */
595 if( stdin_is_interactive && in==stdin ){
596 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
597 if( zTrans ){
598 int nTrans = strlen30(zTrans)+1;
599 if( nTrans>nLine ){
600 zLine = realloc(zLine, nTrans);
drh884406b2018-07-29 18:56:35 +0000601 if( zLine==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000602 }
603 memcpy(zLine, zTrans, nTrans);
604 sqlite3_free(zTrans);
605 }
606 }
607#endif /* defined(_WIN32) || defined(WIN32) */
608 return zLine;
609}
610
611/*
612** Retrieve a single line of input text.
613**
614** If in==0 then read from standard input and prompt before each line.
615** If isContinuation is true, then a continuation prompt is appropriate.
616** If isContinuation is zero, then the main prompt should be used.
617**
618** If zPrior is not NULL then it is a buffer from a prior call to this
619** routine that can be reused.
620**
621** The result is stored in space obtained from malloc() and must either
622** be freed by the caller or else passed back into this routine via the
623** zPrior argument for reuse.
624*/
625static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
626 char *zPrompt;
627 char *zResult;
628 if( in!=0 ){
629 zResult = local_getline(zPrior, in);
630 }else{
631 zPrompt = isContinuation ? continuePrompt : mainPrompt;
632#if SHELL_USE_LOCAL_GETLINE
633 printf("%s", zPrompt);
634 fflush(stdout);
635 zResult = local_getline(zPrior, stdin);
636#else
637 free(zPrior);
638 zResult = shell_readline(zPrompt);
639 if( zResult && *zResult ) shell_add_history(zResult);
640#endif
641 }
642 return zResult;
643}
drh5af06982018-01-10 00:53:55 +0000644
645
646/*
647** Return the value of a hexadecimal digit. Return -1 if the input
648** is not a hex digit.
649*/
650static int hexDigitValue(char c){
651 if( c>='0' && c<='9' ) return c - '0';
652 if( c>='a' && c<='f' ) return c - 'a' + 10;
653 if( c>='A' && c<='F' ) return c - 'A' + 10;
654 return -1;
655}
656
657/*
658** Interpret zArg as an integer value, possibly with suffixes.
659*/
660static sqlite3_int64 integerValue(const char *zArg){
661 sqlite3_int64 v = 0;
662 static const struct { char *zSuffix; int iMult; } aMult[] = {
663 { "KiB", 1024 },
664 { "MiB", 1024*1024 },
665 { "GiB", 1024*1024*1024 },
666 { "KB", 1000 },
667 { "MB", 1000000 },
668 { "GB", 1000000000 },
669 { "K", 1000 },
670 { "M", 1000000 },
671 { "G", 1000000000 },
672 };
673 int i;
674 int isNeg = 0;
675 if( zArg[0]=='-' ){
676 isNeg = 1;
677 zArg++;
678 }else if( zArg[0]=='+' ){
679 zArg++;
680 }
681 if( zArg[0]=='0' && zArg[1]=='x' ){
682 int x;
683 zArg += 2;
684 while( (x = hexDigitValue(zArg[0]))>=0 ){
685 v = (v<<4) + x;
686 zArg++;
687 }
688 }else{
689 while( IsDigit(zArg[0]) ){
690 v = v*10 + zArg[0] - '0';
691 zArg++;
692 }
693 }
694 for(i=0; i<ArraySize(aMult); i++){
695 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
696 v *= aMult[i].iMult;
697 break;
698 }
699 }
700 return isNeg? -v : v;
701}
702
drh2ce15c32017-07-11 13:34:40 +0000703/*
704** A variable length string to which one can append text.
705*/
706typedef struct ShellText ShellText;
707struct ShellText {
708 char *z;
709 int n;
710 int nAlloc;
711};
712
713/*
714** Initialize and destroy a ShellText object
715*/
716static void initText(ShellText *p){
717 memset(p, 0, sizeof(*p));
718}
719static void freeText(ShellText *p){
720 free(p->z);
721 initText(p);
722}
723
724/* zIn is either a pointer to a NULL-terminated string in memory obtained
725** from malloc(), or a NULL pointer. The string pointed to by zAppend is
726** added to zIn, and the result returned in memory obtained from malloc().
727** zIn, if it was not NULL, is freed.
728**
729** If the third argument, quote, is not '\0', then it is used as a
730** quote character for zAppend.
731*/
732static void appendText(ShellText *p, char const *zAppend, char quote){
733 int len;
734 int i;
735 int nAppend = strlen30(zAppend);
736
737 len = nAppend+p->n+1;
738 if( quote ){
739 len += 2;
740 for(i=0; i<nAppend; i++){
741 if( zAppend[i]==quote ) len++;
742 }
743 }
744
745 if( p->n+len>=p->nAlloc ){
746 p->nAlloc = p->nAlloc*2 + len + 20;
747 p->z = realloc(p->z, p->nAlloc);
drh884406b2018-07-29 18:56:35 +0000748 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000749 }
750
751 if( quote ){
752 char *zCsr = p->z+p->n;
753 *zCsr++ = quote;
754 for(i=0; i<nAppend; i++){
755 *zCsr++ = zAppend[i];
756 if( zAppend[i]==quote ) *zCsr++ = quote;
757 }
758 *zCsr++ = quote;
759 p->n = (int)(zCsr - p->z);
760 *zCsr = '\0';
761 }else{
762 memcpy(p->z+p->n, zAppend, nAppend);
763 p->n += nAppend;
764 p->z[p->n] = '\0';
765 }
766}
767
768/*
769** Attempt to determine if identifier zName needs to be quoted, either
770** because it contains non-alphanumeric characters, or because it is an
771** SQLite keyword. Be conservative in this estimate: When in doubt assume
772** that quoting is required.
773**
774** Return '"' if quoting is required. Return 0 if no quoting is required.
775*/
776static char quoteChar(const char *zName){
drhfc0ec3e2018-04-25 19:02:48 +0000777 int i;
drh2ce15c32017-07-11 13:34:40 +0000778 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
779 for(i=0; zName[i]; i++){
780 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
781 }
drhfc0ec3e2018-04-25 19:02:48 +0000782 return sqlite3_keyword_check(zName, i) ? '"' : 0;
drh2ce15c32017-07-11 13:34:40 +0000783}
784
785/*
drh667a2a22018-01-02 00:04:37 +0000786** Construct a fake object name and column list to describe the structure
787** of the view, virtual table, or table valued function zSchema.zName.
drhceba7922018-01-01 21:28:25 +0000788*/
drh667a2a22018-01-02 00:04:37 +0000789static char *shellFakeSchema(
drhceba7922018-01-01 21:28:25 +0000790 sqlite3 *db, /* The database connection containing the vtab */
791 const char *zSchema, /* Schema of the database holding the vtab */
792 const char *zName /* The name of the virtual table */
793){
794 sqlite3_stmt *pStmt = 0;
795 char *zSql;
drh1d315cf2018-01-01 21:49:43 +0000796 ShellText s;
797 char cQuote;
798 char *zDiv = "(";
drh667a2a22018-01-02 00:04:37 +0000799 int nRow = 0;
drhceba7922018-01-01 21:28:25 +0000800
drh1d315cf2018-01-01 21:49:43 +0000801 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
802 zSchema ? zSchema : "main", zName);
drhceba7922018-01-01 21:28:25 +0000803 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
804 sqlite3_free(zSql);
drh1d315cf2018-01-01 21:49:43 +0000805 initText(&s);
806 if( zSchema ){
807 cQuote = quoteChar(zSchema);
808 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
809 appendText(&s, zSchema, cQuote);
810 appendText(&s, ".", 0);
drhceba7922018-01-01 21:28:25 +0000811 }
drh1d315cf2018-01-01 21:49:43 +0000812 cQuote = quoteChar(zName);
813 appendText(&s, zName, cQuote);
814 while( sqlite3_step(pStmt)==SQLITE_ROW ){
815 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
drh667a2a22018-01-02 00:04:37 +0000816 nRow++;
drh1d315cf2018-01-01 21:49:43 +0000817 appendText(&s, zDiv, 0);
818 zDiv = ",";
819 cQuote = quoteChar(zCol);
820 appendText(&s, zCol, cQuote);
821 }
822 appendText(&s, ")", 0);
drhceba7922018-01-01 21:28:25 +0000823 sqlite3_finalize(pStmt);
drh667a2a22018-01-02 00:04:37 +0000824 if( nRow==0 ){
825 freeText(&s);
826 s.z = 0;
827 }
drh1d315cf2018-01-01 21:49:43 +0000828 return s.z;
drhceba7922018-01-01 21:28:25 +0000829}
830
831/*
drh667a2a22018-01-02 00:04:37 +0000832** SQL function: shell_module_schema(X)
833**
834** Return a fake schema for the table-valued function or eponymous virtual
835** table X.
836*/
837static void shellModuleSchema(
838 sqlite3_context *pCtx,
839 int nVal,
840 sqlite3_value **apVal
841){
842 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
843 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
drhb9685182018-01-17 13:15:23 +0000844 UNUSED_PARAMETER(nVal);
drh667a2a22018-01-02 00:04:37 +0000845 if( zFake ){
dandcfbff92018-01-08 17:05:32 +0000846 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
drh667a2a22018-01-02 00:04:37 +0000847 -1, sqlite3_free);
dandcfbff92018-01-08 17:05:32 +0000848 free(zFake);
drh667a2a22018-01-02 00:04:37 +0000849 }
850}
851
852/*
drh2ce15c32017-07-11 13:34:40 +0000853** SQL function: shell_add_schema(S,X)
854**
855** Add the schema name X to the CREATE statement in S and return the result.
856** Examples:
857**
858** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
859**
860** Also works on
861**
862** CREATE INDEX
863** CREATE UNIQUE INDEX
864** CREATE VIEW
865** CREATE TRIGGER
866** CREATE VIRTUAL TABLE
867**
868** This UDF is used by the .schema command to insert the schema name of
869** attached databases into the middle of the sqlite_master.sql field.
870*/
871static void shellAddSchemaName(
872 sqlite3_context *pCtx,
873 int nVal,
874 sqlite3_value **apVal
875){
876 static const char *aPrefix[] = {
877 "TABLE",
878 "INDEX",
879 "UNIQUE INDEX",
880 "VIEW",
881 "TRIGGER",
882 "VIRTUAL TABLE"
883 };
884 int i = 0;
885 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
886 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
drh667a2a22018-01-02 00:04:37 +0000887 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
drhceba7922018-01-01 21:28:25 +0000888 sqlite3 *db = sqlite3_context_db_handle(pCtx);
drhb9685182018-01-17 13:15:23 +0000889 UNUSED_PARAMETER(nVal);
drh2ce15c32017-07-11 13:34:40 +0000890 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
drh89997982017-07-11 18:11:33 +0000891 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
drh2ce15c32017-07-11 13:34:40 +0000892 int n = strlen30(aPrefix[i]);
893 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
drhceba7922018-01-01 21:28:25 +0000894 char *z = 0;
drh667a2a22018-01-02 00:04:37 +0000895 char *zFake = 0;
drhceba7922018-01-01 21:28:25 +0000896 if( zSchema ){
897 char cQuote = quoteChar(zSchema);
898 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
899 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
900 }else{
901 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
902 }
drh2ce15c32017-07-11 13:34:40 +0000903 }
drh667a2a22018-01-02 00:04:37 +0000904 if( zName
905 && aPrefix[i][0]=='V'
906 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
907 ){
908 if( z==0 ){
dandcfbff92018-01-08 17:05:32 +0000909 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
drh667a2a22018-01-02 00:04:37 +0000910 }else{
dandcfbff92018-01-08 17:05:32 +0000911 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
drh667a2a22018-01-02 00:04:37 +0000912 }
dandcfbff92018-01-08 17:05:32 +0000913 free(zFake);
drhceba7922018-01-01 21:28:25 +0000914 }
915 if( z ){
916 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
917 return;
918 }
drh2ce15c32017-07-11 13:34:40 +0000919 }
920 }
921 }
922 sqlite3_result_value(pCtx, apVal[0]);
923}
924
925/*
926** The source code for several run-time loadable extensions is inserted
927** below by the ../tool/mkshellc.tcl script. Before processing that included
928** code, we need to override some macros to make the included program code
929** work here in the middle of this regular program.
930*/
931#define SQLITE_EXTENSION_INIT1
drh89997982017-07-11 18:11:33 +0000932#define SQLITE_EXTENSION_INIT2(X) (void)(X)
drh2ce15c32017-07-11 13:34:40 +0000933
mistachkinacae8c32018-01-05 20:08:46 +0000934#if defined(_WIN32) && defined(_MSC_VER)
drh03491a12018-01-07 21:58:17 +0000935INCLUDE test_windirent.h
mistachkindfdfd8c2018-01-04 22:46:08 +0000936INCLUDE test_windirent.c
937#define dirent DIRENT
mistachkindfdfd8c2018-01-04 22:46:08 +0000938#endif
drh2ce15c32017-07-11 13:34:40 +0000939INCLUDE ../ext/misc/shathree.c
940INCLUDE ../ext/misc/fileio.c
drh56eb09b2017-07-11 13:59:07 +0000941INCLUDE ../ext/misc/completion.c
drh8682e122018-01-07 20:38:10 +0000942INCLUDE ../ext/misc/appendvfs.c
drh50b910a2019-01-21 14:55:03 +0000943INCLUDE ../ext/misc/memtrace.c
dan72afc3c2017-12-05 18:32:40 +0000944#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +0000945INCLUDE ../ext/misc/zipfile.c
dand1b51d42017-12-16 19:11:26 +0000946INCLUDE ../ext/misc/sqlar.c
dan72afc3c2017-12-05 18:32:40 +0000947#endif
dan43efc182017-12-19 17:42:13 +0000948INCLUDE ../ext/expert/sqlite3expert.h
949INCLUDE ../ext/expert/sqlite3expert.c
drh2ce15c32017-07-11 13:34:40 +0000950
dan68cb86e2019-04-20 20:57:28 +0000951INCLUDE ../ext/misc/dbdata.c
952
drh2ce15c32017-07-11 13:34:40 +0000953#if defined(SQLITE_ENABLE_SESSION)
954/*
955** State information for a single open session
956*/
957typedef struct OpenSession OpenSession;
958struct OpenSession {
959 char *zName; /* Symbolic name for this session */
960 int nFilter; /* Number of xFilter rejection GLOB patterns */
961 char **azFilter; /* Array of xFilter rejection GLOB patterns */
962 sqlite3_session *p; /* The open session */
963};
964#endif
965
966/*
967** Shell output mode information from before ".explain on",
968** saved so that it can be restored by ".explain off"
969*/
970typedef struct SavedModeInfo SavedModeInfo;
971struct SavedModeInfo {
972 int valid; /* Is there legit data in here? */
973 int mode; /* Mode prior to ".explain on" */
974 int showHeader; /* The ".header" setting prior to ".explain on" */
975 int colWidth[100]; /* Column widths prior to ".explain on" */
976};
977
dan43efc182017-12-19 17:42:13 +0000978typedef struct ExpertInfo ExpertInfo;
979struct ExpertInfo {
980 sqlite3expert *pExpert;
981 int bVerbose;
982};
983
drh4b5345c2018-04-24 13:07:40 +0000984/* A single line in the EQP output */
985typedef struct EQPGraphRow EQPGraphRow;
986struct EQPGraphRow {
drhe2ca99c2018-05-02 00:33:43 +0000987 int iEqpId; /* ID for this row */
988 int iParentId; /* ID of the parent row */
drh4b5345c2018-04-24 13:07:40 +0000989 EQPGraphRow *pNext; /* Next row in sequence */
990 char zText[1]; /* Text to display for this row */
991};
992
993/* All EQP output is collected into an instance of the following */
994typedef struct EQPGraph EQPGraph;
995struct EQPGraph {
996 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
997 EQPGraphRow *pLast; /* Last element of the pRow list */
998 char zPrefix[100]; /* Graph prefix */
999};
1000
drh2ce15c32017-07-11 13:34:40 +00001001/*
1002** State information about the database connection is contained in an
1003** instance of the following structure.
1004*/
1005typedef struct ShellState ShellState;
1006struct ShellState {
1007 sqlite3 *db; /* The database */
drh1fa6d9f2018-01-06 21:46:01 +00001008 u8 autoExplain; /* Automatically turn on .explain mode */
1009 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
drhe2ca99c2018-05-02 00:33:43 +00001010 u8 autoEQPtest; /* autoEQP is in test mode */
drhb4e50392019-01-26 15:40:04 +00001011 u8 autoEQPtrace; /* autoEQP is in trace mode */
drh1fa6d9f2018-01-06 21:46:01 +00001012 u8 statsOn; /* True to display memory stats before each finalize */
1013 u8 scanstatsOn; /* True to display scan stats before each finalize */
1014 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
drh13c20932018-01-10 21:41:55 +00001015 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
drh4b5345c2018-04-24 13:07:40 +00001016 u8 nEqpLevel; /* Depth of the EQP output graph */
drh707821f2018-12-05 13:39:06 +00001017 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
drh4b5345c2018-04-24 13:07:40 +00001018 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
drh2ce15c32017-07-11 13:34:40 +00001019 int outCount; /* Revert to stdout when reaching zero */
1020 int cnt; /* Number of records displayed so far */
drh2c8ee022018-12-13 18:59:30 +00001021 int lineno; /* Line number of last line read from in */
drh60379d42018-12-13 18:30:01 +00001022 FILE *in; /* Read commands from this stream */
drh2ce15c32017-07-11 13:34:40 +00001023 FILE *out; /* Write results here */
1024 FILE *traceOut; /* Output for sqlite3_trace() */
1025 int nErr; /* Number of errors seen */
1026 int mode; /* An output mode setting */
drh3c484e82018-01-10 22:27:21 +00001027 int modePrior; /* Saved mode */
drh2ce15c32017-07-11 13:34:40 +00001028 int cMode; /* temporary output mode for the current query */
1029 int normalMode; /* Output mode before ".explain on" */
1030 int writableSchema; /* True if PRAGMA writable_schema=ON */
1031 int showHeader; /* True to show column names in List or Column mode */
1032 int nCheck; /* Number of ".check" commands run */
drh3f83f592019-02-04 14:53:18 +00001033 unsigned nProgress; /* Number of progress callbacks encountered */
1034 unsigned mxProgress; /* Maximum progress callbacks before failing */
1035 unsigned flgProgress; /* Flags for the progress callback */
drh2ce15c32017-07-11 13:34:40 +00001036 unsigned shellFlgs; /* Various flags */
drh6ca64482019-01-22 16:06:20 +00001037 sqlite3_int64 szMax; /* --maxsize argument to .open */
drh2ce15c32017-07-11 13:34:40 +00001038 char *zDestTable; /* Name of destination table when MODE_Insert */
drh13c20932018-01-10 21:41:55 +00001039 char *zTempFile; /* Temporary file that might need deleting */
drh2ce15c32017-07-11 13:34:40 +00001040 char zTestcase[30]; /* Name of current test case */
1041 char colSeparator[20]; /* Column separator character for several modes */
1042 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drh3c484e82018-01-10 22:27:21 +00001043 char colSepPrior[20]; /* Saved column separator */
1044 char rowSepPrior[20]; /* Saved row separator */
drh2ce15c32017-07-11 13:34:40 +00001045 int colWidth[100]; /* Requested width of each column when in column mode*/
1046 int actualWidth[100]; /* Actual width of each column */
1047 char nullValue[20]; /* The text to print when a NULL comes back from
1048 ** the database */
1049 char outfile[FILENAME_MAX]; /* Filename for *out */
1050 const char *zDbFilename; /* name of the database file */
1051 char *zFreeOnClose; /* Filename to free when closing */
1052 const char *zVfs; /* Name of VFS to use */
1053 sqlite3_stmt *pStmt; /* Current statement if any. */
1054 FILE *pLog; /* Write log output here */
1055 int *aiIndent; /* Array of indents used in MODE_Explain */
1056 int nIndent; /* Size of array aiIndent[] */
1057 int iIndent; /* Index of current op in aiIndent[] */
drh4b5345c2018-04-24 13:07:40 +00001058 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
drh2ce15c32017-07-11 13:34:40 +00001059#if defined(SQLITE_ENABLE_SESSION)
1060 int nSession; /* Number of active sessions */
1061 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1062#endif
dan43efc182017-12-19 17:42:13 +00001063 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
drh2ce15c32017-07-11 13:34:40 +00001064};
1065
drh1fa6d9f2018-01-06 21:46:01 +00001066
drhada70452017-12-21 21:02:27 +00001067/* Allowed values for ShellState.autoEQP
1068*/
drhe2ca99c2018-05-02 00:33:43 +00001069#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1070#define AUTOEQP_on 1 /* Automatic EQP is on */
1071#define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1072#define AUTOEQP_full 3 /* Show full EXPLAIN */
drhada70452017-12-21 21:02:27 +00001073
drh1fa6d9f2018-01-06 21:46:01 +00001074/* Allowed values for ShellState.openMode
1075*/
drh60f34ae2018-10-30 13:19:49 +00001076#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1077#define SHELL_OPEN_NORMAL 1 /* Normal database file */
1078#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1079#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1080#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1081#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
drh33746482018-12-13 15:06:26 +00001082#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
drh1fa6d9f2018-01-06 21:46:01 +00001083
drh707821f2018-12-05 13:39:06 +00001084/* Allowed values for ShellState.eTraceType
1085*/
1086#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1087#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1088#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1089
drh3f83f592019-02-04 14:53:18 +00001090/* Bits in the ShellState.flgProgress variable */
drhfc4eeef2019-02-05 19:48:46 +00001091#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1092#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1093 ** callback limit is reached, and for each
1094 ** top-level SQL statement */
1095#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
drh3f83f592019-02-04 14:53:18 +00001096
drh2ce15c32017-07-11 13:34:40 +00001097/*
1098** These are the allowed shellFlgs values
1099*/
drhb2a0f752017-08-28 15:51:35 +00001100#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1101#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1102#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1103#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1104#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1105#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1106#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
dan68cb86e2019-04-20 20:57:28 +00001107#define SHFLG_Recover 0x00000080 /* .dump is --recover */
drh2ce15c32017-07-11 13:34:40 +00001108
1109/*
1110** Macros for testing and setting shellFlgs
1111*/
1112#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1113#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1114#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1115
1116/*
1117** These are the allowed modes.
1118*/
1119#define MODE_Line 0 /* One column per line. Blank line between records */
1120#define MODE_Column 1 /* One record per line in neat columns */
1121#define MODE_List 2 /* One record per line with a separator */
1122#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1123#define MODE_Html 4 /* Generate an XHTML table */
1124#define MODE_Insert 5 /* Generate SQL "insert" statements */
1125#define MODE_Quote 6 /* Quote values as for SQL */
1126#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1127#define MODE_Csv 8 /* Quote strings, numbers are plain */
1128#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1129#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1130#define MODE_Pretty 11 /* Pretty-print schemas */
drh4b5345c2018-04-24 13:07:40 +00001131#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
drh2ce15c32017-07-11 13:34:40 +00001132
1133static const char *modeDescr[] = {
1134 "line",
1135 "column",
1136 "list",
1137 "semi",
1138 "html",
1139 "insert",
1140 "quote",
1141 "tcl",
1142 "csv",
1143 "explain",
1144 "ascii",
1145 "prettyprint",
drh4b5345c2018-04-24 13:07:40 +00001146 "eqp"
drh2ce15c32017-07-11 13:34:40 +00001147};
1148
1149/*
1150** These are the column/row/line separators used by the various
1151** import/export modes.
1152*/
1153#define SEP_Column "|"
1154#define SEP_Row "\n"
1155#define SEP_Tab "\t"
1156#define SEP_Space " "
1157#define SEP_Comma ","
1158#define SEP_CrLf "\r\n"
1159#define SEP_Unit "\x1F"
1160#define SEP_Record "\x1E"
1161
1162/*
drh2ce15c32017-07-11 13:34:40 +00001163** A callback for the sqlite3_log() interface.
1164*/
1165static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1166 ShellState *p = (ShellState*)pArg;
1167 if( p->pLog==0 ) return;
1168 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1169 fflush(p->pLog);
1170}
1171
1172/*
drh634c70f2018-01-10 16:50:18 +00001173** SQL function: shell_putsnl(X)
1174**
1175** Write the text X to the screen (or whatever output is being directed)
1176** adding a newline at the end, and then return X.
1177*/
1178static void shellPutsFunc(
1179 sqlite3_context *pCtx,
1180 int nVal,
1181 sqlite3_value **apVal
1182){
1183 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
drhb9685182018-01-17 13:15:23 +00001184 (void)nVal;
drh634c70f2018-01-10 16:50:18 +00001185 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1186 sqlite3_result_value(pCtx, apVal[0]);
1187}
1188
1189/*
drh97913132018-01-11 00:04:00 +00001190** SQL function: edit(VALUE)
1191** edit(VALUE,EDITOR)
1192**
1193** These steps:
1194**
1195** (1) Write VALUE into a temporary file.
1196** (2) Run program EDITOR on that temporary file.
1197** (3) Read the temporary file back and return its content as the result.
1198** (4) Delete the temporary file
1199**
1200** If the EDITOR argument is omitted, use the value in the VISUAL
1201** environment variable. If still there is no EDITOR, through an error.
1202**
1203** Also throw an error if the EDITOR program returns a non-zero exit code.
1204*/
drh04a28c32018-01-31 01:38:44 +00001205#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00001206static void editFunc(
1207 sqlite3_context *context,
1208 int argc,
1209 sqlite3_value **argv
1210){
1211 const char *zEditor;
1212 char *zTempFile = 0;
1213 sqlite3 *db;
1214 char *zCmd = 0;
1215 int bBin;
1216 int rc;
drhf018fd52018-08-06 02:08:53 +00001217 int hasCRNL = 0;
drh97913132018-01-11 00:04:00 +00001218 FILE *f = 0;
1219 sqlite3_int64 sz;
1220 sqlite3_int64 x;
1221 unsigned char *p = 0;
1222
1223 if( argc==2 ){
1224 zEditor = (const char*)sqlite3_value_text(argv[1]);
1225 }else{
1226 zEditor = getenv("VISUAL");
1227 }
1228 if( zEditor==0 ){
1229 sqlite3_result_error(context, "no editor for edit()", -1);
1230 return;
1231 }
1232 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1233 sqlite3_result_error(context, "NULL input to edit()", -1);
1234 return;
1235 }
1236 db = sqlite3_context_db_handle(context);
1237 zTempFile = 0;
1238 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1239 if( zTempFile==0 ){
1240 sqlite3_uint64 r = 0;
1241 sqlite3_randomness(sizeof(r), &r);
1242 zTempFile = sqlite3_mprintf("temp%llx", r);
1243 if( zTempFile==0 ){
1244 sqlite3_result_error_nomem(context);
1245 return;
1246 }
1247 }
1248 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
drhf018fd52018-08-06 02:08:53 +00001249 /* When writing the file to be edited, do \n to \r\n conversions on systems
1250 ** that want \r\n line endings */
drh97913132018-01-11 00:04:00 +00001251 f = fopen(zTempFile, bBin ? "wb" : "w");
1252 if( f==0 ){
1253 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1254 goto edit_func_end;
1255 }
1256 sz = sqlite3_value_bytes(argv[0]);
1257 if( bBin ){
1258 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
1259 }else{
drhf018fd52018-08-06 02:08:53 +00001260 const char *z = (const char*)sqlite3_value_text(argv[0]);
1261 /* Remember whether or not the value originally contained \r\n */
1262 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
drh97913132018-01-11 00:04:00 +00001263 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
1264 }
1265 fclose(f);
1266 f = 0;
1267 if( x!=sz ){
1268 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1269 goto edit_func_end;
1270 }
1271 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1272 if( zCmd==0 ){
1273 sqlite3_result_error_nomem(context);
1274 goto edit_func_end;
1275 }
1276 rc = system(zCmd);
1277 sqlite3_free(zCmd);
1278 if( rc ){
1279 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1280 goto edit_func_end;
1281 }
drhf018fd52018-08-06 02:08:53 +00001282 f = fopen(zTempFile, "rb");
drh97913132018-01-11 00:04:00 +00001283 if( f==0 ){
1284 sqlite3_result_error(context,
1285 "edit() cannot reopen temp file after edit", -1);
1286 goto edit_func_end;
1287 }
1288 fseek(f, 0, SEEK_END);
1289 sz = ftell(f);
1290 rewind(f);
1291 p = sqlite3_malloc64( sz+(bBin==0) );
1292 if( p==0 ){
1293 sqlite3_result_error_nomem(context);
1294 goto edit_func_end;
1295 }
drhf018fd52018-08-06 02:08:53 +00001296 x = fread(p, 1, sz, f);
drh97913132018-01-11 00:04:00 +00001297 fclose(f);
1298 f = 0;
1299 if( x!=sz ){
1300 sqlite3_result_error(context, "could not read back the whole file", -1);
1301 goto edit_func_end;
1302 }
1303 if( bBin ){
mistachkinb71aa092018-01-23 00:05:18 +00001304 sqlite3_result_blob64(context, p, sz, sqlite3_free);
drh97913132018-01-11 00:04:00 +00001305 }else{
dan60bdcf52018-10-03 11:13:30 +00001306 sqlite3_int64 i, j;
drhf018fd52018-08-06 02:08:53 +00001307 if( hasCRNL ){
1308 /* If the original contains \r\n then do no conversions back to \n */
1309 j = sz;
1310 }else{
1311 /* If the file did not originally contain \r\n then convert any new
1312 ** \r\n back into \n */
1313 for(i=j=0; i<sz; i++){
1314 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1315 p[j++] = p[i];
1316 }
1317 sz = j;
1318 p[sz] = 0;
1319 }
mistachkinb71aa092018-01-23 00:05:18 +00001320 sqlite3_result_text64(context, (const char*)p, sz,
1321 sqlite3_free, SQLITE_UTF8);
drh97913132018-01-11 00:04:00 +00001322 }
1323 p = 0;
1324
1325edit_func_end:
1326 if( f ) fclose(f);
1327 unlink(zTempFile);
1328 sqlite3_free(zTempFile);
1329 sqlite3_free(p);
1330}
drh04a28c32018-01-31 01:38:44 +00001331#endif /* SQLITE_NOHAVE_SYSTEM */
drh97913132018-01-11 00:04:00 +00001332
1333/*
drh3c484e82018-01-10 22:27:21 +00001334** Save or restore the current output mode
1335*/
1336static void outputModePush(ShellState *p){
1337 p->modePrior = p->mode;
1338 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1339 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1340}
1341static void outputModePop(ShellState *p){
1342 p->mode = p->modePrior;
1343 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1344 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1345}
1346
1347/*
drh2ce15c32017-07-11 13:34:40 +00001348** Output the given string as a hex-encoded blob (eg. X'1234' )
1349*/
1350static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1351 int i;
1352 char *zBlob = (char *)pBlob;
1353 raw_printf(out,"X'");
1354 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1355 raw_printf(out,"'");
1356}
1357
1358/*
1359** Find a string that is not found anywhere in z[]. Return a pointer
1360** to that string.
1361**
1362** Try to use zA and zB first. If both of those are already found in z[]
1363** then make up some string and store it in the buffer zBuf.
1364*/
1365static const char *unused_string(
1366 const char *z, /* Result must not appear anywhere in z */
1367 const char *zA, const char *zB, /* Try these first */
1368 char *zBuf /* Space to store a generated string */
1369){
1370 unsigned i = 0;
1371 if( strstr(z, zA)==0 ) return zA;
1372 if( strstr(z, zB)==0 ) return zB;
1373 do{
1374 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1375 }while( strstr(z,zBuf)!=0 );
1376 return zBuf;
1377}
1378
1379/*
1380** Output the given string as a quoted string using SQL quoting conventions.
1381**
1382** See also: output_quoted_escaped_string()
1383*/
1384static void output_quoted_string(FILE *out, const char *z){
1385 int i;
1386 char c;
1387 setBinaryMode(out, 1);
1388 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1389 if( c==0 ){
1390 utf8_printf(out,"'%s'",z);
1391 }else{
1392 raw_printf(out, "'");
1393 while( *z ){
1394 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1395 if( c=='\'' ) i++;
1396 if( i ){
1397 utf8_printf(out, "%.*s", i, z);
1398 z += i;
1399 }
1400 if( c=='\'' ){
1401 raw_printf(out, "'");
1402 continue;
1403 }
1404 if( c==0 ){
1405 break;
1406 }
1407 z++;
1408 }
1409 raw_printf(out, "'");
1410 }
1411 setTextMode(out, 1);
1412}
1413
1414/*
1415** Output the given string as a quoted string using SQL quoting conventions.
1416** Additionallly , escape the "\n" and "\r" characters so that they do not
1417** get corrupted by end-of-line translation facilities in some operating
1418** systems.
1419**
1420** This is like output_quoted_string() but with the addition of the \r\n
1421** escape mechanism.
1422*/
1423static void output_quoted_escaped_string(FILE *out, const char *z){
1424 int i;
1425 char c;
1426 setBinaryMode(out, 1);
1427 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1428 if( c==0 ){
1429 utf8_printf(out,"'%s'",z);
1430 }else{
1431 const char *zNL = 0;
1432 const char *zCR = 0;
1433 int nNL = 0;
1434 int nCR = 0;
1435 char zBuf1[20], zBuf2[20];
1436 for(i=0; z[i]; i++){
1437 if( z[i]=='\n' ) nNL++;
1438 if( z[i]=='\r' ) nCR++;
1439 }
1440 if( nNL ){
1441 raw_printf(out, "replace(");
1442 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1443 }
1444 if( nCR ){
1445 raw_printf(out, "replace(");
1446 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1447 }
1448 raw_printf(out, "'");
1449 while( *z ){
1450 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1451 if( c=='\'' ) i++;
1452 if( i ){
1453 utf8_printf(out, "%.*s", i, z);
1454 z += i;
1455 }
1456 if( c=='\'' ){
1457 raw_printf(out, "'");
1458 continue;
1459 }
1460 if( c==0 ){
1461 break;
1462 }
1463 z++;
1464 if( c=='\n' ){
1465 raw_printf(out, "%s", zNL);
1466 continue;
1467 }
1468 raw_printf(out, "%s", zCR);
1469 }
1470 raw_printf(out, "'");
1471 if( nCR ){
1472 raw_printf(out, ",'%s',char(13))", zCR);
1473 }
1474 if( nNL ){
1475 raw_printf(out, ",'%s',char(10))", zNL);
1476 }
1477 }
1478 setTextMode(out, 1);
1479}
1480
1481/*
1482** Output the given string as a quoted according to C or TCL quoting rules.
1483*/
1484static void output_c_string(FILE *out, const char *z){
1485 unsigned int c;
1486 fputc('"', out);
1487 while( (c = *(z++))!=0 ){
1488 if( c=='\\' ){
1489 fputc(c, out);
1490 fputc(c, out);
1491 }else if( c=='"' ){
1492 fputc('\\', out);
1493 fputc('"', out);
1494 }else if( c=='\t' ){
1495 fputc('\\', out);
1496 fputc('t', out);
1497 }else if( c=='\n' ){
1498 fputc('\\', out);
1499 fputc('n', out);
1500 }else if( c=='\r' ){
1501 fputc('\\', out);
1502 fputc('r', out);
1503 }else if( !isprint(c&0xff) ){
1504 raw_printf(out, "\\%03o", c&0xff);
1505 }else{
1506 fputc(c, out);
1507 }
1508 }
1509 fputc('"', out);
1510}
1511
1512/*
1513** Output the given string with characters that are special to
1514** HTML escaped.
1515*/
1516static void output_html_string(FILE *out, const char *z){
1517 int i;
1518 if( z==0 ) z = "";
1519 while( *z ){
1520 for(i=0; z[i]
1521 && z[i]!='<'
1522 && z[i]!='&'
1523 && z[i]!='>'
1524 && z[i]!='\"'
1525 && z[i]!='\'';
1526 i++){}
1527 if( i>0 ){
1528 utf8_printf(out,"%.*s",i,z);
1529 }
1530 if( z[i]=='<' ){
1531 raw_printf(out,"&lt;");
1532 }else if( z[i]=='&' ){
1533 raw_printf(out,"&amp;");
1534 }else if( z[i]=='>' ){
1535 raw_printf(out,"&gt;");
1536 }else if( z[i]=='\"' ){
1537 raw_printf(out,"&quot;");
1538 }else if( z[i]=='\'' ){
1539 raw_printf(out,"&#39;");
1540 }else{
1541 break;
1542 }
1543 z += i + 1;
1544 }
1545}
1546
1547/*
1548** If a field contains any character identified by a 1 in the following
1549** array, then the string must be quoted for CSV.
1550*/
1551static const char needCsvQuote[] = {
1552 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1553 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1554 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1555 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1556 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1557 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1558 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1559 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1560 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1561 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1562 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1563 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1564 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1565 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1566 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1567 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1568};
1569
1570/*
1571** Output a single term of CSV. Actually, p->colSeparator is used for
1572** the separator, which may or may not be a comma. p->nullValue is
1573** the null value. Strings are quoted if necessary. The separator
1574** is only issued if bSep is true.
1575*/
1576static void output_csv(ShellState *p, const char *z, int bSep){
1577 FILE *out = p->out;
1578 if( z==0 ){
1579 utf8_printf(out,"%s",p->nullValue);
1580 }else{
1581 int i;
1582 int nSep = strlen30(p->colSeparator);
1583 for(i=0; z[i]; i++){
1584 if( needCsvQuote[((unsigned char*)z)[i]]
1585 || (z[i]==p->colSeparator[0] &&
1586 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1587 i = 0;
1588 break;
1589 }
1590 }
1591 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001592 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1593 utf8_printf(out, "%s", zQuoted);
1594 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001595 }else{
1596 utf8_printf(out, "%s", z);
1597 }
1598 }
1599 if( bSep ){
1600 utf8_printf(p->out, "%s", p->colSeparator);
1601 }
1602}
1603
drh2ce15c32017-07-11 13:34:40 +00001604/*
1605** This routine runs when the user presses Ctrl-C
1606*/
1607static void interrupt_handler(int NotUsed){
1608 UNUSED_PARAMETER(NotUsed);
1609 seenInterrupt++;
1610 if( seenInterrupt>2 ) exit(1);
1611 if( globalDb ) sqlite3_interrupt(globalDb);
1612}
mistachkinb4bab902017-10-27 17:09:44 +00001613
1614#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1615/*
1616** This routine runs for console events (e.g. Ctrl-C) on Win32
1617*/
1618static BOOL WINAPI ConsoleCtrlHandler(
1619 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1620){
1621 if( dwCtrlType==CTRL_C_EVENT ){
1622 interrupt_handler(0);
1623 return TRUE;
1624 }
1625 return FALSE;
1626}
drh2ce15c32017-07-11 13:34:40 +00001627#endif
1628
1629#ifndef SQLITE_OMIT_AUTHORIZATION
1630/*
1631** When the ".auth ON" is set, the following authorizer callback is
1632** invoked. It always returns SQLITE_OK.
1633*/
1634static int shellAuth(
1635 void *pClientData,
1636 int op,
1637 const char *zA1,
1638 const char *zA2,
1639 const char *zA3,
1640 const char *zA4
1641){
1642 ShellState *p = (ShellState*)pClientData;
1643 static const char *azAction[] = { 0,
1644 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1645 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1646 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1647 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1648 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1649 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1650 "PRAGMA", "READ", "SELECT",
1651 "TRANSACTION", "UPDATE", "ATTACH",
1652 "DETACH", "ALTER_TABLE", "REINDEX",
1653 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1654 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1655 };
1656 int i;
1657 const char *az[4];
1658 az[0] = zA1;
1659 az[1] = zA2;
1660 az[2] = zA3;
1661 az[3] = zA4;
1662 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1663 for(i=0; i<4; i++){
1664 raw_printf(p->out, " ");
1665 if( az[i] ){
1666 output_c_string(p->out, az[i]);
1667 }else{
1668 raw_printf(p->out, "NULL");
1669 }
1670 }
1671 raw_printf(p->out, "\n");
1672 return SQLITE_OK;
1673}
1674#endif
1675
1676/*
1677** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1678**
1679** This routine converts some CREATE TABLE statements for shadow tables
1680** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1681*/
1682static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1683 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1684 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1685 }else{
1686 utf8_printf(out, "%s%s", z, zTail);
1687 }
1688}
1689static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1690 char c = z[n];
1691 z[n] = 0;
1692 printSchemaLine(out, z, zTail);
1693 z[n] = c;
1694}
1695
1696/*
drh11be81d2018-01-06 15:46:20 +00001697** Return true if string z[] has nothing but whitespace and comments to the
1698** end of the first line.
1699*/
1700static int wsToEol(const char *z){
1701 int i;
1702 for(i=0; z[i]; i++){
1703 if( z[i]=='\n' ) return 1;
1704 if( IsSpace(z[i]) ) continue;
1705 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1706 return 0;
1707 }
1708 return 1;
1709}
drh4b5345c2018-04-24 13:07:40 +00001710
1711/*
1712** Add a new entry to the EXPLAIN QUERY PLAN data
1713*/
drhe2ca99c2018-05-02 00:33:43 +00001714static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
drh4b5345c2018-04-24 13:07:40 +00001715 EQPGraphRow *pNew;
1716 int nText = strlen30(zText);
drhe2ca99c2018-05-02 00:33:43 +00001717 if( p->autoEQPtest ){
1718 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1719 }
drh4b5345c2018-04-24 13:07:40 +00001720 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1721 if( pNew==0 ) shell_out_of_memory();
drhe2ca99c2018-05-02 00:33:43 +00001722 pNew->iEqpId = iEqpId;
1723 pNew->iParentId = p2;
drh4b5345c2018-04-24 13:07:40 +00001724 memcpy(pNew->zText, zText, nText+1);
1725 pNew->pNext = 0;
1726 if( p->sGraph.pLast ){
1727 p->sGraph.pLast->pNext = pNew;
1728 }else{
1729 p->sGraph.pRow = pNew;
1730 }
1731 p->sGraph.pLast = pNew;
1732}
1733
1734/*
1735** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1736** in p->sGraph.
1737*/
1738static void eqp_reset(ShellState *p){
1739 EQPGraphRow *pRow, *pNext;
1740 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1741 pNext = pRow->pNext;
1742 sqlite3_free(pRow);
1743 }
1744 memset(&p->sGraph, 0, sizeof(p->sGraph));
1745}
1746
drhe2ca99c2018-05-02 00:33:43 +00001747/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
drh4b5345c2018-04-24 13:07:40 +00001748** pOld, or return the first such line if pOld is NULL
1749*/
drhe2ca99c2018-05-02 00:33:43 +00001750static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
drh4b5345c2018-04-24 13:07:40 +00001751 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
drhe2ca99c2018-05-02 00:33:43 +00001752 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
drh4b5345c2018-04-24 13:07:40 +00001753 return pRow;
1754}
1755
drhe2ca99c2018-05-02 00:33:43 +00001756/* Render a single level of the graph that has iEqpId as its parent. Called
drh4b5345c2018-04-24 13:07:40 +00001757** recursively to render sublevels.
1758*/
drhe2ca99c2018-05-02 00:33:43 +00001759static void eqp_render_level(ShellState *p, int iEqpId){
drh4b5345c2018-04-24 13:07:40 +00001760 EQPGraphRow *pRow, *pNext;
drh4b5345c2018-04-24 13:07:40 +00001761 int n = strlen30(p->sGraph.zPrefix);
1762 char *z;
drhe2ca99c2018-05-02 00:33:43 +00001763 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1764 pNext = eqp_next_row(p, iEqpId, pRow);
drh4b5345c2018-04-24 13:07:40 +00001765 z = pRow->zText;
1766 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
drhe2188f02018-05-07 11:37:34 +00001767 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
drh4b5345c2018-04-24 13:07:40 +00001768 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
drhe2ca99c2018-05-02 00:33:43 +00001769 eqp_render_level(p, pRow->iEqpId);
drh4b5345c2018-04-24 13:07:40 +00001770 p->sGraph.zPrefix[n] = 0;
1771 }
1772 }
1773}
1774
1775/*
1776** Display and reset the EXPLAIN QUERY PLAN data
1777*/
1778static void eqp_render(ShellState *p){
1779 EQPGraphRow *pRow = p->sGraph.pRow;
1780 if( pRow ){
1781 if( pRow->zText[0]=='-' ){
1782 if( pRow->pNext==0 ){
1783 eqp_reset(p);
1784 return;
1785 }
1786 utf8_printf(p->out, "%s\n", pRow->zText+3);
1787 p->sGraph.pRow = pRow->pNext;
1788 sqlite3_free(pRow);
1789 }else{
1790 utf8_printf(p->out, "QUERY PLAN\n");
1791 }
1792 p->sGraph.zPrefix[0] = 0;
1793 eqp_render_level(p, 0);
1794 eqp_reset(p);
1795 }
1796}
drh11be81d2018-01-06 15:46:20 +00001797
drh569b1d92019-02-05 20:51:41 +00001798#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh11be81d2018-01-06 15:46:20 +00001799/*
drh3f83f592019-02-04 14:53:18 +00001800** Progress handler callback.
1801*/
1802static int progress_handler(void *pClientData) {
1803 ShellState *p = (ShellState*)pClientData;
1804 p->nProgress++;
1805 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1806 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
drhfc4eeef2019-02-05 19:48:46 +00001807 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
1808 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
drh3f83f592019-02-04 14:53:18 +00001809 return 1;
1810 }
drhfc4eeef2019-02-05 19:48:46 +00001811 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
drh3f83f592019-02-04 14:53:18 +00001812 raw_printf(p->out, "Progress %u\n", p->nProgress);
1813 }
1814 return 0;
1815}
drh569b1d92019-02-05 20:51:41 +00001816#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00001817
1818/*
drh2ce15c32017-07-11 13:34:40 +00001819** This is the callback routine that the shell
1820** invokes for each row of a query result.
1821*/
1822static int shell_callback(
1823 void *pArg,
1824 int nArg, /* Number of result columns */
1825 char **azArg, /* Text of each result column */
1826 char **azCol, /* Column names */
1827 int *aiType /* Column types */
1828){
1829 int i;
1830 ShellState *p = (ShellState*)pArg;
1831
drhb3c45232017-08-28 14:33:27 +00001832 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001833 switch( p->cMode ){
1834 case MODE_Line: {
1835 int w = 5;
1836 if( azArg==0 ) break;
1837 for(i=0; i<nArg; i++){
1838 int len = strlen30(azCol[i] ? azCol[i] : "");
1839 if( len>w ) w = len;
1840 }
1841 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1842 for(i=0; i<nArg; i++){
1843 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1844 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1845 }
1846 break;
1847 }
1848 case MODE_Explain:
1849 case MODE_Column: {
1850 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1851 const int *colWidth;
1852 int showHdr;
1853 char *rowSep;
1854 if( p->cMode==MODE_Column ){
1855 colWidth = p->colWidth;
1856 showHdr = p->showHeader;
1857 rowSep = p->rowSeparator;
1858 }else{
1859 colWidth = aExplainWidths;
1860 showHdr = 1;
1861 rowSep = SEP_Row;
1862 }
1863 if( p->cnt++==0 ){
1864 for(i=0; i<nArg; i++){
1865 int w, n;
1866 if( i<ArraySize(p->colWidth) ){
1867 w = colWidth[i];
1868 }else{
1869 w = 0;
1870 }
1871 if( w==0 ){
1872 w = strlenChar(azCol[i] ? azCol[i] : "");
1873 if( w<10 ) w = 10;
1874 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1875 if( w<n ) w = n;
1876 }
1877 if( i<ArraySize(p->actualWidth) ){
1878 p->actualWidth[i] = w;
1879 }
1880 if( showHdr ){
1881 utf8_width_print(p->out, w, azCol[i]);
1882 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1883 }
1884 }
1885 if( showHdr ){
1886 for(i=0; i<nArg; i++){
1887 int w;
1888 if( i<ArraySize(p->actualWidth) ){
1889 w = p->actualWidth[i];
1890 if( w<0 ) w = -w;
1891 }else{
1892 w = 10;
1893 }
1894 utf8_printf(p->out,"%-*.*s%s",w,w,
1895 "----------------------------------------------------------"
1896 "----------------------------------------------------------",
1897 i==nArg-1 ? rowSep : " ");
1898 }
1899 }
1900 }
1901 if( azArg==0 ) break;
1902 for(i=0; i<nArg; i++){
1903 int w;
1904 if( i<ArraySize(p->actualWidth) ){
1905 w = p->actualWidth[i];
1906 }else{
1907 w = 10;
1908 }
1909 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1910 w = strlenChar(azArg[i]);
1911 }
1912 if( i==1 && p->aiIndent && p->pStmt ){
1913 if( p->iIndent<p->nIndent ){
1914 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1915 }
1916 p->iIndent++;
1917 }
1918 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1919 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1920 }
1921 break;
1922 }
1923 case MODE_Semi: { /* .schema and .fullschema output */
1924 printSchemaLine(p->out, azArg[0], ";\n");
1925 break;
1926 }
1927 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1928 char *z;
1929 int j;
1930 int nParen = 0;
1931 char cEnd = 0;
1932 char c;
1933 int nLine = 0;
1934 assert( nArg==1 );
1935 if( azArg[0]==0 ) break;
1936 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1937 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1938 ){
1939 utf8_printf(p->out, "%s;\n", azArg[0]);
1940 break;
1941 }
1942 z = sqlite3_mprintf("%s", azArg[0]);
1943 j = 0;
1944 for(i=0; IsSpace(z[i]); i++){}
1945 for(; (c = z[i])!=0; i++){
1946 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001947 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001948 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1949 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1950 j--;
1951 }
1952 z[j++] = c;
1953 }
1954 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1955 z[j] = 0;
1956 if( strlen30(z)>=79 ){
drh11be81d2018-01-06 15:46:20 +00001957 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001958 if( c==cEnd ){
1959 cEnd = 0;
1960 }else if( c=='"' || c=='\'' || c=='`' ){
1961 cEnd = c;
1962 }else if( c=='[' ){
1963 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001964 }else if( c=='-' && z[i+1]=='-' ){
1965 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001966 }else if( c=='(' ){
1967 nParen++;
1968 }else if( c==')' ){
1969 nParen--;
1970 if( nLine>0 && nParen==0 && j>0 ){
1971 printSchemaLineN(p->out, z, j, "\n");
1972 j = 0;
1973 }
1974 }
1975 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001976 if( nParen==1 && cEnd==0
1977 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1978 ){
drh2ce15c32017-07-11 13:34:40 +00001979 if( c=='\n' ) j--;
1980 printSchemaLineN(p->out, z, j, "\n ");
1981 j = 0;
1982 nLine++;
1983 while( IsSpace(z[i+1]) ){ i++; }
1984 }
1985 }
1986 z[j] = 0;
1987 }
1988 printSchemaLine(p->out, z, ";\n");
1989 sqlite3_free(z);
1990 break;
1991 }
1992 case MODE_List: {
1993 if( p->cnt++==0 && p->showHeader ){
1994 for(i=0; i<nArg; i++){
1995 utf8_printf(p->out,"%s%s",azCol[i],
1996 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1997 }
1998 }
1999 if( azArg==0 ) break;
2000 for(i=0; i<nArg; i++){
2001 char *z = azArg[i];
2002 if( z==0 ) z = p->nullValue;
2003 utf8_printf(p->out, "%s", z);
2004 if( i<nArg-1 ){
2005 utf8_printf(p->out, "%s", p->colSeparator);
2006 }else{
2007 utf8_printf(p->out, "%s", p->rowSeparator);
2008 }
2009 }
2010 break;
2011 }
2012 case MODE_Html: {
2013 if( p->cnt++==0 && p->showHeader ){
2014 raw_printf(p->out,"<TR>");
2015 for(i=0; i<nArg; i++){
2016 raw_printf(p->out,"<TH>");
2017 output_html_string(p->out, azCol[i]);
2018 raw_printf(p->out,"</TH>\n");
2019 }
2020 raw_printf(p->out,"</TR>\n");
2021 }
2022 if( azArg==0 ) break;
2023 raw_printf(p->out,"<TR>");
2024 for(i=0; i<nArg; i++){
2025 raw_printf(p->out,"<TD>");
2026 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2027 raw_printf(p->out,"</TD>\n");
2028 }
2029 raw_printf(p->out,"</TR>\n");
2030 break;
2031 }
2032 case MODE_Tcl: {
2033 if( p->cnt++==0 && p->showHeader ){
2034 for(i=0; i<nArg; i++){
2035 output_c_string(p->out,azCol[i] ? azCol[i] : "");
2036 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2037 }
2038 utf8_printf(p->out, "%s", p->rowSeparator);
2039 }
2040 if( azArg==0 ) break;
2041 for(i=0; i<nArg; i++){
2042 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2043 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2044 }
2045 utf8_printf(p->out, "%s", p->rowSeparator);
2046 break;
2047 }
2048 case MODE_Csv: {
2049 setBinaryMode(p->out, 1);
2050 if( p->cnt++==0 && p->showHeader ){
2051 for(i=0; i<nArg; i++){
2052 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2053 }
2054 utf8_printf(p->out, "%s", p->rowSeparator);
2055 }
2056 if( nArg>0 ){
2057 for(i=0; i<nArg; i++){
2058 output_csv(p, azArg[i], i<nArg-1);
2059 }
2060 utf8_printf(p->out, "%s", p->rowSeparator);
2061 }
2062 setTextMode(p->out, 1);
2063 break;
2064 }
2065 case MODE_Insert: {
2066 if( azArg==0 ) break;
2067 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2068 if( p->showHeader ){
2069 raw_printf(p->out,"(");
2070 for(i=0; i<nArg; i++){
2071 if( i>0 ) raw_printf(p->out, ",");
2072 if( quoteChar(azCol[i]) ){
2073 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2074 utf8_printf(p->out, "%s", z);
2075 sqlite3_free(z);
2076 }else{
2077 raw_printf(p->out, "%s", azCol[i]);
2078 }
2079 }
2080 raw_printf(p->out,")");
2081 }
2082 p->cnt++;
2083 for(i=0; i<nArg; i++){
2084 raw_printf(p->out, i>0 ? "," : " VALUES(");
2085 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2086 utf8_printf(p->out,"NULL");
2087 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2088 if( ShellHasFlag(p, SHFLG_Newlines) ){
2089 output_quoted_string(p->out, azArg[i]);
2090 }else{
2091 output_quoted_escaped_string(p->out, azArg[i]);
2092 }
2093 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2094 utf8_printf(p->out,"%s", azArg[i]);
2095 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2096 char z[50];
2097 double r = sqlite3_column_double(p->pStmt, i);
drh2f1f8802018-06-13 17:19:20 +00002098 sqlite3_uint64 ur;
2099 memcpy(&ur,&r,sizeof(r));
2100 if( ur==0x7ff0000000000000LL ){
2101 raw_printf(p->out, "1e999");
2102 }else if( ur==0xfff0000000000000LL ){
2103 raw_printf(p->out, "-1e999");
2104 }else{
2105 sqlite3_snprintf(50,z,"%!.20g", r);
2106 raw_printf(p->out, "%s", z);
2107 }
drh2ce15c32017-07-11 13:34:40 +00002108 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2109 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2110 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2111 output_hex_blob(p->out, pBlob, nBlob);
2112 }else if( isNumber(azArg[i], 0) ){
2113 utf8_printf(p->out,"%s", azArg[i]);
2114 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2115 output_quoted_string(p->out, azArg[i]);
2116 }else{
2117 output_quoted_escaped_string(p->out, azArg[i]);
2118 }
2119 }
2120 raw_printf(p->out,");\n");
2121 break;
2122 }
2123 case MODE_Quote: {
2124 if( azArg==0 ) break;
2125 if( p->cnt==0 && p->showHeader ){
2126 for(i=0; i<nArg; i++){
2127 if( i>0 ) raw_printf(p->out, ",");
2128 output_quoted_string(p->out, azCol[i]);
2129 }
2130 raw_printf(p->out,"\n");
2131 }
2132 p->cnt++;
2133 for(i=0; i<nArg; i++){
2134 if( i>0 ) raw_printf(p->out, ",");
2135 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2136 utf8_printf(p->out,"NULL");
2137 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2138 output_quoted_string(p->out, azArg[i]);
2139 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2140 utf8_printf(p->out,"%s", azArg[i]);
2141 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2142 char z[50];
2143 double r = sqlite3_column_double(p->pStmt, i);
2144 sqlite3_snprintf(50,z,"%!.20g", r);
2145 raw_printf(p->out, "%s", z);
2146 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2147 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2148 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2149 output_hex_blob(p->out, pBlob, nBlob);
2150 }else if( isNumber(azArg[i], 0) ){
2151 utf8_printf(p->out,"%s", azArg[i]);
2152 }else{
2153 output_quoted_string(p->out, azArg[i]);
2154 }
2155 }
2156 raw_printf(p->out,"\n");
2157 break;
2158 }
2159 case MODE_Ascii: {
2160 if( p->cnt++==0 && p->showHeader ){
2161 for(i=0; i<nArg; i++){
2162 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2163 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2164 }
2165 utf8_printf(p->out, "%s", p->rowSeparator);
2166 }
2167 if( azArg==0 ) break;
2168 for(i=0; i<nArg; i++){
2169 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2170 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2171 }
2172 utf8_printf(p->out, "%s", p->rowSeparator);
2173 break;
2174 }
drh4b5345c2018-04-24 13:07:40 +00002175 case MODE_EQP: {
drhe2ca99c2018-05-02 00:33:43 +00002176 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
drh4b5345c2018-04-24 13:07:40 +00002177 break;
2178 }
drh2ce15c32017-07-11 13:34:40 +00002179 }
2180 return 0;
2181}
2182
2183/*
2184** This is the callback routine that the SQLite library
2185** invokes for each row of a query result.
2186*/
2187static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2188 /* since we don't have type info, call the shell_callback with a NULL value */
2189 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2190}
2191
2192/*
2193** This is the callback routine from sqlite3_exec() that appends all
2194** output onto the end of a ShellText object.
2195*/
2196static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2197 ShellText *p = (ShellText*)pArg;
2198 int i;
2199 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00002200 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002201 if( p->n ) appendText(p, "|", 0);
2202 for(i=0; i<nArg; i++){
2203 if( i ) appendText(p, ",", 0);
2204 if( azArg[i] ) appendText(p, azArg[i], 0);
2205 }
2206 return 0;
2207}
2208
2209/*
2210** Generate an appropriate SELFTEST table in the main database.
2211*/
2212static void createSelftestTable(ShellState *p){
2213 char *zErrMsg = 0;
2214 sqlite3_exec(p->db,
2215 "SAVEPOINT selftest_init;\n"
2216 "CREATE TABLE IF NOT EXISTS selftest(\n"
2217 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2218 " op TEXT,\n" /* Operator: memo run */
2219 " cmd TEXT,\n" /* Command text */
2220 " ans TEXT\n" /* Desired answer */
2221 ");"
2222 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2223 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2224 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2225 " 'memo','Tests generated by --init');\n"
2226 "INSERT INTO [_shell$self]\n"
2227 " SELECT 'run',\n"
2228 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2229 "FROM sqlite_master ORDER BY 2'',224))',\n"
2230 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2231 "FROM sqlite_master ORDER BY 2',224));\n"
2232 "INSERT INTO [_shell$self]\n"
2233 " SELECT 'run',"
2234 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2235 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2236 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2237 " FROM (\n"
2238 " SELECT name FROM sqlite_master\n"
2239 " WHERE type='table'\n"
2240 " AND name<>'selftest'\n"
2241 " AND coalesce(rootpage,0)>0\n"
2242 " )\n"
2243 " ORDER BY name;\n"
2244 "INSERT INTO [_shell$self]\n"
2245 " VALUES('run','PRAGMA integrity_check','ok');\n"
2246 "INSERT INTO selftest(tno,op,cmd,ans)"
2247 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2248 "DROP TABLE [_shell$self];"
2249 ,0,0,&zErrMsg);
2250 if( zErrMsg ){
2251 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2252 sqlite3_free(zErrMsg);
2253 }
2254 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2255}
2256
2257
2258/*
2259** Set the destination table field of the ShellState structure to
2260** the name of the table given. Escape any quote characters in the
2261** table name.
2262*/
2263static void set_table_name(ShellState *p, const char *zName){
2264 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00002265 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00002266 char *z;
2267
2268 if( p->zDestTable ){
2269 free(p->zDestTable);
2270 p->zDestTable = 0;
2271 }
2272 if( zName==0 ) return;
2273 cQuote = quoteChar(zName);
2274 n = strlen30(zName);
2275 if( cQuote ) n += n+2;
2276 z = p->zDestTable = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00002277 if( z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002278 n = 0;
2279 if( cQuote ) z[n++] = cQuote;
2280 for(i=0; zName[i]; i++){
2281 z[n++] = zName[i];
2282 if( zName[i]==cQuote ) z[n++] = cQuote;
2283 }
2284 if( cQuote ) z[n++] = cQuote;
2285 z[n] = 0;
2286}
2287
2288
2289/*
2290** Execute a query statement that will generate SQL output. Print
2291** the result columns, comma-separated, on a line and then add a
2292** semicolon terminator to the end of that line.
2293**
2294** If the number of columns is 1 and that column contains text "--"
2295** then write the semicolon on a separate line. That way, if a
2296** "--" comment occurs at the end of the statement, the comment
2297** won't consume the semicolon terminator.
2298*/
2299static int run_table_dump_query(
2300 ShellState *p, /* Query context */
2301 const char *zSelect, /* SELECT statement to extract content */
2302 const char *zFirstRow /* Print before first row, if not NULL */
2303){
2304 sqlite3_stmt *pSelect;
2305 int rc;
2306 int nResult;
2307 int i;
2308 const char *z;
2309 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2310 if( rc!=SQLITE_OK || !pSelect ){
2311 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2312 sqlite3_errmsg(p->db));
2313 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2314 return rc;
2315 }
2316 rc = sqlite3_step(pSelect);
2317 nResult = sqlite3_column_count(pSelect);
2318 while( rc==SQLITE_ROW ){
2319 if( zFirstRow ){
2320 utf8_printf(p->out, "%s", zFirstRow);
2321 zFirstRow = 0;
2322 }
2323 z = (const char*)sqlite3_column_text(pSelect, 0);
2324 utf8_printf(p->out, "%s", z);
2325 for(i=1; i<nResult; i++){
2326 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2327 }
2328 if( z==0 ) z = "";
2329 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2330 if( z[0] ){
2331 raw_printf(p->out, "\n;\n");
2332 }else{
2333 raw_printf(p->out, ";\n");
2334 }
2335 rc = sqlite3_step(pSelect);
2336 }
2337 rc = sqlite3_finalize(pSelect);
2338 if( rc!=SQLITE_OK ){
2339 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2340 sqlite3_errmsg(p->db));
2341 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2342 }
2343 return rc;
2344}
2345
2346/*
2347** Allocate space and save off current error string.
2348*/
2349static char *save_err_msg(
2350 sqlite3 *db /* Database to query */
2351){
2352 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2353 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2354 if( zErrMsg ){
2355 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2356 }
2357 return zErrMsg;
2358}
2359
2360#ifdef __linux__
2361/*
2362** Attempt to display I/O stats on Linux using /proc/PID/io
2363*/
2364static void displayLinuxIoStats(FILE *out){
2365 FILE *in;
2366 char z[200];
2367 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2368 in = fopen(z, "rb");
2369 if( in==0 ) return;
2370 while( fgets(z, sizeof(z), in)!=0 ){
2371 static const struct {
2372 const char *zPattern;
2373 const char *zDesc;
2374 } aTrans[] = {
2375 { "rchar: ", "Bytes received by read():" },
2376 { "wchar: ", "Bytes sent to write():" },
2377 { "syscr: ", "Read() system calls:" },
2378 { "syscw: ", "Write() system calls:" },
2379 { "read_bytes: ", "Bytes read from storage:" },
2380 { "write_bytes: ", "Bytes written to storage:" },
2381 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2382 };
2383 int i;
2384 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00002385 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00002386 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2387 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2388 break;
2389 }
2390 }
2391 }
2392 fclose(in);
2393}
2394#endif
2395
2396/*
2397** Display a single line of status using 64-bit values.
2398*/
2399static void displayStatLine(
2400 ShellState *p, /* The shell context */
2401 char *zLabel, /* Label for this one line */
2402 char *zFormat, /* Format for the result */
2403 int iStatusCtrl, /* Which status to display */
2404 int bReset /* True to reset the stats */
2405){
2406 sqlite3_int64 iCur = -1;
2407 sqlite3_int64 iHiwtr = -1;
2408 int i, nPercent;
2409 char zLine[200];
2410 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2411 for(i=0, nPercent=0; zFormat[i]; i++){
2412 if( zFormat[i]=='%' ) nPercent++;
2413 }
2414 if( nPercent>1 ){
2415 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2416 }else{
2417 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2418 }
2419 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2420}
2421
2422/*
2423** Display memory stats.
2424*/
2425static int display_stats(
2426 sqlite3 *db, /* Database to query */
2427 ShellState *pArg, /* Pointer to ShellState */
2428 int bReset /* True to reset the stats */
2429){
2430 int iCur;
2431 int iHiwtr;
drh393344f2018-03-09 16:37:05 +00002432 FILE *out;
2433 if( pArg==0 || pArg->out==0 ) return 0;
2434 out = pArg->out;
drh2ce15c32017-07-11 13:34:40 +00002435
drh393344f2018-03-09 16:37:05 +00002436 if( pArg->pStmt && (pArg->statsOn & 2) ){
2437 int nCol, i, x;
2438 sqlite3_stmt *pStmt = pArg->pStmt;
2439 char z[100];
2440 nCol = sqlite3_column_count(pStmt);
2441 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2442 for(i=0; i<nCol; i++){
2443 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2444 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002445#ifndef SQLITE_OMIT_DECLTYPE
drh393344f2018-03-09 16:37:05 +00002446 sqlite3_snprintf(30, z+x, "declared type:");
2447 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
drh929cce82018-03-17 16:26:36 +00002448#endif
2449#ifdef SQLITE_ENABLE_COLUMN_METADATA
drh393344f2018-03-09 16:37:05 +00002450 sqlite3_snprintf(30, z+x, "database name:");
2451 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2452 sqlite3_snprintf(30, z+x, "table name:");
2453 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2454 sqlite3_snprintf(30, z+x, "origin name:");
2455 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002456#endif
drh2ce15c32017-07-11 13:34:40 +00002457 }
drh929cce82018-03-17 16:26:36 +00002458 }
drh2ce15c32017-07-11 13:34:40 +00002459
drh393344f2018-03-09 16:37:05 +00002460 displayStatLine(pArg, "Memory Used:",
2461 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2462 displayStatLine(pArg, "Number of Outstanding Allocations:",
2463 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2464 if( pArg->shellFlgs & SHFLG_Pagecache ){
2465 displayStatLine(pArg, "Number of Pcache Pages Used:",
2466 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2467 }
2468 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2469 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2470 displayStatLine(pArg, "Largest Allocation:",
2471 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2472 displayStatLine(pArg, "Largest Pcache Allocation:",
2473 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2474#ifdef YYTRACKMAXSTACKDEPTH
2475 displayStatLine(pArg, "Deepest Parser Stack:",
2476 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2477#endif
2478
2479 if( db ){
drh2ce15c32017-07-11 13:34:40 +00002480 if( pArg->shellFlgs & SHFLG_Lookaside ){
2481 iHiwtr = iCur = -1;
2482 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2483 &iCur, &iHiwtr, bReset);
2484 raw_printf(pArg->out,
2485 "Lookaside Slots Used: %d (max %d)\n",
2486 iCur, iHiwtr);
2487 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2488 &iCur, &iHiwtr, bReset);
2489 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2490 iHiwtr);
2491 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2492 &iCur, &iHiwtr, bReset);
2493 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2494 iHiwtr);
2495 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2496 &iCur, &iHiwtr, bReset);
2497 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2498 iHiwtr);
2499 }
2500 iHiwtr = iCur = -1;
2501 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2502 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2503 iCur);
2504 iHiwtr = iCur = -1;
2505 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2506 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2507 iHiwtr = iCur = -1;
2508 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2509 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2510 iHiwtr = iCur = -1;
2511 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2512 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2513 iHiwtr = iCur = -1;
drhffc78a42018-03-14 14:53:50 +00002514 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2515 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2516 iHiwtr = iCur = -1;
drh2ce15c32017-07-11 13:34:40 +00002517 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2518 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2519 iCur);
2520 iHiwtr = iCur = -1;
2521 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2522 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2523 iCur);
2524 }
2525
drh393344f2018-03-09 16:37:05 +00002526 if( pArg->pStmt ){
drh2ce15c32017-07-11 13:34:40 +00002527 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2528 bReset);
2529 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2530 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2531 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2532 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2533 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2534 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2535 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
drh393344f2018-03-09 16:37:05 +00002536 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
2537 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2538 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2539 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2540 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2541 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
drh2ce15c32017-07-11 13:34:40 +00002542 }
2543
2544#ifdef __linux__
2545 displayLinuxIoStats(pArg->out);
2546#endif
2547
2548 /* Do not remove this machine readable comment: extra-stats-output-here */
2549
2550 return 0;
2551}
2552
2553/*
2554** Display scan stats.
2555*/
2556static void display_scanstats(
2557 sqlite3 *db, /* Database to query */
2558 ShellState *pArg /* Pointer to ShellState */
2559){
2560#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2561 UNUSED_PARAMETER(db);
2562 UNUSED_PARAMETER(pArg);
2563#else
2564 int i, k, n, mx;
2565 raw_printf(pArg->out, "-------- scanstats --------\n");
2566 mx = 0;
2567 for(k=0; k<=mx; k++){
2568 double rEstLoop = 1.0;
2569 for(i=n=0; 1; i++){
2570 sqlite3_stmt *p = pArg->pStmt;
2571 sqlite3_int64 nLoop, nVisit;
2572 double rEst;
2573 int iSid;
2574 const char *zExplain;
2575 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2576 break;
2577 }
2578 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2579 if( iSid>mx ) mx = iSid;
2580 if( iSid!=k ) continue;
2581 if( n==0 ){
2582 rEstLoop = (double)nLoop;
2583 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2584 }
2585 n++;
2586 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2587 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2588 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2589 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2590 rEstLoop *= rEst;
2591 raw_printf(pArg->out,
2592 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2593 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2594 );
2595 }
2596 }
2597 raw_printf(pArg->out, "---------------------------\n");
2598#endif
2599}
2600
2601/*
2602** Parameter azArray points to a zero-terminated array of strings. zStr
2603** points to a single nul-terminated string. Return non-zero if zStr
2604** is equal, according to strcmp(), to any of the strings in the array.
2605** Otherwise, return zero.
2606*/
2607static int str_in_array(const char *zStr, const char **azArray){
2608 int i;
2609 for(i=0; azArray[i]; i++){
2610 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2611 }
2612 return 0;
2613}
2614
2615/*
2616** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2617** and populate the ShellState.aiIndent[] array with the number of
2618** spaces each opcode should be indented before it is output.
2619**
2620** The indenting rules are:
2621**
2622** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2623** all opcodes that occur between the p2 jump destination and the opcode
2624** itself by 2 spaces.
2625**
2626** * For each "Goto", if the jump destination is earlier in the program
2627** and ends on one of:
2628** Yield SeekGt SeekLt RowSetRead Rewind
2629** or if the P1 parameter is one instead of zero,
2630** then indent all opcodes between the earlier instruction
2631** and "Goto" by 2 spaces.
2632*/
2633static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2634 const char *zSql; /* The text of the SQL statement */
2635 const char *z; /* Used to check if this is an EXPLAIN */
2636 int *abYield = 0; /* True if op is an OP_Yield */
2637 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2638 int iOp; /* Index of operation in p->aiIndent[] */
2639
drhf1949b62018-06-07 17:32:59 +00002640 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
drh2ce15c32017-07-11 13:34:40 +00002641 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2642 "Rewind", 0 };
2643 const char *azGoto[] = { "Goto", 0 };
2644
2645 /* Try to figure out if this is really an EXPLAIN statement. If this
2646 ** cannot be verified, return early. */
2647 if( sqlite3_column_count(pSql)!=8 ){
2648 p->cMode = p->mode;
2649 return;
2650 }
2651 zSql = sqlite3_sql(pSql);
2652 if( zSql==0 ) return;
2653 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2654 if( sqlite3_strnicmp(z, "explain", 7) ){
2655 p->cMode = p->mode;
2656 return;
2657 }
2658
2659 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2660 int i;
2661 int iAddr = sqlite3_column_int(pSql, 0);
2662 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2663
2664 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2665 ** p2 is an instruction address, set variable p2op to the index of that
2666 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2667 ** the current instruction is part of a sub-program generated by an
2668 ** SQL trigger or foreign key. */
2669 int p2 = sqlite3_column_int(pSql, 3);
2670 int p2op = (p2 + (iOp-iAddr));
2671
2672 /* Grow the p->aiIndent array as required */
2673 if( iOp>=nAlloc ){
2674 if( iOp==0 ){
2675 /* Do further verfication that this is explain output. Abort if
2676 ** it is not */
2677 static const char *explainCols[] = {
2678 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2679 int jj;
2680 for(jj=0; jj<ArraySize(explainCols); jj++){
2681 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2682 p->cMode = p->mode;
2683 sqlite3_reset(pSql);
2684 return;
2685 }
2686 }
2687 }
2688 nAlloc += 100;
2689 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002690 if( p->aiIndent==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002691 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002692 if( abYield==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002693 }
2694 abYield[iOp] = str_in_array(zOp, azYield);
2695 p->aiIndent[iOp] = 0;
2696 p->nIndent = iOp+1;
2697
2698 if( str_in_array(zOp, azNext) ){
2699 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2700 }
2701 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2702 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2703 ){
2704 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2705 }
2706 }
2707
2708 p->iIndent = 0;
2709 sqlite3_free(abYield);
2710 sqlite3_reset(pSql);
2711}
2712
2713/*
2714** Free the array allocated by explain_data_prepare().
2715*/
2716static void explain_data_delete(ShellState *p){
2717 sqlite3_free(p->aiIndent);
2718 p->aiIndent = 0;
2719 p->nIndent = 0;
2720 p->iIndent = 0;
2721}
2722
2723/*
2724** Disable and restore .wheretrace and .selecttrace settings.
2725*/
2726#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2727extern int sqlite3SelectTrace;
2728static int savedSelectTrace;
2729#endif
2730#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2731extern int sqlite3WhereTrace;
2732static int savedWhereTrace;
2733#endif
2734static void disable_debug_trace_modes(void){
2735#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2736 savedSelectTrace = sqlite3SelectTrace;
2737 sqlite3SelectTrace = 0;
2738#endif
2739#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2740 savedWhereTrace = sqlite3WhereTrace;
2741 sqlite3WhereTrace = 0;
2742#endif
2743}
2744static void restore_debug_trace_modes(void){
2745#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2746 sqlite3SelectTrace = savedSelectTrace;
2747#endif
2748#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2749 sqlite3WhereTrace = savedWhereTrace;
2750#endif
2751}
2752
drh9cb02642019-02-28 20:10:52 +00002753/* Create the TEMP table used to store parameter bindings */
2754static void bind_table_init(ShellState *p){
drh346f4e22019-03-25 21:35:41 +00002755 int wrSchema = 0;
2756 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
2757 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
drh9cb02642019-02-28 20:10:52 +00002758 sqlite3_exec(p->db,
drh65c29fd2019-03-25 21:56:26 +00002759 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
drh9cb02642019-02-28 20:10:52 +00002760 " key TEXT PRIMARY KEY,\n"
2761 " value ANY\n"
2762 ") WITHOUT ROWID;",
2763 0, 0, 0);
drh346f4e22019-03-25 21:35:41 +00002764 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
drh9cb02642019-02-28 20:10:52 +00002765}
2766
drh8b738d02019-02-25 18:43:54 +00002767/*
2768** Bind parameters on a prepared statement.
2769**
2770** Parameter bindings are taken from a TEMP table of the form:
2771**
drh1cb02632019-03-25 22:05:22 +00002772** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
drh8b738d02019-02-25 18:43:54 +00002773** WITHOUT ROWID;
2774**
2775** No bindings occur if this table does not exist. The special character '$'
2776** is included in the table name to help prevent collisions with actual tables.
2777** The table must be in the TEMP schema.
2778*/
2779static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2780 int nVar;
2781 int i;
2782 int rc;
2783 sqlite3_stmt *pQ = 0;
2784
2785 nVar = sqlite3_bind_parameter_count(pStmt);
2786 if( nVar==0 ) return; /* Nothing to do */
drh65c29fd2019-03-25 21:56:26 +00002787 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
drh8b738d02019-02-25 18:43:54 +00002788 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2789 return; /* Parameter table does not exist */
2790 }
2791 rc = sqlite3_prepare_v2(pArg->db,
drh65c29fd2019-03-25 21:56:26 +00002792 "SELECT value FROM temp.sqlite_parameters"
drh8b738d02019-02-25 18:43:54 +00002793 " WHERE key=?1", -1, &pQ, 0);
2794 if( rc || pQ==0 ) return;
2795 for(i=1; i<=nVar; i++){
2796 char zNum[30];
2797 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2798 if( zVar==0 ){
2799 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2800 zVar = zNum;
2801 }
2802 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2803 if( sqlite3_step(pQ)==SQLITE_ROW ){
2804 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2805 }else{
2806 sqlite3_bind_null(pStmt, i);
2807 }
2808 sqlite3_reset(pQ);
2809 }
2810 sqlite3_finalize(pQ);
2811}
2812
drh2ce15c32017-07-11 13:34:40 +00002813/*
2814** Run a prepared statement
2815*/
2816static void exec_prepared_stmt(
2817 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002818 sqlite3_stmt *pStmt /* Statment to run */
drh2ce15c32017-07-11 13:34:40 +00002819){
2820 int rc;
2821
2822 /* perform the first step. this will tell us if we
2823 ** have a result set or not and how wide it is.
2824 */
2825 rc = sqlite3_step(pStmt);
2826 /* if we have a result set... */
2827 if( SQLITE_ROW == rc ){
drha10b9992018-03-09 15:24:33 +00002828 /* allocate space for col name ptr, value ptr, and type */
2829 int nCol = sqlite3_column_count(pStmt);
2830 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2831 if( !pData ){
2832 rc = SQLITE_NOMEM;
drh2ce15c32017-07-11 13:34:40 +00002833 }else{
drha10b9992018-03-09 15:24:33 +00002834 char **azCols = (char **)pData; /* Names of result columns */
2835 char **azVals = &azCols[nCol]; /* Results */
2836 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2837 int i, x;
2838 assert(sizeof(int) <= sizeof(char *));
2839 /* save off ptrs to column names */
2840 for(i=0; i<nCol; i++){
2841 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2842 }
drh2ce15c32017-07-11 13:34:40 +00002843 do{
drha10b9992018-03-09 15:24:33 +00002844 /* extract the data and data types */
2845 for(i=0; i<nCol; i++){
2846 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2847 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2848 azVals[i] = "";
2849 }else{
2850 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2851 }
2852 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2853 rc = SQLITE_NOMEM;
2854 break; /* from for */
2855 }
2856 } /* end for */
2857
2858 /* if data and types extracted successfully... */
2859 if( SQLITE_ROW == rc ){
2860 /* call the supplied callback with the result row data */
2861 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2862 rc = SQLITE_ABORT;
2863 }else{
2864 rc = sqlite3_step(pStmt);
2865 }
2866 }
2867 } while( SQLITE_ROW == rc );
2868 sqlite3_free(pData);
drh2ce15c32017-07-11 13:34:40 +00002869 }
2870 }
2871}
2872
dan6b046be2018-01-09 15:25:55 +00002873#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002874/*
dan43efc182017-12-19 17:42:13 +00002875** This function is called to process SQL if the previous shell command
2876** was ".expert". It passes the SQL in the second argument directly to
2877** the sqlite3expert object.
2878**
2879** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2880** code. In this case, (*pzErr) may be set to point to a buffer containing
2881** an English language error message. It is the responsibility of the
2882** caller to eventually free this buffer using sqlite3_free().
2883*/
2884static int expertHandleSQL(
2885 ShellState *pState,
2886 const char *zSql,
2887 char **pzErr
2888){
2889 assert( pState->expert.pExpert );
2890 assert( pzErr==0 || *pzErr==0 );
2891 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2892}
2893
2894/*
2895** This function is called either to silently clean up the object
2896** created by the ".expert" command (if bCancel==1), or to generate a
2897** report from it and then clean it up (if bCancel==0).
2898**
2899** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2900** code. In this case, (*pzErr) may be set to point to a buffer containing
2901** an English language error message. It is the responsibility of the
2902** caller to eventually free this buffer using sqlite3_free().
2903*/
2904static int expertFinish(
2905 ShellState *pState,
2906 int bCancel,
2907 char **pzErr
2908){
2909 int rc = SQLITE_OK;
2910 sqlite3expert *p = pState->expert.pExpert;
2911 assert( p );
2912 assert( bCancel || pzErr==0 || *pzErr==0 );
2913 if( bCancel==0 ){
2914 FILE *out = pState->out;
2915 int bVerbose = pState->expert.bVerbose;
2916
2917 rc = sqlite3_expert_analyze(p, pzErr);
2918 if( rc==SQLITE_OK ){
2919 int nQuery = sqlite3_expert_count(p);
2920 int i;
2921
2922 if( bVerbose ){
2923 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2924 raw_printf(out, "-- Candidates -----------------------------\n");
2925 raw_printf(out, "%s\n", zCand);
2926 }
2927 for(i=0; i<nQuery; i++){
2928 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2929 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2930 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2931 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2932 if( bVerbose ){
2933 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2934 raw_printf(out, "%s\n\n", zSql);
2935 }
2936 raw_printf(out, "%s\n", zIdx);
2937 raw_printf(out, "%s\n", zEQP);
2938 }
2939 }
2940 }
2941 sqlite3_expert_destroy(p);
2942 pState->expert.pExpert = 0;
2943 return rc;
2944}
2945
dan6b046be2018-01-09 15:25:55 +00002946/*
2947** Implementation of ".expert" dot command.
2948*/
2949static int expertDotCommand(
2950 ShellState *pState, /* Current shell tool state */
2951 char **azArg, /* Array of arguments passed to dot command */
2952 int nArg /* Number of entries in azArg[] */
2953){
2954 int rc = SQLITE_OK;
2955 char *zErr = 0;
2956 int i;
2957 int iSample = 0;
2958
2959 assert( pState->expert.pExpert==0 );
2960 memset(&pState->expert, 0, sizeof(ExpertInfo));
2961
2962 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2963 char *z = azArg[i];
2964 int n;
2965 if( z[0]=='-' && z[1]=='-' ) z++;
2966 n = strlen30(z);
2967 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2968 pState->expert.bVerbose = 1;
2969 }
2970 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2971 if( i==(nArg-1) ){
2972 raw_printf(stderr, "option requires an argument: %s\n", z);
2973 rc = SQLITE_ERROR;
2974 }else{
2975 iSample = (int)integerValue(azArg[++i]);
2976 if( iSample<0 || iSample>100 ){
2977 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2978 rc = SQLITE_ERROR;
2979 }
2980 }
2981 }
2982 else{
2983 raw_printf(stderr, "unknown option: %s\n", z);
2984 rc = SQLITE_ERROR;
2985 }
2986 }
2987
2988 if( rc==SQLITE_OK ){
2989 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2990 if( pState->expert.pExpert==0 ){
2991 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2992 rc = SQLITE_ERROR;
2993 }else{
2994 sqlite3_expert_config(
2995 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2996 );
2997 }
2998 }
2999
3000 return rc;
3001}
3002#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00003003
3004/*
drh2ce15c32017-07-11 13:34:40 +00003005** Execute a statement or set of statements. Print
3006** any result rows/columns depending on the current mode
3007** set via the supplied callback.
3008**
3009** This is very similar to SQLite's built-in sqlite3_exec()
3010** function except it takes a slightly different callback
3011** and callback data argument.
3012*/
3013static int shell_exec(
drh2ce15c32017-07-11 13:34:40 +00003014 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00003015 const char *zSql, /* SQL to be evaluated */
drh2ce15c32017-07-11 13:34:40 +00003016 char **pzErrMsg /* Error msg written here */
3017){
3018 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
3019 int rc = SQLITE_OK; /* Return Code */
3020 int rc2;
3021 const char *zLeftover; /* Tail of unprocessed SQL */
drha10b9992018-03-09 15:24:33 +00003022 sqlite3 *db = pArg->db;
drh2ce15c32017-07-11 13:34:40 +00003023
3024 if( pzErrMsg ){
3025 *pzErrMsg = NULL;
3026 }
3027
dan6b046be2018-01-09 15:25:55 +00003028#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00003029 if( pArg->expert.pExpert ){
3030 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3031 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3032 }
dan6b046be2018-01-09 15:25:55 +00003033#endif
dan43efc182017-12-19 17:42:13 +00003034
drh2ce15c32017-07-11 13:34:40 +00003035 while( zSql[0] && (SQLITE_OK == rc) ){
3036 static const char *zStmtSql;
3037 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3038 if( SQLITE_OK != rc ){
3039 if( pzErrMsg ){
3040 *pzErrMsg = save_err_msg(db);
3041 }
3042 }else{
3043 if( !pStmt ){
3044 /* this happens for a comment or white-space */
3045 zSql = zLeftover;
3046 while( IsSpace(zSql[0]) ) zSql++;
3047 continue;
3048 }
3049 zStmtSql = sqlite3_sql(pStmt);
3050 if( zStmtSql==0 ) zStmtSql = "";
3051 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3052
3053 /* save off the prepared statment handle and reset row count */
3054 if( pArg ){
3055 pArg->pStmt = pStmt;
3056 pArg->cnt = 0;
3057 }
3058
3059 /* echo the sql statement if echo on */
3060 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3061 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3062 }
3063
3064 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drh39c5c4a2019-03-06 14:53:27 +00003065 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
drh2ce15c32017-07-11 13:34:40 +00003066 sqlite3_stmt *pExplain;
3067 char *zEQP;
drhada70452017-12-21 21:02:27 +00003068 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00003069 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00003070 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3071 if( pArg->autoEQP>=AUTOEQP_trigger ){
3072 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3073 }
drh2ce15c32017-07-11 13:34:40 +00003074 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3075 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3076 if( rc==SQLITE_OK ){
3077 while( sqlite3_step(pExplain)==SQLITE_ROW ){
drh4b5345c2018-04-24 13:07:40 +00003078 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
drhe2ca99c2018-05-02 00:33:43 +00003079 int iEqpId = sqlite3_column_int(pExplain, 0);
3080 int iParentId = sqlite3_column_int(pExplain, 1);
drh4b5345c2018-04-24 13:07:40 +00003081 if( zEQPLine[0]=='-' ) eqp_render(pArg);
drhe2ca99c2018-05-02 00:33:43 +00003082 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
drh2ce15c32017-07-11 13:34:40 +00003083 }
drh4b5345c2018-04-24 13:07:40 +00003084 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003085 }
3086 sqlite3_finalize(pExplain);
3087 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00003088 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00003089 /* Also do an EXPLAIN for ".eqp full" mode */
3090 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3091 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3092 if( rc==SQLITE_OK ){
3093 pArg->cMode = MODE_Explain;
3094 explain_data_prepare(pArg, pExplain);
drha10b9992018-03-09 15:24:33 +00003095 exec_prepared_stmt(pArg, pExplain);
drh2ce15c32017-07-11 13:34:40 +00003096 explain_data_delete(pArg);
3097 }
3098 sqlite3_finalize(pExplain);
3099 sqlite3_free(zEQP);
3100 }
drh51efe092018-03-20 12:04:38 +00003101 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3102 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3103 /* Reprepare pStmt before reactiving trace modes */
3104 sqlite3_finalize(pStmt);
3105 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
drh3c49eaf2018-06-07 15:23:43 +00003106 if( pArg ) pArg->pStmt = pStmt;
drh51efe092018-03-20 12:04:38 +00003107 }
drh2ce15c32017-07-11 13:34:40 +00003108 restore_debug_trace_modes();
3109 }
3110
3111 if( pArg ){
3112 pArg->cMode = pArg->mode;
drh4b5345c2018-04-24 13:07:40 +00003113 if( pArg->autoExplain ){
drh39c5c4a2019-03-06 14:53:27 +00003114 if( sqlite3_stmt_isexplain(pStmt)==1 ){
drh4b5345c2018-04-24 13:07:40 +00003115 pArg->cMode = MODE_Explain;
3116 }
drh39c5c4a2019-03-06 14:53:27 +00003117 if( sqlite3_stmt_isexplain(pStmt)==2 ){
drh4b5345c2018-04-24 13:07:40 +00003118 pArg->cMode = MODE_EQP;
3119 }
drh2ce15c32017-07-11 13:34:40 +00003120 }
3121
3122 /* If the shell is currently in ".explain" mode, gather the extra
3123 ** data required to add indents to the output.*/
3124 if( pArg->cMode==MODE_Explain ){
3125 explain_data_prepare(pArg, pStmt);
3126 }
3127 }
3128
drh8b738d02019-02-25 18:43:54 +00003129 bind_prepared_stmt(pArg, pStmt);
drha10b9992018-03-09 15:24:33 +00003130 exec_prepared_stmt(pArg, pStmt);
drh2ce15c32017-07-11 13:34:40 +00003131 explain_data_delete(pArg);
drh4b5345c2018-04-24 13:07:40 +00003132 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003133
3134 /* print usage stats if stats on */
3135 if( pArg && pArg->statsOn ){
3136 display_stats(db, pArg, 0);
3137 }
3138
3139 /* print loop-counters if required */
3140 if( pArg && pArg->scanstatsOn ){
3141 display_scanstats(db, pArg);
3142 }
3143
3144 /* Finalize the statement just executed. If this fails, save a
3145 ** copy of the error message. Otherwise, set zSql to point to the
3146 ** next statement to execute. */
3147 rc2 = sqlite3_finalize(pStmt);
3148 if( rc!=SQLITE_NOMEM ) rc = rc2;
3149 if( rc==SQLITE_OK ){
3150 zSql = zLeftover;
3151 while( IsSpace(zSql[0]) ) zSql++;
3152 }else if( pzErrMsg ){
3153 *pzErrMsg = save_err_msg(db);
3154 }
3155
3156 /* clear saved stmt handle */
3157 if( pArg ){
3158 pArg->pStmt = NULL;
3159 }
3160 }
3161 } /* end while */
3162
3163 return rc;
3164}
3165
3166/*
3167** Release memory previously allocated by tableColumnList().
3168*/
3169static void freeColumnList(char **azCol){
3170 int i;
3171 for(i=1; azCol[i]; i++){
3172 sqlite3_free(azCol[i]);
3173 }
3174 /* azCol[0] is a static string */
3175 sqlite3_free(azCol);
3176}
3177
3178/*
3179** Return a list of pointers to strings which are the names of all
3180** columns in table zTab. The memory to hold the names is dynamically
3181** allocated and must be released by the caller using a subsequent call
3182** to freeColumnList().
3183**
3184** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3185** value that needs to be preserved, then azCol[0] is filled in with the
3186** name of the rowid column.
3187**
3188** The first regular column in the table is azCol[1]. The list is terminated
3189** by an entry with azCol[i]==0.
3190*/
3191static char **tableColumnList(ShellState *p, const char *zTab){
3192 char **azCol = 0;
3193 sqlite3_stmt *pStmt;
3194 char *zSql;
3195 int nCol = 0;
3196 int nAlloc = 0;
3197 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3198 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3199 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3200 int rc;
3201
3202 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3203 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3204 sqlite3_free(zSql);
3205 if( rc ) return 0;
3206 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3207 if( nCol>=nAlloc-2 ){
3208 nAlloc = nAlloc*2 + nCol + 10;
3209 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
drh4b5345c2018-04-24 13:07:40 +00003210 if( azCol==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00003211 }
3212 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3213 if( sqlite3_column_int(pStmt, 5) ){
3214 nPK++;
3215 if( nPK==1
3216 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3217 "INTEGER")==0
3218 ){
3219 isIPK = 1;
3220 }else{
3221 isIPK = 0;
3222 }
3223 }
3224 }
3225 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00003226 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003227 azCol[0] = 0;
3228 azCol[nCol+1] = 0;
3229
3230 /* The decision of whether or not a rowid really needs to be preserved
3231 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3232 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3233 ** rowids on tables where the rowid is inaccessible because there are other
3234 ** columns in the table named "rowid", "_rowid_", and "oid".
3235 */
3236 if( preserveRowid && isIPK ){
3237 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3238 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3239 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3240 ** ROWID aliases. To distinguish these cases, check to see if
3241 ** there is a "pk" entry in "PRAGMA index_list". There will be
3242 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3243 */
3244 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3245 " WHERE origin='pk'", zTab);
3246 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3247 sqlite3_free(zSql);
3248 if( rc ){
3249 freeColumnList(azCol);
3250 return 0;
3251 }
3252 rc = sqlite3_step(pStmt);
3253 sqlite3_finalize(pStmt);
3254 preserveRowid = rc==SQLITE_ROW;
3255 }
3256 if( preserveRowid ){
3257 /* Only preserve the rowid if we can find a name to use for the
3258 ** rowid */
3259 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3260 int i, j;
3261 for(j=0; j<3; j++){
3262 for(i=1; i<=nCol; i++){
3263 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3264 }
3265 if( i>nCol ){
3266 /* At this point, we know that azRowid[j] is not the name of any
3267 ** ordinary column in the table. Verify that azRowid[j] is a valid
3268 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3269 ** tables will fail this last check */
3270 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3271 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3272 break;
3273 }
3274 }
3275 }
3276 return azCol;
3277}
3278
3279/*
3280** Toggle the reverse_unordered_selects setting.
3281*/
3282static void toggleSelectOrder(sqlite3 *db){
3283 sqlite3_stmt *pStmt = 0;
3284 int iSetting = 0;
3285 char zStmt[100];
3286 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3287 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3288 iSetting = sqlite3_column_int(pStmt, 0);
3289 }
3290 sqlite3_finalize(pStmt);
3291 sqlite3_snprintf(sizeof(zStmt), zStmt,
3292 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3293 sqlite3_exec(db, zStmt, 0, 0, 0);
3294}
3295
3296/*
3297** This is a different callback routine used for dumping the database.
3298** Each row received by this callback consists of a table name,
3299** the table type ("index" or "table") and SQL to create the table.
3300** This routine should print text sufficient to recreate the table.
3301*/
3302static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3303 int rc;
3304 const char *zTable;
3305 const char *zType;
3306 const char *zSql;
3307 ShellState *p = (ShellState *)pArg;
3308
3309 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00003310 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003311 zTable = azArg[0];
3312 zType = azArg[1];
3313 zSql = azArg[2];
3314
3315 if( strcmp(zTable, "sqlite_sequence")==0 ){
3316 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3317 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3318 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3319 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3320 return 0;
3321 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3322 char *zIns;
3323 if( !p->writableSchema ){
3324 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3325 p->writableSchema = 1;
3326 }
3327 zIns = sqlite3_mprintf(
3328 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3329 "VALUES('table','%q','%q',0,'%q');",
3330 zTable, zTable, zSql);
3331 utf8_printf(p->out, "%s\n", zIns);
3332 sqlite3_free(zIns);
3333 return 0;
3334 }else{
3335 printSchemaLine(p->out, zSql, ";\n");
3336 }
3337
3338 if( strcmp(zType, "table")==0 ){
3339 ShellText sSelect;
3340 ShellText sTable;
3341 char **azCol;
3342 int i;
3343 char *savedDestTable;
3344 int savedMode;
3345
3346 azCol = tableColumnList(p, zTable);
3347 if( azCol==0 ){
3348 p->nErr++;
3349 return 0;
3350 }
3351
3352 /* Always quote the table name, even if it appears to be pure ascii,
3353 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3354 initText(&sTable);
3355 appendText(&sTable, zTable, quoteChar(zTable));
3356 /* If preserving the rowid, add a column list after the table name.
3357 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3358 ** instead of the usual "INSERT INTO tab VALUES(...)".
3359 */
3360 if( azCol[0] ){
3361 appendText(&sTable, "(", 0);
3362 appendText(&sTable, azCol[0], 0);
3363 for(i=1; azCol[i]; i++){
3364 appendText(&sTable, ",", 0);
3365 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3366 }
3367 appendText(&sTable, ")", 0);
3368 }
3369
3370 /* Build an appropriate SELECT statement */
3371 initText(&sSelect);
3372 appendText(&sSelect, "SELECT ", 0);
3373 if( azCol[0] ){
3374 appendText(&sSelect, azCol[0], 0);
3375 appendText(&sSelect, ",", 0);
3376 }
3377 for(i=1; azCol[i]; i++){
3378 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3379 if( azCol[i+1] ){
3380 appendText(&sSelect, ",", 0);
3381 }
3382 }
3383 freeColumnList(azCol);
3384 appendText(&sSelect, " FROM ", 0);
3385 appendText(&sSelect, zTable, quoteChar(zTable));
3386
3387 savedDestTable = p->zDestTable;
3388 savedMode = p->mode;
3389 p->zDestTable = sTable.z;
3390 p->mode = p->cMode = MODE_Insert;
drha10b9992018-03-09 15:24:33 +00003391 rc = shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003392 if( (rc&0xff)==SQLITE_CORRUPT ){
3393 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3394 toggleSelectOrder(p->db);
drha10b9992018-03-09 15:24:33 +00003395 shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003396 toggleSelectOrder(p->db);
3397 }
3398 p->zDestTable = savedDestTable;
3399 p->mode = savedMode;
3400 freeText(&sTable);
3401 freeText(&sSelect);
3402 if( rc ) p->nErr++;
3403 }
3404 return 0;
3405}
3406
3407/*
3408** Run zQuery. Use dump_callback() as the callback routine so that
3409** the contents of the query are output as SQL statements.
3410**
3411** If we get a SQLITE_CORRUPT error, rerun the query after appending
3412** "ORDER BY rowid DESC" to the end.
3413*/
3414static int run_schema_dump_query(
3415 ShellState *p,
3416 const char *zQuery
3417){
3418 int rc;
3419 char *zErr = 0;
3420 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3421 if( rc==SQLITE_CORRUPT ){
3422 char *zQ2;
3423 int len = strlen30(zQuery);
3424 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3425 if( zErr ){
3426 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3427 sqlite3_free(zErr);
3428 zErr = 0;
3429 }
3430 zQ2 = malloc( len+100 );
3431 if( zQ2==0 ) return rc;
3432 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3433 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3434 if( rc ){
3435 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3436 }else{
3437 rc = SQLITE_CORRUPT;
3438 }
3439 sqlite3_free(zErr);
3440 free(zQ2);
3441 }
3442 return rc;
3443}
3444
3445/*
drh98aa2ab2018-09-26 16:53:51 +00003446** Text of help messages.
3447**
3448** The help text for each individual command begins with a line that starts
3449** with ".". Subsequent lines are supplimental information.
3450**
3451** There must be two or more spaces between the end of the command and the
3452** start of the description of what that command does.
drh2ce15c32017-07-11 13:34:40 +00003453*/
drh98aa2ab2018-09-26 16:53:51 +00003454static const char *(azHelp[]) = {
drhe37c0e12018-01-06 19:19:50 +00003455#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drh98aa2ab2018-09-26 16:53:51 +00003456 ".archive ... Manage SQL archives",
3457 " Each command must have exactly one of the following options:",
3458 " -c, --create Create a new archive",
drhaf5a2e12019-03-25 15:09:19 +00003459 " -u, --update Add files or update files with changed mtime",
drhb17ea912019-03-25 14:24:19 +00003460 " -i, --insert Like -u but always add even if mtime unchanged",
drh98aa2ab2018-09-26 16:53:51 +00003461 " -t, --list List contents of archive",
3462 " -x, --extract Extract files from archive",
3463 " Optional arguments:",
3464 " -v, --verbose Print each filename as it is processed",
3465 " -f FILE, --file FILE Operate on archive FILE (default is current db)",
3466 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS",
3467 " -C DIR, --directory DIR Change to directory DIR to read/extract files",
3468 " -n, --dryrun Show the SQL that would have occurred",
3469 " Examples:",
3470 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar",
3471 " .ar -tf archive.sar # List members of archive.sar",
3472 " .ar -xvf archive.sar # Verbosely extract files from archive.sar",
3473 " See also:",
3474 " http://sqlite.org/cli.html#sqlar_archive_support",
drhe37c0e12018-01-06 19:19:50 +00003475#endif
drh2ce15c32017-07-11 13:34:40 +00003476#ifndef SQLITE_OMIT_AUTHORIZATION
drh98aa2ab2018-09-26 16:53:51 +00003477 ".auth ON|OFF Show authorizer callbacks",
drh2ce15c32017-07-11 13:34:40 +00003478#endif
drh98aa2ab2018-09-26 16:53:51 +00003479 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3480 " --append Use the appendvfs",
drha50bffb2018-12-08 01:09:14 +00003481 " --async Write to FILE without a journal and without fsync()",
drh98aa2ab2018-09-26 16:53:51 +00003482 ".bail on|off Stop after hitting an error. Default OFF",
3483 ".binary on|off Turn binary output on or off. Default OFF",
3484 ".cd DIRECTORY Change the working directory to DIRECTORY",
3485 ".changes on|off Show number of rows changed by SQL",
3486 ".check GLOB Fail if output since .testcase does not match",
3487 ".clone NEWDB Clone data into NEWDB from the existing database",
3488 ".databases List names and files of attached databases",
3489 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3490 ".dbinfo ?DB? Show status information about the database",
drheb7f2a02018-09-26 18:02:32 +00003491 ".dump ?TABLE? ... Render all database content as SQL",
3492 " Options:",
3493 " --preserve-rowids Include ROWID values in the output",
3494 " --newlines Allow unescaped newline characters in output",
3495 " TABLE is LIKE pattern for the tables to dump",
drh98aa2ab2018-09-26 16:53:51 +00003496 ".echo on|off Turn command echo on or off",
drhb4e50392019-01-26 15:40:04 +00003497 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
3498 " Other Modes:",
3499#ifdef SQLITE_DEBUG
3500 " test Show raw EXPLAIN QUERY PLAN output",
3501 " trace Like \"full\" but also enable \"PRAGMA vdbe_trace\"",
3502#endif
3503 " trigger Like \"full\" but also show trigger bytecode",
drh98aa2ab2018-09-26 16:53:51 +00003504 ".excel Display the output of next command in a spreadsheet",
drheb7f2a02018-09-26 18:02:32 +00003505 ".exit ?CODE? Exit this program with return-code CODE",
drh98aa2ab2018-09-26 16:53:51 +00003506 ".expert EXPERIMENTAL. Suggest indexes for specified queries",
drh2ce15c32017-07-11 13:34:40 +00003507/* Because explain mode comes on automatically now, the ".explain" mode
3508** is removed from the help screen. It is still supported for legacy, however */
drh98aa2ab2018-09-26 16:53:51 +00003509/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/
3510 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3511 ".headers on|off Turn display of headers on or off",
3512 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3513 ".import FILE TABLE Import data from FILE into TABLE",
drh2ce15c32017-07-11 13:34:40 +00003514#ifndef SQLITE_OMIT_TEST_CONTROL
drh98aa2ab2018-09-26 16:53:51 +00003515 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
drh2ce15c32017-07-11 13:34:40 +00003516#endif
drh98aa2ab2018-09-26 16:53:51 +00003517 ".indexes ?TABLE? Show names of indexes",
3518 " If TABLE is specified, only show indexes for",
3519 " tables matching TABLE using the LIKE operator.",
drh2ce15c32017-07-11 13:34:40 +00003520#ifdef SQLITE_ENABLE_IOTRACE
drh98aa2ab2018-09-26 16:53:51 +00003521 ".iotrace FILE Enable I/O diagnostic logging to FILE",
drh2ce15c32017-07-11 13:34:40 +00003522#endif
drh98aa2ab2018-09-26 16:53:51 +00003523 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3524 ".lint OPTIONS Report potential schema issues.",
3525 " Options:",
3526 " fkey-indexes Find missing foreign key indexes",
drh2ce15c32017-07-11 13:34:40 +00003527#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh98aa2ab2018-09-26 16:53:51 +00003528 ".load FILE ?ENTRY? Load an extension library",
drh2ce15c32017-07-11 13:34:40 +00003529#endif
drh98aa2ab2018-09-26 16:53:51 +00003530 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3531 ".mode MODE ?TABLE? Set output mode",
3532 " MODE is one of:",
3533 " ascii Columns/rows delimited by 0x1F and 0x1E",
3534 " csv Comma-separated values",
3535 " column Left-aligned columns. (See .width)",
3536 " html HTML <table> code",
3537 " insert SQL insert statements for TABLE",
3538 " line One value per line",
3539 " list Values delimited by \"|\"",
3540 " quote Escape answers as for SQL",
3541 " tabs Tab-separated values",
3542 " tcl TCL list elements",
3543 ".nullvalue STRING Use STRING in place of NULL values",
3544 ".once (-e|-x|FILE) Output for the next SQL command only to FILE",
3545 " If FILE begins with '|' then open as a pipe",
3546 " Other options:",
3547 " -e Invoke system text editor",
3548 " -x Open in a spreadsheet",
3549 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3550 " Options:",
drh60f34ae2018-10-30 13:19:49 +00003551 " --append Use appendvfs to append database to the end of FILE",
drha751f392018-10-30 15:31:22 +00003552#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00003553 " --deserialize Load into memory useing sqlite3_deserialize()",
drh33746482018-12-13 15:06:26 +00003554 " --hexdb Load the output of \"dbtotxt\" as an in-memory database",
drh6ca64482019-01-22 16:06:20 +00003555 " --maxsize N Maximum size for --hexdb or --deserialized database",
drha751f392018-10-30 15:31:22 +00003556#endif
drh60f34ae2018-10-30 13:19:49 +00003557 " --new Initialize FILE to an empty database",
3558 " --readonly Open FILE readonly",
3559 " --zip FILE is a ZIP archive",
drh98aa2ab2018-09-26 16:53:51 +00003560 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
3561 " If FILE begins with '|' then open it as a pipe.",
drh9cb02642019-02-28 20:10:52 +00003562 ".parameter CMD ... Manage SQL parameter bindings",
3563 " clear Erase all bindings",
3564 " init Initialize the TEMP table that holds bindings",
3565 " list List the current parameter bindings",
3566 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
3567 " PARAMETER should start with '$', ':', '@', or '?'",
3568 " unset PARAMETER Remove PARAMETER from the binding table",
drh98aa2ab2018-09-26 16:53:51 +00003569 ".print STRING... Print literal STRING",
drh569b1d92019-02-05 20:51:41 +00003570#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00003571 ".progress N Invoke progress handler after every N opcodes",
3572 " --limit N Interrupt after N progress callbacks",
3573 " --once Do no more than one progress interrupt",
3574 " --quiet|-q No output except at interrupts",
3575 " --reset Reset the count for each input and interrupt",
drh569b1d92019-02-05 20:51:41 +00003576#endif
drh98aa2ab2018-09-26 16:53:51 +00003577 ".prompt MAIN CONTINUE Replace the standard prompts",
3578 ".quit Exit this program",
3579 ".read FILE Read input from FILE",
3580 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
3581 ".save FILE Write in-memory database into FILE",
3582 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
3583 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
3584 " Options:",
3585 " --indent Try to pretty-print the schema",
drheb7f2a02018-09-26 18:02:32 +00003586 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
3587 " Options:",
3588 " --init Create a new SELFTEST table",
3589 " -v Verbose output",
drh98aa2ab2018-09-26 16:53:51 +00003590 ".separator COL ?ROW? Change the column and row separators",
drh2ce15c32017-07-11 13:34:40 +00003591#if defined(SQLITE_ENABLE_SESSION)
drheb7f2a02018-09-26 18:02:32 +00003592 ".session ?NAME? CMD ... Create or control sessions",
3593 " Subcommands:",
3594 " attach TABLE Attach TABLE",
3595 " changeset FILE Write a changeset into FILE",
3596 " close Close one session",
3597 " enable ?BOOLEAN? Set or query the enable bit",
3598 " filter GLOB... Reject tables matching GLOBs",
3599 " indirect ?BOOLEAN? Mark or query the indirect status",
3600 " isempty Query whether the session is empty",
3601 " list List currently open session names",
3602 " open DB NAME Open a new session on DB",
3603 " patchset FILE Write a patchset into FILE",
3604 " If ?NAME? is omitted, the first defined session is used.",
drh2ce15c32017-07-11 13:34:40 +00003605#endif
drheb7f2a02018-09-26 18:02:32 +00003606 ".sha3sum ... Compute a SHA3 hash of database content",
3607 " Options:",
3608 " --schema Also hash the sqlite_master table",
3609 " --sha3-224 Use the sha3-224 algorithm",
3610 " --sha3-256 Use the sha3-256 algorithm. This is the default.",
3611 " --sha3-384 Use the sha3-384 algorithm",
3612 " --sha3-512 Use the sha3-512 algorithm",
3613 " Any other argument is a LIKE pattern for tables to hash",
drh04a28c32018-01-31 01:38:44 +00003614#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003615 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003616#endif
drh98aa2ab2018-09-26 16:53:51 +00003617 ".show Show the current values for various settings",
3618 ".stats ?on|off? Show stats or turn stats on or off",
drh04a28c32018-01-31 01:38:44 +00003619#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003620 ".system CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003621#endif
drh98aa2ab2018-09-26 16:53:51 +00003622 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
3623 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
3624 ".timeout MS Try opening locked tables for MS milliseconds",
3625 ".timer on|off Turn SQL timer on or off",
drh707821f2018-12-05 13:39:06 +00003626#ifndef SQLITE_OMIT_TRACE
3627 ".trace ?OPTIONS? Output each SQL statement as it is run",
3628 " FILE Send output to FILE",
3629 " stdout Send output to stdout",
3630 " stderr Send output to stderr",
3631 " off Disable tracing",
3632 " --expanded Expand query parameters",
3633#ifdef SQLITE_ENABLE_NORMALIZE
3634 " --normalized Normal the SQL statements",
3635#endif
3636 " --plain Show SQL as it is input",
3637 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
3638 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
3639 " --row Trace each row (SQLITE_TRACE_ROW)",
3640 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
3641#endif /* SQLITE_OMIT_TRACE */
drh98aa2ab2018-09-26 16:53:51 +00003642 ".vfsinfo ?AUX? Information about the top-level VFS",
3643 ".vfslist List all available VFSes",
3644 ".vfsname ?AUX? Print the name of the VFS stack",
3645 ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
3646 " Negative values right-justify",
3647};
3648
3649/*
3650** Output help text.
3651**
3652** zPattern describes the set of commands for which help text is provided.
3653** If zPattern is NULL, then show all commands, but only give a one-line
3654** description of each.
3655**
3656** Return the number of matches.
3657*/
3658static int showHelp(FILE *out, const char *zPattern){
drhe93f8262018-10-11 16:53:37 +00003659 int i = 0;
3660 int j = 0;
drh98aa2ab2018-09-26 16:53:51 +00003661 int n = 0;
3662 char *zPat;
drh488cddf2018-10-06 14:38:17 +00003663 if( zPattern==0
3664 || zPattern[0]=='0'
3665 || strcmp(zPattern,"-a")==0
3666 || strcmp(zPattern,"-all")==0
3667 ){
drh98aa2ab2018-09-26 16:53:51 +00003668 /* Show all commands, but only one line per command */
drh488cddf2018-10-06 14:38:17 +00003669 if( zPattern==0 ) zPattern = "";
drh98aa2ab2018-09-26 16:53:51 +00003670 for(i=0; i<ArraySize(azHelp); i++){
drh488cddf2018-10-06 14:38:17 +00003671 if( azHelp[i][0]=='.' || zPattern[0] ){
drh98aa2ab2018-09-26 16:53:51 +00003672 utf8_printf(out, "%s\n", azHelp[i]);
3673 n++;
3674 }
3675 }
3676 }else{
3677 /* Look for commands that for which zPattern is an exact prefix */
3678 zPat = sqlite3_mprintf(".%s*", zPattern);
3679 for(i=0; i<ArraySize(azHelp); i++){
3680 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3681 utf8_printf(out, "%s\n", azHelp[i]);
drheb7f2a02018-09-26 18:02:32 +00003682 j = i+1;
drh98aa2ab2018-09-26 16:53:51 +00003683 n++;
3684 }
3685 }
3686 sqlite3_free(zPat);
drheb7f2a02018-09-26 18:02:32 +00003687 if( n ){
3688 if( n==1 ){
3689 /* when zPattern is a prefix of exactly one command, then include the
3690 ** details of that command, which should begin at offset j */
3691 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3692 utf8_printf(out, "%s\n", azHelp[j]);
3693 j++;
3694 }
3695 }
3696 return n;
3697 }
3698 /* Look for commands that contain zPattern anywhere. Show the complete
3699 ** text of all commands that match. */
drh98aa2ab2018-09-26 16:53:51 +00003700 zPat = sqlite3_mprintf("%%%s%%", zPattern);
3701 for(i=0; i<ArraySize(azHelp); i++){
3702 if( azHelp[i][0]=='.' ) j = i;
3703 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3704 utf8_printf(out, "%s\n", azHelp[j]);
3705 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3706 j++;
3707 utf8_printf(out, "%s\n", azHelp[j]);
3708 }
3709 i = j;
3710 n++;
3711 }
3712 }
3713 sqlite3_free(zPat);
3714 }
3715 return n;
3716}
drh2ce15c32017-07-11 13:34:40 +00003717
drh2ce15c32017-07-11 13:34:40 +00003718/* Forward reference */
drh60379d42018-12-13 18:30:01 +00003719static int process_input(ShellState *p);
drh2ce15c32017-07-11 13:34:40 +00003720
3721/*
3722** Read the content of file zName into memory obtained from sqlite3_malloc64()
3723** and return a pointer to the buffer. The caller is responsible for freeing
3724** the memory.
3725**
3726** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3727** read.
3728**
3729** For convenience, a nul-terminator byte is always appended to the data read
3730** from the file before the buffer is returned. This byte is not included in
3731** the final value of (*pnByte), if applicable.
3732**
3733** NULL is returned if any error is encountered. The final value of *pnByte
3734** is undefined in this case.
3735*/
3736static char *readFile(const char *zName, int *pnByte){
3737 FILE *in = fopen(zName, "rb");
3738 long nIn;
3739 size_t nRead;
3740 char *pBuf;
3741 if( in==0 ) return 0;
3742 fseek(in, 0, SEEK_END);
3743 nIn = ftell(in);
3744 rewind(in);
3745 pBuf = sqlite3_malloc64( nIn+1 );
drh1dbb1472018-10-11 10:37:24 +00003746 if( pBuf==0 ){ fclose(in); return 0; }
drh2ce15c32017-07-11 13:34:40 +00003747 nRead = fread(pBuf, nIn, 1, in);
3748 fclose(in);
3749 if( nRead!=1 ){
3750 sqlite3_free(pBuf);
3751 return 0;
3752 }
3753 pBuf[nIn] = 0;
3754 if( pnByte ) *pnByte = nIn;
3755 return pBuf;
3756}
3757
3758#if defined(SQLITE_ENABLE_SESSION)
3759/*
3760** Close a single OpenSession object and release all of its associated
3761** resources.
3762*/
3763static void session_close(OpenSession *pSession){
3764 int i;
3765 sqlite3session_delete(pSession->p);
3766 sqlite3_free(pSession->zName);
3767 for(i=0; i<pSession->nFilter; i++){
3768 sqlite3_free(pSession->azFilter[i]);
3769 }
3770 sqlite3_free(pSession->azFilter);
3771 memset(pSession, 0, sizeof(OpenSession));
3772}
3773#endif
3774
3775/*
3776** Close all OpenSession objects and release all associated resources.
3777*/
3778#if defined(SQLITE_ENABLE_SESSION)
3779static void session_close_all(ShellState *p){
3780 int i;
3781 for(i=0; i<p->nSession; i++){
3782 session_close(&p->aSession[i]);
3783 }
3784 p->nSession = 0;
3785}
3786#else
3787# define session_close_all(X)
3788#endif
3789
3790/*
3791** Implementation of the xFilter function for an open session. Omit
3792** any tables named by ".session filter" but let all other table through.
3793*/
3794#if defined(SQLITE_ENABLE_SESSION)
3795static int session_filter(void *pCtx, const char *zTab){
3796 OpenSession *pSession = (OpenSession*)pCtx;
3797 int i;
3798 for(i=0; i<pSession->nFilter; i++){
3799 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3800 }
3801 return 1;
3802}
3803#endif
3804
3805/*
drh1fa6d9f2018-01-06 21:46:01 +00003806** Try to deduce the type of file for zName based on its content. Return
3807** one of the SHELL_OPEN_* constants.
drh1bf208c2018-03-09 21:54:01 +00003808**
3809** If the file does not exist or is empty but its name looks like a ZIP
3810** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3811** Otherwise, assume an ordinary database regardless of the filename if
3812** the type cannot be determined from content.
drh1fa6d9f2018-01-06 21:46:01 +00003813*/
drhfc97c1c2018-05-14 00:41:12 +00003814int deduceDatabaseType(const char *zName, int dfltZip){
drh1fa6d9f2018-01-06 21:46:01 +00003815 FILE *f = fopen(zName, "rb");
3816 size_t n;
3817 int rc = SHELL_OPEN_UNSPEC;
3818 char zBuf[100];
drh1bf208c2018-03-09 21:54:01 +00003819 if( f==0 ){
drhbe4ccb22018-05-17 20:04:24 +00003820 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3821 return SHELL_OPEN_ZIPFILE;
3822 }else{
3823 return SHELL_OPEN_NORMAL;
3824 }
drh1bf208c2018-03-09 21:54:01 +00003825 }
drh2b3c4af2018-10-30 14:36:21 +00003826 n = fread(zBuf, 16, 1, f);
3827 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
3828 fclose(f);
3829 return SHELL_OPEN_NORMAL;
3830 }
drh1fa6d9f2018-01-06 21:46:01 +00003831 fseek(f, -25, SEEK_END);
3832 n = fread(zBuf, 25, 1, f);
3833 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3834 rc = SHELL_OPEN_APPENDVFS;
3835 }else{
3836 fseek(f, -22, SEEK_END);
3837 n = fread(zBuf, 22, 1, f);
3838 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3839 && zBuf[3]==0x06 ){
3840 rc = SHELL_OPEN_ZIPFILE;
drh1bf208c2018-03-09 21:54:01 +00003841 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
mistachkina3926f42018-05-14 12:23:04 +00003842 rc = SHELL_OPEN_ZIPFILE;
drh1fa6d9f2018-01-06 21:46:01 +00003843 }
3844 }
3845 fclose(f);
3846 return rc;
3847}
3848
drh33746482018-12-13 15:06:26 +00003849#ifdef SQLITE_ENABLE_DESERIALIZE
3850/*
3851** Reconstruct an in-memory database using the output from the "dbtotxt"
3852** program. Read content from the file in p->zDbFilename. If p->zDbFilename
3853** is 0, then read from standard input.
3854*/
3855static unsigned char *readHexDb(ShellState *p, int *pnData){
3856 unsigned char *a = 0;
drh2c8ee022018-12-13 18:59:30 +00003857 int nLine;
drh33746482018-12-13 15:06:26 +00003858 int n = 0;
3859 int pgsz = 0;
3860 int iOffset = 0;
3861 int j, k;
3862 int rc;
3863 FILE *in;
3864 unsigned char x[16];
drh2c8ee022018-12-13 18:59:30 +00003865 char zLine[1000];
drh33746482018-12-13 15:06:26 +00003866 if( p->zDbFilename ){
3867 in = fopen(p->zDbFilename, "r");
3868 if( in==0 ){
3869 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
3870 return 0;
3871 }
drh2c8ee022018-12-13 18:59:30 +00003872 nLine = 0;
drh33746482018-12-13 15:06:26 +00003873 }else{
drh60379d42018-12-13 18:30:01 +00003874 in = p->in;
drh2c8ee022018-12-13 18:59:30 +00003875 nLine = p->lineno;
drh33746482018-12-13 15:06:26 +00003876 }
3877 *pnData = 0;
drh2c8ee022018-12-13 18:59:30 +00003878 nLine++;
drh33746482018-12-13 15:06:26 +00003879 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
3880 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
3881 if( rc!=2 ) goto readHexDb_error;
3882 if( n<=0 ) goto readHexDb_error;
3883 a = sqlite3_malloc( n );
3884 if( a==0 ){
3885 utf8_printf(stderr, "Out of memory!\n");
3886 goto readHexDb_error;
3887 }
3888 memset(a, 0, n);
3889 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
3890 utf8_printf(stderr, "invalid pagesize\n");
3891 goto readHexDb_error;
3892 }
drh2c8ee022018-12-13 18:59:30 +00003893 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
drh33746482018-12-13 15:06:26 +00003894 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
3895 if( rc==2 ){
3896 iOffset = k;
3897 continue;
3898 }
3899 if( strncmp(zLine, "| end ", 6)==0 ){
3900 break;
3901 }
3902 rc = sscanf(zLine,"| %d: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx"
3903 " %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx",
3904 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
3905 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
3906 if( rc==17 ){
3907 k = iOffset+j;
drhf354e772018-12-13 22:58:52 +00003908 if( k+16<=n ){
3909 memcpy(a+k, x, 16);
drh33746482018-12-13 15:06:26 +00003910 }
drh33746482018-12-13 15:06:26 +00003911 }
3912 }
3913 *pnData = n;
drh2c8ee022018-12-13 18:59:30 +00003914 if( in!=p->in ){
3915 fclose(in);
3916 }else{
3917 p->lineno = nLine;
3918 }
drh33746482018-12-13 15:06:26 +00003919 return a;
3920
3921readHexDb_error:
3922 if( in!=stdin ){
3923 fclose(in);
3924 }else{
drh60379d42018-12-13 18:30:01 +00003925 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
drh2c8ee022018-12-13 18:59:30 +00003926 nLine++;
drh33746482018-12-13 15:06:26 +00003927 if(strncmp(zLine, "| end ", 6)==0 ) break;
3928 }
drh2c8ee022018-12-13 18:59:30 +00003929 p->lineno = nLine;
drh33746482018-12-13 15:06:26 +00003930 }
3931 sqlite3_free(a);
3932 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
3933 return 0;
3934}
3935#endif /* SQLITE_ENABLE_DESERIALIZE */
3936
danb1825882019-04-23 20:48:32 +00003937/*
3938** Scalar function "shell_escape_crnl" used by the .recover command.
3939** The argument passed to this function is the output of built-in
3940** function quote(). If the first character of the input is "'",
3941** indicating that the value passed to quote() was a text value,
3942** then this function searches the input for "\n" and "\r" characters
3943** and adds a wrapper similar to the following:
3944**
3945** replace(replace(<input>, '\n', char(10), '\r', char(13));
3946**
3947** Or, if the first character of the input is not "'", then a copy
3948** of the input is returned.
3949*/
3950static void shellEscapeCrnl(
3951 sqlite3_context *context,
3952 int argc,
3953 sqlite3_value **argv
3954){
3955 const char *zText = (const char*)sqlite3_value_text(argv[0]);
3956 if( zText[0]=='\'' ){
3957 int nText = sqlite3_value_bytes(argv[0]);
3958 int i;
3959 char zBuf1[20];
3960 char zBuf2[20];
3961 const char *zNL = 0;
3962 const char *zCR = 0;
3963 int nCR = 0;
3964 int nNL = 0;
3965
3966 for(i=0; zText[i]; i++){
3967 if( zNL==0 && zText[i]=='\n' ){
3968 zNL = unused_string(zText, "\\n", "\\012", zBuf1);
3969 nNL = (int)strlen(zNL);
3970 }
3971 if( zCR==0 && zText[i]=='\r' ){
3972 zCR = unused_string(zText, "\\r", "\\015", zBuf2);
3973 nCR = (int)strlen(zCR);
3974 }
3975 }
3976
3977 if( zNL || zCR ){
3978 int iOut = 0;
3979 i64 nMax = (nNL > nCR) ? nNL : nCR;
3980 i64 nAlloc = nMax * nText + (nMax+12)*2;
3981 char *zOut = (char*)sqlite3_malloc64(nAlloc);
3982 if( zOut==0 ){
3983 sqlite3_result_error_nomem(context);
3984 return;
3985 }
3986
3987 if( zNL && zCR ){
3988 memcpy(&zOut[iOut], "replace(replace(", 16);
3989 iOut += 16;
3990 }else{
3991 memcpy(&zOut[iOut], "replace(", 8);
3992 iOut += 8;
3993 }
3994 for(i=0; zText[i]; i++){
3995 if( zText[i]=='\n' ){
3996 memcpy(&zOut[iOut], zNL, nNL);
3997 iOut += nNL;
3998 }else if( zText[i]=='\r' ){
3999 memcpy(&zOut[iOut], zCR, nCR);
4000 iOut += nCR;
4001 }else{
4002 zOut[iOut] = zText[i];
4003 iOut++;
4004 }
4005 }
4006
4007 if( zNL ){
4008 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4009 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4010 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4011 }
4012 if( zCR ){
4013 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4014 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4015 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4016 }
4017
4018 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4019 sqlite3_free(zOut);
4020 return;
4021 }
4022 }
4023
4024 sqlite3_result_value(context, argv[0]);
4025}
4026
drhbe4ccb22018-05-17 20:04:24 +00004027/* Flags for open_db().
4028**
4029** The default behavior of open_db() is to exit(1) if the database fails to
4030** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4031** but still returns without calling exit.
4032**
4033** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4034** ZIP archive if the file does not exist or is empty and its name matches
4035** the *.zip pattern.
4036*/
4037#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
4038#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
4039
drh1fa6d9f2018-01-06 21:46:01 +00004040/*
drh2ce15c32017-07-11 13:34:40 +00004041** Make sure the database is open. If it is not, then open it. If
4042** the database fails to open, print an error message and exit.
4043*/
drhbe4ccb22018-05-17 20:04:24 +00004044static void open_db(ShellState *p, int openFlags){
drh2ce15c32017-07-11 13:34:40 +00004045 if( p->db==0 ){
drhf2072d12018-05-11 15:10:11 +00004046 if( p->openMode==SHELL_OPEN_UNSPEC ){
4047 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
4048 p->openMode = SHELL_OPEN_NORMAL;
drhbe4ccb22018-05-17 20:04:24 +00004049 }else{
4050 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
4051 (openFlags & OPEN_DB_ZIPFILE)!=0);
drhf2072d12018-05-11 15:10:11 +00004052 }
drh1fa6d9f2018-01-06 21:46:01 +00004053 }
4054 switch( p->openMode ){
4055 case SHELL_OPEN_APPENDVFS: {
4056 sqlite3_open_v2(p->zDbFilename, &p->db,
4057 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
4058 break;
4059 }
drh33746482018-12-13 15:06:26 +00004060 case SHELL_OPEN_HEXDB:
drh60f34ae2018-10-30 13:19:49 +00004061 case SHELL_OPEN_DESERIALIZE: {
4062 sqlite3_open(0, &p->db);
4063 break;
4064 }
drh1fa6d9f2018-01-06 21:46:01 +00004065 case SHELL_OPEN_ZIPFILE: {
4066 sqlite3_open(":memory:", &p->db);
4067 break;
4068 }
drhee269a62018-02-14 23:27:43 +00004069 case SHELL_OPEN_READONLY: {
4070 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
4071 break;
4072 }
drh1fa6d9f2018-01-06 21:46:01 +00004073 case SHELL_OPEN_UNSPEC:
4074 case SHELL_OPEN_NORMAL: {
4075 sqlite3_open(p->zDbFilename, &p->db);
4076 break;
4077 }
4078 }
drh2ce15c32017-07-11 13:34:40 +00004079 globalDb = p->db;
4080 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4081 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4082 p->zDbFilename, sqlite3_errmsg(p->db));
drhf25cc4f2019-01-04 14:29:21 +00004083 if( openFlags & OPEN_DB_KEEPALIVE ){
4084 sqlite3_open(":memory:", &p->db);
4085 return;
4086 }
drh2ce15c32017-07-11 13:34:40 +00004087 exit(1);
4088 }
4089#ifndef SQLITE_OMIT_LOAD_EXTENSION
4090 sqlite3_enable_load_extension(p->db, 1);
4091#endif
4092 sqlite3_fileio_init(p->db, 0, 0);
4093 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00004094 sqlite3_completion_init(p->db, 0, 0);
dan68cb86e2019-04-20 20:57:28 +00004095 sqlite3_dbdata_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00004096#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00004097 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00004098 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00004099#endif
drhceba7922018-01-01 21:28:25 +00004100 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00004101 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00004102 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4103 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00004104 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4105 shellPutsFunc, 0, 0);
danb1825882019-04-23 20:48:32 +00004106 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4107 shellEscapeCrnl, 0, 0);
drh04a28c32018-01-31 01:38:44 +00004108#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00004109 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4110 editFunc, 0, 0);
4111 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4112 editFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00004113#endif
drh1fa6d9f2018-01-06 21:46:01 +00004114 if( p->openMode==SHELL_OPEN_ZIPFILE ){
4115 char *zSql = sqlite3_mprintf(
4116 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
4117 sqlite3_exec(p->db, zSql, 0, 0, 0);
4118 sqlite3_free(zSql);
drha751f392018-10-30 15:31:22 +00004119 }
4120#ifdef SQLITE_ENABLE_DESERIALIZE
drh33746482018-12-13 15:06:26 +00004121 else
4122 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
mistachkin99490932018-12-17 22:19:57 +00004123 int rc;
drh60f34ae2018-10-30 13:19:49 +00004124 int nData = 0;
drh33746482018-12-13 15:06:26 +00004125 unsigned char *aData;
4126 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4127 aData = (unsigned char*)readFile(p->zDbFilename, &nData);
4128 }else{
4129 aData = readHexDb(p, &nData);
4130 if( aData==0 ){
4131 utf8_printf(stderr, "Error in hexdb input\n");
4132 return;
4133 }
4134 }
mistachkin99490932018-12-17 22:19:57 +00004135 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
drh60f34ae2018-10-30 13:19:49 +00004136 SQLITE_DESERIALIZE_RESIZEABLE |
4137 SQLITE_DESERIALIZE_FREEONCLOSE);
4138 if( rc ){
4139 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4140 }
drh6ca64482019-01-22 16:06:20 +00004141 if( p->szMax>0 ){
4142 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4143 }
drh1fa6d9f2018-01-06 21:46:01 +00004144 }
drha751f392018-10-30 15:31:22 +00004145#endif
drh2ce15c32017-07-11 13:34:40 +00004146 }
4147}
4148
drh9e804032018-05-18 17:11:50 +00004149/*
4150** Attempt to close the databaes connection. Report errors.
4151*/
4152void close_db(sqlite3 *db){
4153 int rc = sqlite3_close(db);
4154 if( rc ){
4155 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4156 rc, sqlite3_errmsg(db));
4157 }
4158}
4159
drh56eb09b2017-07-11 13:59:07 +00004160#if HAVE_READLINE || HAVE_EDITLINE
4161/*
4162** Readline completion callbacks
4163*/
4164static char *readline_completion_generator(const char *text, int state){
4165 static sqlite3_stmt *pStmt = 0;
4166 char *zRet;
4167 if( state==0 ){
4168 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00004169 sqlite3_finalize(pStmt);
4170 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4171 " FROM completion(%Q) ORDER BY 1", text);
4172 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4173 sqlite3_free(zSql);
4174 }
4175 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00004176 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00004177 }else{
4178 sqlite3_finalize(pStmt);
4179 pStmt = 0;
4180 zRet = 0;
4181 }
4182 return zRet;
4183}
4184static char **readline_completion(const char *zText, int iStart, int iEnd){
4185 rl_attempted_completion_over = 1;
4186 return rl_completion_matches(zText, readline_completion_generator);
4187}
4188
4189#elif HAVE_LINENOISE
4190/*
4191** Linenoise completion callback
4192*/
4193static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00004194 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00004195 int i, iStart;
4196 sqlite3_stmt *pStmt = 0;
4197 char *zSql;
4198 char zBuf[1000];
4199
4200 if( nLine>sizeof(zBuf)-30 ) return;
drh1615c372018-05-12 23:56:22 +00004201 if( zLine[0]=='.' || zLine[0]=='#') return;
drh56eb09b2017-07-11 13:59:07 +00004202 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4203 if( i==nLine-1 ) return;
4204 iStart = i+1;
4205 memcpy(zBuf, zLine, iStart);
4206 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4207 " FROM completion(%Q,%Q) ORDER BY 1",
4208 &zLine[iStart], zLine);
4209 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4210 sqlite3_free(zSql);
4211 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4212 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4213 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4214 int nCompletion = sqlite3_column_bytes(pStmt, 0);
4215 if( iStart+nCompletion < sizeof(zBuf)-1 ){
4216 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4217 linenoiseAddCompletion(lc, zBuf);
4218 }
4219 }
4220 sqlite3_finalize(pStmt);
4221}
4222#endif
4223
drh2ce15c32017-07-11 13:34:40 +00004224/*
4225** Do C-language style dequoting.
4226**
4227** \a -> alarm
4228** \b -> backspace
4229** \t -> tab
4230** \n -> newline
4231** \v -> vertical tab
4232** \f -> form feed
4233** \r -> carriage return
4234** \s -> space
4235** \" -> "
4236** \' -> '
4237** \\ -> backslash
4238** \NNN -> ascii character NNN in octal
4239*/
4240static void resolve_backslashes(char *z){
4241 int i, j;
4242 char c;
4243 while( *z && *z!='\\' ) z++;
4244 for(i=j=0; (c = z[i])!=0; i++, j++){
4245 if( c=='\\' && z[i+1]!=0 ){
4246 c = z[++i];
4247 if( c=='a' ){
4248 c = '\a';
4249 }else if( c=='b' ){
4250 c = '\b';
4251 }else if( c=='t' ){
4252 c = '\t';
4253 }else if( c=='n' ){
4254 c = '\n';
4255 }else if( c=='v' ){
4256 c = '\v';
4257 }else if( c=='f' ){
4258 c = '\f';
4259 }else if( c=='r' ){
4260 c = '\r';
4261 }else if( c=='"' ){
4262 c = '"';
4263 }else if( c=='\'' ){
4264 c = '\'';
4265 }else if( c=='\\' ){
4266 c = '\\';
4267 }else if( c>='0' && c<='7' ){
4268 c -= '0';
4269 if( z[i+1]>='0' && z[i+1]<='7' ){
4270 i++;
4271 c = (c<<3) + z[i] - '0';
4272 if( z[i+1]>='0' && z[i+1]<='7' ){
4273 i++;
4274 c = (c<<3) + z[i] - '0';
4275 }
4276 }
4277 }
4278 }
4279 z[j] = c;
4280 }
4281 if( j<i ) z[j] = 0;
4282}
4283
4284/*
drh2ce15c32017-07-11 13:34:40 +00004285** Interpret zArg as either an integer or a boolean value. Return 1 or 0
4286** for TRUE and FALSE. Return the integer value if appropriate.
4287*/
4288static int booleanValue(const char *zArg){
4289 int i;
4290 if( zArg[0]=='0' && zArg[1]=='x' ){
4291 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4292 }else{
4293 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4294 }
4295 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4296 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4297 return 1;
4298 }
4299 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4300 return 0;
4301 }
4302 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4303 zArg);
4304 return 0;
4305}
4306
4307/*
4308** Set or clear a shell flag according to a boolean value.
4309*/
4310static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4311 if( booleanValue(zArg) ){
4312 ShellSetFlag(p, mFlag);
4313 }else{
4314 ShellClearFlag(p, mFlag);
4315 }
4316}
4317
4318/*
4319** Close an output file, assuming it is not stderr or stdout
4320*/
4321static void output_file_close(FILE *f){
4322 if( f && f!=stdout && f!=stderr ) fclose(f);
4323}
4324
4325/*
4326** Try to open an output file. The names "stdout" and "stderr" are
4327** recognized and do the right thing. NULL is returned if the output
4328** filename is "off".
4329*/
drha92a01a2018-01-10 22:15:37 +00004330static FILE *output_file_open(const char *zFile, int bTextMode){
drh2ce15c32017-07-11 13:34:40 +00004331 FILE *f;
4332 if( strcmp(zFile,"stdout")==0 ){
4333 f = stdout;
4334 }else if( strcmp(zFile, "stderr")==0 ){
4335 f = stderr;
4336 }else if( strcmp(zFile, "off")==0 ){
4337 f = 0;
4338 }else{
drha92a01a2018-01-10 22:15:37 +00004339 f = fopen(zFile, bTextMode ? "w" : "wb");
drh2ce15c32017-07-11 13:34:40 +00004340 if( f==0 ){
4341 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4342 }
4343 }
4344 return f;
4345}
4346
drh707821f2018-12-05 13:39:06 +00004347#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00004348/*
4349** A routine for handling output from sqlite3_trace().
4350*/
4351static int sql_trace_callback(
drh707821f2018-12-05 13:39:06 +00004352 unsigned mType, /* The trace type */
4353 void *pArg, /* The ShellState pointer */
4354 void *pP, /* Usually a pointer to sqlite_stmt */
4355 void *pX /* Auxiliary output */
drh2ce15c32017-07-11 13:34:40 +00004356){
drh707821f2018-12-05 13:39:06 +00004357 ShellState *p = (ShellState*)pArg;
4358 sqlite3_stmt *pStmt;
4359 const char *zSql;
4360 int nSql;
4361 if( p->traceOut==0 ) return 0;
4362 if( mType==SQLITE_TRACE_CLOSE ){
4363 utf8_printf(p->traceOut, "-- closing database connection\n");
4364 return 0;
4365 }
4366 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4367 zSql = (const char*)pX;
4368 }else{
4369 pStmt = (sqlite3_stmt*)pP;
4370 switch( p->eTraceType ){
4371 case SHELL_TRACE_EXPANDED: {
4372 zSql = sqlite3_expanded_sql(pStmt);
4373 break;
4374 }
4375#ifdef SQLITE_ENABLE_NORMALIZE
4376 case SHELL_TRACE_NORMALIZED: {
4377 zSql = sqlite3_normalized_sql(pStmt);
4378 break;
4379 }
4380#endif
4381 default: {
4382 zSql = sqlite3_sql(pStmt);
4383 break;
4384 }
4385 }
4386 }
4387 if( zSql==0 ) return 0;
4388 nSql = strlen30(zSql);
4389 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4390 switch( mType ){
4391 case SQLITE_TRACE_ROW:
4392 case SQLITE_TRACE_STMT: {
4393 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4394 break;
4395 }
4396 case SQLITE_TRACE_PROFILE: {
4397 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4398 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4399 break;
4400 }
drh2ce15c32017-07-11 13:34:40 +00004401 }
4402 return 0;
4403}
4404#endif
drh2ce15c32017-07-11 13:34:40 +00004405
4406/*
4407** A no-op routine that runs with the ".breakpoint" doc-command. This is
4408** a useful spot to set a debugger breakpoint.
4409*/
4410static void test_breakpoint(void){
4411 static int nCall = 0;
4412 nCall++;
4413}
4414
4415/*
4416** An object used to read a CSV and other files for import.
4417*/
4418typedef struct ImportCtx ImportCtx;
4419struct ImportCtx {
4420 const char *zFile; /* Name of the input file */
4421 FILE *in; /* Read the CSV text from this input stream */
4422 char *z; /* Accumulated text for a field */
4423 int n; /* Number of bytes in z */
4424 int nAlloc; /* Space allocated for z[] */
4425 int nLine; /* Current line number */
4426 int bNotFirst; /* True if one or more bytes already read */
4427 int cTerm; /* Character that terminated the most recent field */
4428 int cColSep; /* The column separator character. (Usually ",") */
4429 int cRowSep; /* The row separator character. (Usually "\n") */
4430};
4431
4432/* Append a single byte to z[] */
4433static void import_append_char(ImportCtx *p, int c){
4434 if( p->n+1>=p->nAlloc ){
4435 p->nAlloc += p->nAlloc + 100;
4436 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drh4b5345c2018-04-24 13:07:40 +00004437 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004438 }
4439 p->z[p->n++] = (char)c;
4440}
4441
4442/* Read a single field of CSV text. Compatible with rfc4180 and extended
4443** with the option of having a separator other than ",".
4444**
4445** + Input comes from p->in.
4446** + Store results in p->z of length p->n. Space to hold p->z comes
4447** from sqlite3_malloc64().
4448** + Use p->cSep as the column separator. The default is ",".
4449** + Use p->rSep as the row separator. The default is "\n".
4450** + Keep track of the line number in p->nLine.
4451** + Store the character that terminates the field in p->cTerm. Store
4452** EOF on end-of-file.
4453** + Report syntax errors on stderr
4454*/
4455static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4456 int c;
4457 int cSep = p->cColSep;
4458 int rSep = p->cRowSep;
4459 p->n = 0;
4460 c = fgetc(p->in);
4461 if( c==EOF || seenInterrupt ){
4462 p->cTerm = EOF;
4463 return 0;
4464 }
4465 if( c=='"' ){
4466 int pc, ppc;
4467 int startLine = p->nLine;
4468 int cQuote = c;
4469 pc = ppc = 0;
4470 while( 1 ){
4471 c = fgetc(p->in);
4472 if( c==rSep ) p->nLine++;
4473 if( c==cQuote ){
4474 if( pc==cQuote ){
4475 pc = 0;
4476 continue;
4477 }
4478 }
4479 if( (c==cSep && pc==cQuote)
4480 || (c==rSep && pc==cQuote)
4481 || (c==rSep && pc=='\r' && ppc==cQuote)
4482 || (c==EOF && pc==cQuote)
4483 ){
4484 do{ p->n--; }while( p->z[p->n]!=cQuote );
4485 p->cTerm = c;
4486 break;
4487 }
4488 if( pc==cQuote && c!='\r' ){
4489 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4490 p->zFile, p->nLine, cQuote);
4491 }
4492 if( c==EOF ){
4493 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4494 p->zFile, startLine, cQuote);
4495 p->cTerm = c;
4496 break;
4497 }
4498 import_append_char(p, c);
4499 ppc = pc;
4500 pc = c;
4501 }
4502 }else{
4503 /* If this is the first field being parsed and it begins with the
4504 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4505 if( (c&0xff)==0xef && p->bNotFirst==0 ){
4506 import_append_char(p, c);
4507 c = fgetc(p->in);
4508 if( (c&0xff)==0xbb ){
4509 import_append_char(p, c);
4510 c = fgetc(p->in);
4511 if( (c&0xff)==0xbf ){
4512 p->bNotFirst = 1;
4513 p->n = 0;
4514 return csv_read_one_field(p);
4515 }
4516 }
4517 }
4518 while( c!=EOF && c!=cSep && c!=rSep ){
4519 import_append_char(p, c);
4520 c = fgetc(p->in);
4521 }
4522 if( c==rSep ){
4523 p->nLine++;
4524 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4525 }
4526 p->cTerm = c;
4527 }
4528 if( p->z ) p->z[p->n] = 0;
4529 p->bNotFirst = 1;
4530 return p->z;
4531}
4532
4533/* Read a single field of ASCII delimited text.
4534**
4535** + Input comes from p->in.
4536** + Store results in p->z of length p->n. Space to hold p->z comes
4537** from sqlite3_malloc64().
4538** + Use p->cSep as the column separator. The default is "\x1F".
4539** + Use p->rSep as the row separator. The default is "\x1E".
4540** + Keep track of the row number in p->nLine.
4541** + Store the character that terminates the field in p->cTerm. Store
4542** EOF on end-of-file.
4543** + Report syntax errors on stderr
4544*/
4545static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4546 int c;
4547 int cSep = p->cColSep;
4548 int rSep = p->cRowSep;
4549 p->n = 0;
4550 c = fgetc(p->in);
4551 if( c==EOF || seenInterrupt ){
4552 p->cTerm = EOF;
4553 return 0;
4554 }
4555 while( c!=EOF && c!=cSep && c!=rSep ){
4556 import_append_char(p, c);
4557 c = fgetc(p->in);
4558 }
4559 if( c==rSep ){
4560 p->nLine++;
4561 }
4562 p->cTerm = c;
4563 if( p->z ) p->z[p->n] = 0;
4564 return p->z;
4565}
4566
4567/*
4568** Try to transfer data for table zTable. If an error is seen while
4569** moving forward, try to go backwards. The backwards movement won't
4570** work for WITHOUT ROWID tables.
4571*/
4572static void tryToCloneData(
4573 ShellState *p,
4574 sqlite3 *newDb,
4575 const char *zTable
4576){
4577 sqlite3_stmt *pQuery = 0;
4578 sqlite3_stmt *pInsert = 0;
4579 char *zQuery = 0;
4580 char *zInsert = 0;
4581 int rc;
4582 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00004583 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00004584 int k = 0;
4585 int cnt = 0;
4586 const int spinRate = 10000;
4587
4588 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4589 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4590 if( rc ){
4591 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4592 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4593 zQuery);
4594 goto end_data_xfer;
4595 }
4596 n = sqlite3_column_count(pQuery);
4597 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh4b5345c2018-04-24 13:07:40 +00004598 if( zInsert==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004599 sqlite3_snprintf(200+nTable,zInsert,
4600 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00004601 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00004602 for(j=1; j<n; j++){
4603 memcpy(zInsert+i, ",?", 2);
4604 i += 2;
4605 }
4606 memcpy(zInsert+i, ");", 3);
4607 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4608 if( rc ){
4609 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4610 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4611 zQuery);
4612 goto end_data_xfer;
4613 }
4614 for(k=0; k<2; k++){
4615 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4616 for(i=0; i<n; i++){
4617 switch( sqlite3_column_type(pQuery, i) ){
4618 case SQLITE_NULL: {
4619 sqlite3_bind_null(pInsert, i+1);
4620 break;
4621 }
4622 case SQLITE_INTEGER: {
4623 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4624 break;
4625 }
4626 case SQLITE_FLOAT: {
4627 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4628 break;
4629 }
4630 case SQLITE_TEXT: {
4631 sqlite3_bind_text(pInsert, i+1,
4632 (const char*)sqlite3_column_text(pQuery,i),
4633 -1, SQLITE_STATIC);
4634 break;
4635 }
4636 case SQLITE_BLOB: {
4637 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4638 sqlite3_column_bytes(pQuery,i),
4639 SQLITE_STATIC);
4640 break;
4641 }
4642 }
4643 } /* End for */
4644 rc = sqlite3_step(pInsert);
4645 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4646 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4647 sqlite3_errmsg(newDb));
4648 }
4649 sqlite3_reset(pInsert);
4650 cnt++;
4651 if( (cnt%spinRate)==0 ){
4652 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4653 fflush(stdout);
4654 }
4655 } /* End while */
4656 if( rc==SQLITE_DONE ) break;
4657 sqlite3_finalize(pQuery);
4658 sqlite3_free(zQuery);
4659 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4660 zTable);
4661 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4662 if( rc ){
4663 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4664 break;
4665 }
4666 } /* End for(k=0...) */
4667
4668end_data_xfer:
4669 sqlite3_finalize(pQuery);
4670 sqlite3_finalize(pInsert);
4671 sqlite3_free(zQuery);
4672 sqlite3_free(zInsert);
4673}
4674
4675
4676/*
4677** Try to transfer all rows of the schema that match zWhere. For
4678** each row, invoke xForEach() on the object defined by that row.
4679** If an error is encountered while moving forward through the
4680** sqlite_master table, try again moving backwards.
4681*/
4682static void tryToCloneSchema(
4683 ShellState *p,
4684 sqlite3 *newDb,
4685 const char *zWhere,
4686 void (*xForEach)(ShellState*,sqlite3*,const char*)
4687){
4688 sqlite3_stmt *pQuery = 0;
4689 char *zQuery = 0;
4690 int rc;
4691 const unsigned char *zName;
4692 const unsigned char *zSql;
4693 char *zErrMsg = 0;
4694
4695 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4696 " WHERE %s", zWhere);
4697 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4698 if( rc ){
4699 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4700 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4701 zQuery);
4702 goto end_schema_xfer;
4703 }
4704 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4705 zName = sqlite3_column_text(pQuery, 0);
4706 zSql = sqlite3_column_text(pQuery, 1);
4707 printf("%s... ", zName); fflush(stdout);
4708 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4709 if( zErrMsg ){
4710 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4711 sqlite3_free(zErrMsg);
4712 zErrMsg = 0;
4713 }
4714 if( xForEach ){
4715 xForEach(p, newDb, (const char*)zName);
4716 }
4717 printf("done\n");
4718 }
4719 if( rc!=SQLITE_DONE ){
4720 sqlite3_finalize(pQuery);
4721 sqlite3_free(zQuery);
4722 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4723 " WHERE %s ORDER BY rowid DESC", zWhere);
4724 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4725 if( rc ){
4726 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4727 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4728 zQuery);
4729 goto end_schema_xfer;
4730 }
4731 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4732 zName = sqlite3_column_text(pQuery, 0);
4733 zSql = sqlite3_column_text(pQuery, 1);
4734 printf("%s... ", zName); fflush(stdout);
4735 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4736 if( zErrMsg ){
4737 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4738 sqlite3_free(zErrMsg);
4739 zErrMsg = 0;
4740 }
4741 if( xForEach ){
4742 xForEach(p, newDb, (const char*)zName);
4743 }
4744 printf("done\n");
4745 }
4746 }
4747end_schema_xfer:
4748 sqlite3_finalize(pQuery);
4749 sqlite3_free(zQuery);
4750}
4751
4752/*
4753** Open a new database file named "zNewDb". Try to recover as much information
4754** as possible out of the main database (which might be corrupt) and write it
4755** into zNewDb.
4756*/
4757static void tryToClone(ShellState *p, const char *zNewDb){
4758 int rc;
4759 sqlite3 *newDb = 0;
4760 if( access(zNewDb,0)==0 ){
4761 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4762 return;
4763 }
4764 rc = sqlite3_open(zNewDb, &newDb);
4765 if( rc ){
4766 utf8_printf(stderr, "Cannot create output database: %s\n",
4767 sqlite3_errmsg(newDb));
4768 }else{
4769 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4770 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4771 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4772 tryToCloneSchema(p, newDb, "type!='table'", 0);
4773 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4774 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4775 }
drh9e804032018-05-18 17:11:50 +00004776 close_db(newDb);
drh2ce15c32017-07-11 13:34:40 +00004777}
4778
4779/*
drh13c20932018-01-10 21:41:55 +00004780** Change the output file back to stdout.
4781**
4782** If the p->doXdgOpen flag is set, that means the output was being
4783** redirected to a temporary file named by p->zTempFile. In that case,
4784** launch start/open/xdg-open on that temporary file.
drh2ce15c32017-07-11 13:34:40 +00004785*/
4786static void output_reset(ShellState *p){
4787 if( p->outfile[0]=='|' ){
4788#ifndef SQLITE_OMIT_POPEN
4789 pclose(p->out);
4790#endif
4791 }else{
4792 output_file_close(p->out);
drh04a28c32018-01-31 01:38:44 +00004793#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00004794 if( p->doXdgOpen ){
4795 const char *zXdgOpenCmd =
4796#if defined(_WIN32)
4797 "start";
4798#elif defined(__APPLE__)
4799 "open";
4800#else
4801 "xdg-open";
4802#endif
4803 char *zCmd;
4804 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
drha92a01a2018-01-10 22:15:37 +00004805 if( system(zCmd) ){
4806 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4807 }
drh13c20932018-01-10 21:41:55 +00004808 sqlite3_free(zCmd);
drh3c484e82018-01-10 22:27:21 +00004809 outputModePop(p);
drh13c20932018-01-10 21:41:55 +00004810 p->doXdgOpen = 0;
4811 }
drh04a28c32018-01-31 01:38:44 +00004812#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00004813 }
4814 p->outfile[0] = 0;
4815 p->out = stdout;
4816}
4817
4818/*
4819** Run an SQL command and return the single integer result.
4820*/
4821static int db_int(ShellState *p, const char *zSql){
4822 sqlite3_stmt *pStmt;
4823 int res = 0;
4824 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4825 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4826 res = sqlite3_column_int(pStmt,0);
4827 }
4828 sqlite3_finalize(pStmt);
4829 return res;
4830}
4831
4832/*
4833** Convert a 2-byte or 4-byte big-endian integer into a native integer
4834*/
4835static unsigned int get2byteInt(unsigned char *a){
4836 return (a[0]<<8) + a[1];
4837}
4838static unsigned int get4byteInt(unsigned char *a){
4839 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4840}
4841
4842/*
4843** Implementation of the ".info" command.
4844**
4845** Return 1 on error, 2 to exit, and 0 otherwise.
4846*/
4847static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4848 static const struct { const char *zName; int ofst; } aField[] = {
4849 { "file change counter:", 24 },
4850 { "database page count:", 28 },
4851 { "freelist page count:", 36 },
4852 { "schema cookie:", 40 },
4853 { "schema format:", 44 },
4854 { "default cache size:", 48 },
4855 { "autovacuum top root:", 52 },
4856 { "incremental vacuum:", 64 },
4857 { "text encoding:", 56 },
4858 { "user version:", 60 },
4859 { "application id:", 68 },
4860 { "software version:", 96 },
4861 };
4862 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4863 { "number of tables:",
4864 "SELECT count(*) FROM %s WHERE type='table'" },
4865 { "number of indexes:",
4866 "SELECT count(*) FROM %s WHERE type='index'" },
4867 { "number of triggers:",
4868 "SELECT count(*) FROM %s WHERE type='trigger'" },
4869 { "number of views:",
4870 "SELECT count(*) FROM %s WHERE type='view'" },
4871 { "schema size:",
4872 "SELECT total(length(sql)) FROM %s" },
4873 };
drh87c889c2019-03-20 18:22:51 +00004874 int i, rc;
drhea99a312018-07-18 19:09:07 +00004875 unsigned iDataVersion;
drh2ce15c32017-07-11 13:34:40 +00004876 char *zSchemaTab;
4877 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004878 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004879 unsigned char aHdr[100];
4880 open_db(p, 0);
4881 if( p->db==0 ) return 1;
drh87c889c2019-03-20 18:22:51 +00004882 rc = sqlite3_prepare_v2(p->db,
4883 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4884 -1, &pStmt, 0);
4885 if( rc ){
4886 if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){
4887 utf8_printf(stderr, "the \".dbinfo\" command requires the "
4888 "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n");
4889 }else{
4890 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
4891 }
4892 sqlite3_finalize(pStmt);
4893 return 1;
4894 }
drh512e6c32017-10-11 17:51:08 +00004895 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4896 if( sqlite3_step(pStmt)==SQLITE_ROW
4897 && sqlite3_column_bytes(pStmt,0)>100
4898 ){
4899 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4900 sqlite3_finalize(pStmt);
4901 }else{
drh2ce15c32017-07-11 13:34:40 +00004902 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004903 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004904 return 1;
4905 }
4906 i = get2byteInt(aHdr+16);
4907 if( i==1 ) i = 65536;
4908 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4909 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4910 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4911 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4912 for(i=0; i<ArraySize(aField); i++){
4913 int ofst = aField[i].ofst;
4914 unsigned int val = get4byteInt(aHdr + ofst);
4915 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4916 switch( ofst ){
4917 case 56: {
4918 if( val==1 ) raw_printf(p->out, " (utf8)");
4919 if( val==2 ) raw_printf(p->out, " (utf16le)");
4920 if( val==3 ) raw_printf(p->out, " (utf16be)");
4921 }
4922 }
4923 raw_printf(p->out, "\n");
4924 }
4925 if( zDb==0 ){
4926 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4927 }else if( strcmp(zDb,"temp")==0 ){
4928 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4929 }else{
4930 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4931 }
4932 for(i=0; i<ArraySize(aQuery); i++){
4933 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4934 int val = db_int(p, zSql);
4935 sqlite3_free(zSql);
4936 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4937 }
4938 sqlite3_free(zSchemaTab);
drhea99a312018-07-18 19:09:07 +00004939 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
4940 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
drh2ce15c32017-07-11 13:34:40 +00004941 return 0;
4942}
4943
4944/*
4945** Print the current sqlite3_errmsg() value to stderr and return 1.
4946*/
4947static int shellDatabaseError(sqlite3 *db){
4948 const char *zErr = sqlite3_errmsg(db);
4949 utf8_printf(stderr, "Error: %s\n", zErr);
4950 return 1;
4951}
4952
4953/*
drh2ce15c32017-07-11 13:34:40 +00004954** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4955** if they match and FALSE (0) if they do not match.
4956**
4957** Globbing rules:
4958**
4959** '*' Matches any sequence of zero or more characters.
4960**
4961** '?' Matches exactly one character.
4962**
4963** [...] Matches one character from the enclosed list of
4964** characters.
4965**
4966** [^...] Matches one character not in the enclosed list.
4967**
4968** '#' Matches any sequence of one or more digits with an
4969** optional + or - sign in front
4970**
4971** ' ' Any span of whitespace matches any other span of
4972** whitespace.
4973**
4974** Extra whitespace at the end of z[] is ignored.
4975*/
4976static int testcase_glob(const char *zGlob, const char *z){
4977 int c, c2;
4978 int invert;
4979 int seen;
4980
4981 while( (c = (*(zGlob++)))!=0 ){
4982 if( IsSpace(c) ){
4983 if( !IsSpace(*z) ) return 0;
4984 while( IsSpace(*zGlob) ) zGlob++;
4985 while( IsSpace(*z) ) z++;
4986 }else if( c=='*' ){
4987 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4988 if( c=='?' && (*(z++))==0 ) return 0;
4989 }
4990 if( c==0 ){
4991 return 1;
4992 }else if( c=='[' ){
4993 while( *z && testcase_glob(zGlob-1,z)==0 ){
4994 z++;
4995 }
4996 return (*z)!=0;
4997 }
4998 while( (c2 = (*(z++)))!=0 ){
4999 while( c2!=c ){
5000 c2 = *(z++);
5001 if( c2==0 ) return 0;
5002 }
5003 if( testcase_glob(zGlob,z) ) return 1;
5004 }
5005 return 0;
5006 }else if( c=='?' ){
5007 if( (*(z++))==0 ) return 0;
5008 }else if( c=='[' ){
5009 int prior_c = 0;
5010 seen = 0;
5011 invert = 0;
5012 c = *(z++);
5013 if( c==0 ) return 0;
5014 c2 = *(zGlob++);
5015 if( c2=='^' ){
5016 invert = 1;
5017 c2 = *(zGlob++);
5018 }
5019 if( c2==']' ){
5020 if( c==']' ) seen = 1;
5021 c2 = *(zGlob++);
5022 }
5023 while( c2 && c2!=']' ){
5024 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5025 c2 = *(zGlob++);
5026 if( c>=prior_c && c<=c2 ) seen = 1;
5027 prior_c = 0;
5028 }else{
5029 if( c==c2 ){
5030 seen = 1;
5031 }
5032 prior_c = c2;
5033 }
5034 c2 = *(zGlob++);
5035 }
5036 if( c2==0 || (seen ^ invert)==0 ) return 0;
5037 }else if( c=='#' ){
5038 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5039 if( !IsDigit(z[0]) ) return 0;
5040 z++;
5041 while( IsDigit(z[0]) ){ z++; }
5042 }else{
5043 if( c!=(*(z++)) ) return 0;
5044 }
5045 }
5046 while( IsSpace(*z) ){ z++; }
5047 return *z==0;
5048}
5049
5050
5051/*
5052** Compare the string as a command-line option with either one or two
5053** initial "-" characters.
5054*/
5055static int optionMatch(const char *zStr, const char *zOpt){
5056 if( zStr[0]!='-' ) return 0;
5057 zStr++;
5058 if( zStr[0]=='-' ) zStr++;
5059 return strcmp(zStr, zOpt)==0;
5060}
5061
5062/*
5063** Delete a file.
5064*/
5065int shellDeleteFile(const char *zFilename){
5066 int rc;
5067#ifdef _WIN32
5068 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5069 rc = _wunlink(z);
5070 sqlite3_free(z);
5071#else
5072 rc = unlink(zFilename);
5073#endif
5074 return rc;
5075}
5076
drh13c20932018-01-10 21:41:55 +00005077/*
5078** Try to delete the temporary file (if there is one) and free the
5079** memory used to hold the name of the temp file.
5080*/
5081static void clearTempFile(ShellState *p){
5082 if( p->zTempFile==0 ) return;
drh536c3452018-01-11 00:38:39 +00005083 if( p->doXdgOpen ) return;
drh13c20932018-01-10 21:41:55 +00005084 if( shellDeleteFile(p->zTempFile) ) return;
5085 sqlite3_free(p->zTempFile);
5086 p->zTempFile = 0;
5087}
5088
5089/*
5090** Create a new temp file name with the given suffix.
5091*/
5092static void newTempFile(ShellState *p, const char *zSuffix){
5093 clearTempFile(p);
5094 sqlite3_free(p->zTempFile);
5095 p->zTempFile = 0;
drh7f3bf8a2018-01-10 21:50:08 +00005096 if( p->db ){
5097 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5098 }
drh13c20932018-01-10 21:41:55 +00005099 if( p->zTempFile==0 ){
5100 sqlite3_uint64 r;
5101 sqlite3_randomness(sizeof(r), &r);
5102 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
5103 }else{
5104 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5105 }
5106 if( p->zTempFile==0 ){
5107 raw_printf(stderr, "out of memory\n");
5108 exit(1);
5109 }
5110}
5111
drh2ce15c32017-07-11 13:34:40 +00005112
5113/*
5114** The implementation of SQL scalar function fkey_collate_clause(), used
5115** by the ".lint fkey-indexes" command. This scalar function is always
5116** called with four arguments - the parent table name, the parent column name,
5117** the child table name and the child column name.
5118**
5119** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5120**
5121** If either of the named tables or columns do not exist, this function
5122** returns an empty string. An empty string is also returned if both tables
5123** and columns exist but have the same default collation sequence. Or,
5124** if both exist but the default collation sequences are different, this
5125** function returns the string " COLLATE <parent-collation>", where
5126** <parent-collation> is the default collation sequence of the parent column.
5127*/
5128static void shellFkeyCollateClause(
5129 sqlite3_context *pCtx,
5130 int nVal,
5131 sqlite3_value **apVal
5132){
5133 sqlite3 *db = sqlite3_context_db_handle(pCtx);
5134 const char *zParent;
5135 const char *zParentCol;
5136 const char *zParentSeq;
5137 const char *zChild;
5138 const char *zChildCol;
5139 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
5140 int rc;
5141
5142 assert( nVal==4 );
5143 zParent = (const char*)sqlite3_value_text(apVal[0]);
5144 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5145 zChild = (const char*)sqlite3_value_text(apVal[2]);
5146 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5147
5148 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5149 rc = sqlite3_table_column_metadata(
5150 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5151 );
5152 if( rc==SQLITE_OK ){
5153 rc = sqlite3_table_column_metadata(
5154 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5155 );
5156 }
5157
5158 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5159 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5160 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5161 sqlite3_free(z);
5162 }
5163}
5164
5165
5166/*
5167** The implementation of dot-command ".lint fkey-indexes".
5168*/
5169static int lintFkeyIndexes(
5170 ShellState *pState, /* Current shell tool state */
5171 char **azArg, /* Array of arguments passed to dot command */
5172 int nArg /* Number of entries in azArg[] */
5173){
5174 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
5175 FILE *out = pState->out; /* Stream to write non-error output to */
5176 int bVerbose = 0; /* If -verbose is present */
5177 int bGroupByParent = 0; /* If -groupbyparent is present */
5178 int i; /* To iterate through azArg[] */
5179 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
5180 int rc; /* Return code */
5181 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
5182
5183 /*
5184 ** This SELECT statement returns one row for each foreign key constraint
5185 ** in the schema of the main database. The column values are:
5186 **
5187 ** 0. The text of an SQL statement similar to:
5188 **
danf9679312017-12-01 18:40:18 +00005189 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00005190 **
danf9679312017-12-01 18:40:18 +00005191 ** This SELECT is similar to the one that the foreign keys implementation
5192 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00005193 ** be used to optimize this query, then it can also be used by the FK
5194 ** implementation to optimize DELETE or UPDATE statements on the parent
5195 ** table.
5196 **
5197 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5198 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5199 ** contains an index that can be used to optimize the query.
5200 **
5201 ** 2. Human readable text that describes the child table and columns. e.g.
5202 **
5203 ** "child_table(child_key1, child_key2)"
5204 **
5205 ** 3. Human readable text that describes the parent table and columns. e.g.
5206 **
5207 ** "parent_table(parent_key1, parent_key2)"
5208 **
5209 ** 4. A full CREATE INDEX statement for an index that could be used to
5210 ** optimize DELETE or UPDATE statements on the parent table. e.g.
5211 **
5212 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
5213 **
5214 ** 5. The name of the parent table.
5215 **
5216 ** These six values are used by the C logic below to generate the report.
5217 */
5218 const char *zSql =
5219 "SELECT "
danf9679312017-12-01 18:40:18 +00005220 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00005221 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5222 " || fkey_collate_clause("
5223 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5224 ", "
5225 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
5226 " || group_concat('*=?', ' AND ') || ')'"
5227 ", "
5228 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
5229 ", "
5230 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5231 ", "
5232 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5233 " || ' ON ' || quote(s.name) || '('"
5234 " || group_concat(quote(f.[from]) ||"
5235 " fkey_collate_clause("
5236 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5237 " || ');'"
5238 ", "
5239 " f.[table] "
5240 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
5241 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5242 "GROUP BY s.name, f.id "
5243 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5244 ;
5245 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
5246
5247 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00005248 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00005249 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5250 bVerbose = 1;
5251 }
5252 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5253 bGroupByParent = 1;
5254 zIndent = " ";
5255 }
5256 else{
5257 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5258 azArg[0], azArg[1]
5259 );
5260 return SQLITE_ERROR;
5261 }
5262 }
5263
5264 /* Register the fkey_collate_clause() SQL function */
5265 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5266 0, shellFkeyCollateClause, 0, 0
5267 );
5268
5269
5270 if( rc==SQLITE_OK ){
5271 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5272 }
5273 if( rc==SQLITE_OK ){
5274 sqlite3_bind_int(pSql, 1, bGroupByParent);
5275 }
5276
5277 if( rc==SQLITE_OK ){
5278 int rc2;
5279 char *zPrev = 0;
5280 while( SQLITE_ROW==sqlite3_step(pSql) ){
5281 int res = -1;
5282 sqlite3_stmt *pExplain = 0;
5283 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5284 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5285 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5286 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5287 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5288 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5289
5290 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5291 if( rc!=SQLITE_OK ) break;
5292 if( SQLITE_ROW==sqlite3_step(pExplain) ){
5293 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5294 res = (
5295 0==sqlite3_strglob(zGlob, zPlan)
5296 || 0==sqlite3_strglob(zGlobIPK, zPlan)
5297 );
5298 }
5299 rc = sqlite3_finalize(pExplain);
5300 if( rc!=SQLITE_OK ) break;
5301
5302 if( res<0 ){
5303 raw_printf(stderr, "Error: internal error");
5304 break;
5305 }else{
5306 if( bGroupByParent
5307 && (bVerbose || res==0)
5308 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5309 ){
5310 raw_printf(out, "-- Parent table %s\n", zParent);
5311 sqlite3_free(zPrev);
5312 zPrev = sqlite3_mprintf("%s", zParent);
5313 }
5314
5315 if( res==0 ){
5316 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5317 }else if( bVerbose ){
5318 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5319 zIndent, zFrom, zTarget
5320 );
5321 }
5322 }
5323 }
5324 sqlite3_free(zPrev);
5325
5326 if( rc!=SQLITE_OK ){
5327 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5328 }
5329
5330 rc2 = sqlite3_finalize(pSql);
5331 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5332 rc = rc2;
5333 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5334 }
5335 }else{
5336 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5337 }
5338
5339 return rc;
5340}
5341
5342/*
5343** Implementation of ".lint" dot command.
5344*/
5345static int lintDotCommand(
5346 ShellState *pState, /* Current shell tool state */
5347 char **azArg, /* Array of arguments passed to dot command */
5348 int nArg /* Number of entries in azArg[] */
5349){
5350 int n;
drhaf2770f2018-01-05 14:55:43 +00005351 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00005352 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5353 return lintFkeyIndexes(pState, azArg, nArg);
5354
5355 usage:
5356 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5357 raw_printf(stderr, "Where sub-commands are:\n");
5358 raw_printf(stderr, " fkey-indexes\n");
5359 return SQLITE_ERROR;
5360}
5361
drhe37c0e12018-01-06 19:19:50 +00005362#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5363/*********************************************************************************
5364** The ".archive" or ".ar" command.
5365*/
danfd0245d2017-12-07 15:44:29 +00005366static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00005367 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00005368 int *pRc,
5369 const char *zSql,
5370 sqlite3_stmt **ppStmt
5371){
5372 *ppStmt = 0;
5373 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00005374 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00005375 if( rc!=SQLITE_OK ){
5376 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00005377 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00005378 );
5379 *pRc = rc;
5380 }
5381 }
5382}
5383
danac15e2d2017-12-14 19:15:07 +00005384static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00005385 sqlite3 *db,
5386 int *pRc,
danac15e2d2017-12-14 19:15:07 +00005387 sqlite3_stmt **ppStmt,
5388 const char *zFmt,
5389 ...
dan3f67ddf2017-12-13 20:04:53 +00005390){
danac15e2d2017-12-14 19:15:07 +00005391 *ppStmt = 0;
5392 if( *pRc==SQLITE_OK ){
5393 va_list ap;
5394 char *z;
5395 va_start(ap, zFmt);
5396 z = sqlite3_vmprintf(zFmt, ap);
drh1dbb1472018-10-11 10:37:24 +00005397 va_end(ap);
dan3f67ddf2017-12-13 20:04:53 +00005398 if( z==0 ){
5399 *pRc = SQLITE_NOMEM;
5400 }else{
5401 shellPrepare(db, pRc, z, ppStmt);
5402 sqlite3_free(z);
5403 }
dan3f67ddf2017-12-13 20:04:53 +00005404 }
5405}
5406
danfd0245d2017-12-07 15:44:29 +00005407static void shellFinalize(
5408 int *pRc,
5409 sqlite3_stmt *pStmt
5410){
dan25c12182017-12-07 21:03:33 +00005411 if( pStmt ){
5412 sqlite3 *db = sqlite3_db_handle(pStmt);
5413 int rc = sqlite3_finalize(pStmt);
5414 if( *pRc==SQLITE_OK ){
5415 if( rc!=SQLITE_OK ){
5416 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5417 }
5418 *pRc = rc;
5419 }
5420 }
danfd0245d2017-12-07 15:44:29 +00005421}
5422
5423static void shellReset(
5424 int *pRc,
5425 sqlite3_stmt *pStmt
5426){
5427 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00005428 if( *pRc==SQLITE_OK ){
5429 if( rc!=SQLITE_OK ){
5430 sqlite3 *db = sqlite3_db_handle(pStmt);
5431 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5432 }
5433 *pRc = rc;
5434 }
danfd0245d2017-12-07 15:44:29 +00005435}
drhe37c0e12018-01-06 19:19:50 +00005436/*
dan88be0202017-12-09 17:58:02 +00005437** Structure representing a single ".ar" command.
5438*/
5439typedef struct ArCommand ArCommand;
5440struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00005441 u8 eCmd; /* An AR_CMD_* value */
5442 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00005443 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00005444 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00005445 u8 bAppend; /* True if --append */
drhd0f9cdc2018-05-17 14:09:06 +00005446 u8 fromCmdLine; /* Run from -A instead of .archive */
drhb376b3d2018-01-10 13:11:51 +00005447 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00005448 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00005449 const char *zFile; /* --file argument, or NULL */
5450 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00005451 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00005452 ShellState *p; /* Shell state */
5453 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00005454};
5455
5456/*
5457** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5458*/
dan0d0547f2017-12-14 15:40:42 +00005459static int arUsage(FILE *f){
drh98aa2ab2018-09-26 16:53:51 +00005460 showHelp(f,"archive");
dan0d0547f2017-12-14 15:40:42 +00005461 return SQLITE_ERROR;
5462}
5463
5464/*
5465** Print an error message for the .ar command to stderr and return
5466** SQLITE_ERROR.
5467*/
drhd0f9cdc2018-05-17 14:09:06 +00005468static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
dan0d0547f2017-12-14 15:40:42 +00005469 va_list ap;
5470 char *z;
5471 va_start(ap, zFmt);
5472 z = sqlite3_vmprintf(zFmt, ap);
5473 va_end(ap);
drhd0f9cdc2018-05-17 14:09:06 +00005474 utf8_printf(stderr, "Error: %s\n", z);
5475 if( pAr->fromCmdLine ){
5476 utf8_printf(stderr, "Use \"-A\" for more help\n");
5477 }else{
5478 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5479 }
dan0d0547f2017-12-14 15:40:42 +00005480 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00005481 return SQLITE_ERROR;
5482}
5483
5484/*
5485** Values for ArCommand.eCmd.
5486*/
dand4b56e52017-12-12 20:04:59 +00005487#define AR_CMD_CREATE 1
drhb17ea912019-03-25 14:24:19 +00005488#define AR_CMD_UPDATE 2
5489#define AR_CMD_INSERT 3
5490#define AR_CMD_EXTRACT 4
5491#define AR_CMD_LIST 5
5492#define AR_CMD_HELP 6
dand4b56e52017-12-12 20:04:59 +00005493
5494/*
5495** Other (non-command) switches.
5496*/
drhb17ea912019-03-25 14:24:19 +00005497#define AR_SWITCH_VERBOSE 7
5498#define AR_SWITCH_FILE 8
5499#define AR_SWITCH_DIRECTORY 9
5500#define AR_SWITCH_APPEND 10
5501#define AR_SWITCH_DRYRUN 11
dand4b56e52017-12-12 20:04:59 +00005502
5503static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5504 switch( eSwitch ){
5505 case AR_CMD_CREATE:
5506 case AR_CMD_EXTRACT:
5507 case AR_CMD_LIST:
5508 case AR_CMD_UPDATE:
drhb17ea912019-03-25 14:24:19 +00005509 case AR_CMD_INSERT:
dan0d0547f2017-12-14 15:40:42 +00005510 case AR_CMD_HELP:
5511 if( pAr->eCmd ){
drhd0f9cdc2018-05-17 14:09:06 +00005512 return arErrorMsg(pAr, "multiple command options");
dan0d0547f2017-12-14 15:40:42 +00005513 }
dand4b56e52017-12-12 20:04:59 +00005514 pAr->eCmd = eSwitch;
5515 break;
5516
drhb376b3d2018-01-10 13:11:51 +00005517 case AR_SWITCH_DRYRUN:
5518 pAr->bDryRun = 1;
5519 break;
dand4b56e52017-12-12 20:04:59 +00005520 case AR_SWITCH_VERBOSE:
5521 pAr->bVerbose = 1;
5522 break;
drha5676c42018-01-10 15:17:34 +00005523 case AR_SWITCH_APPEND:
5524 pAr->bAppend = 1;
drhca7733b2018-01-10 18:09:20 +00005525 /* Fall thru into --file */
dand4b56e52017-12-12 20:04:59 +00005526 case AR_SWITCH_FILE:
5527 pAr->zFile = zArg;
5528 break;
5529 case AR_SWITCH_DIRECTORY:
5530 pAr->zDir = zArg;
5531 break;
5532 }
5533
5534 return SQLITE_OK;
5535}
dan88be0202017-12-09 17:58:02 +00005536
5537/*
5538** Parse the command line for an ".ar" command. The results are written into
5539** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5540** successfully, otherwise an error message is written to stderr and
5541** SQLITE_ERROR returned.
5542*/
5543static int arParseCommand(
5544 char **azArg, /* Array of arguments passed to dot command */
5545 int nArg, /* Number of entries in azArg[] */
5546 ArCommand *pAr /* Populate this object */
5547){
dand4b56e52017-12-12 20:04:59 +00005548 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00005549 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00005550 char cShort;
5551 u8 eSwitch;
5552 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00005553 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00005554 { "create", 'c', AR_CMD_CREATE, 0 },
5555 { "extract", 'x', AR_CMD_EXTRACT, 0 },
drhb17ea912019-03-25 14:24:19 +00005556 { "insert", 'i', AR_CMD_INSERT, 0 },
drhb376b3d2018-01-10 13:11:51 +00005557 { "list", 't', AR_CMD_LIST, 0 },
5558 { "update", 'u', AR_CMD_UPDATE, 0 },
5559 { "help", 'h', AR_CMD_HELP, 0 },
5560 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
5561 { "file", 'f', AR_SWITCH_FILE, 1 },
drhca7733b2018-01-10 18:09:20 +00005562 { "append", 'a', AR_SWITCH_APPEND, 1 },
drhb376b3d2018-01-10 13:11:51 +00005563 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drhb376b3d2018-01-10 13:11:51 +00005564 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00005565 };
5566 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5567 struct ArSwitch *pEnd = &aSwitch[nSwitch];
5568
dan88be0202017-12-09 17:58:02 +00005569 if( nArg<=1 ){
drh98aa2ab2018-09-26 16:53:51 +00005570 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
dan0d0547f2017-12-14 15:40:42 +00005571 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00005572 }else{
5573 char *z = azArg[1];
dan88be0202017-12-09 17:58:02 +00005574 if( z[0]!='-' ){
5575 /* Traditional style [tar] invocation */
5576 int i;
5577 int iArg = 2;
5578 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00005579 const char *zArg = 0;
5580 struct ArSwitch *pOpt;
5581 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5582 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00005583 }
dan0d0547f2017-12-14 15:40:42 +00005584 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005585 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005586 }
dand4b56e52017-12-12 20:04:59 +00005587 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005588 if( iArg>=nArg ){
drhd0f9cdc2018-05-17 14:09:06 +00005589 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005590 }
dand4b56e52017-12-12 20:04:59 +00005591 zArg = azArg[iArg++];
5592 }
5593 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00005594 }
dan88be0202017-12-09 17:58:02 +00005595 pAr->nArg = nArg-iArg;
5596 if( pAr->nArg>0 ){
5597 pAr->azArg = &azArg[iArg];
5598 }
dand4b56e52017-12-12 20:04:59 +00005599 }else{
5600 /* Non-traditional invocation */
5601 int iArg;
5602 for(iArg=1; iArg<nArg; iArg++){
5603 int n;
5604 z = azArg[iArg];
5605 if( z[0]!='-' ){
5606 /* All remaining command line words are command arguments. */
5607 pAr->azArg = &azArg[iArg];
5608 pAr->nArg = nArg-iArg;
5609 break;
5610 }
drhaf2770f2018-01-05 14:55:43 +00005611 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00005612
5613 if( z[1]!='-' ){
5614 int i;
5615 /* One or more short options */
5616 for(i=1; i<n; i++){
5617 const char *zArg = 0;
5618 struct ArSwitch *pOpt;
5619 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5620 if( z[i]==pOpt->cShort ) break;
5621 }
dan0d0547f2017-12-14 15:40:42 +00005622 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005623 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005624 }
dand4b56e52017-12-12 20:04:59 +00005625 if( pOpt->bArg ){
5626 if( i<(n-1) ){
5627 zArg = &z[i+1];
5628 i = n;
5629 }else{
dan0d0547f2017-12-14 15:40:42 +00005630 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005631 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005632 }
dand4b56e52017-12-12 20:04:59 +00005633 zArg = azArg[++iArg];
5634 }
5635 }
5636 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5637 }
5638 }else if( z[2]=='\0' ){
5639 /* A -- option, indicating that all remaining command line words
5640 ** are command arguments. */
5641 pAr->azArg = &azArg[iArg+1];
5642 pAr->nArg = nArg-iArg-1;
5643 break;
5644 }else{
5645 /* A long option */
5646 const char *zArg = 0; /* Argument for option, if any */
5647 struct ArSwitch *pMatch = 0; /* Matching option */
5648 struct ArSwitch *pOpt; /* Iterator */
5649 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5650 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00005651 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00005652 if( pMatch ){
drhd0f9cdc2018-05-17 14:09:06 +00005653 return arErrorMsg(pAr, "ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00005654 }else{
5655 pMatch = pOpt;
5656 }
5657 }
5658 }
5659
5660 if( pMatch==0 ){
drhd0f9cdc2018-05-17 14:09:06 +00005661 return arErrorMsg(pAr, "unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00005662 }
5663 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005664 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005665 return arErrorMsg(pAr, "option requires an argument: %s", z);
dan0d0547f2017-12-14 15:40:42 +00005666 }
dand4b56e52017-12-12 20:04:59 +00005667 zArg = azArg[++iArg];
5668 }
5669 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5670 }
5671 }
dan88be0202017-12-09 17:58:02 +00005672 }
5673 }
5674
5675 return SQLITE_OK;
5676}
5677
5678/*
dan3f67ddf2017-12-13 20:04:53 +00005679** This function assumes that all arguments within the ArCommand.azArg[]
5680** array refer to archive members, as for the --extract or --list commands.
5681** It checks that each of them are present. If any specified file is not
5682** present in the archive, an error is printed to stderr and an error
5683** code returned. Otherwise, if all specified arguments are present in
5684** the archive, SQLITE_OK is returned.
5685**
5686** This function strips any trailing '/' characters from each argument.
5687** This is consistent with the way the [tar] command seems to work on
5688** Linux.
5689*/
drhb376b3d2018-01-10 13:11:51 +00005690static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00005691 int rc = SQLITE_OK;
5692 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00005693 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00005694 sqlite3_stmt *pTest = 0;
5695
drhb376b3d2018-01-10 13:11:51 +00005696 shellPreparePrintf(pAr->db, &rc, &pTest,
5697 "SELECT name FROM %s WHERE name=$name",
5698 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00005699 );
drhb376b3d2018-01-10 13:11:51 +00005700 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00005701 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5702 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00005703 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00005704 int bOk = 0;
5705 while( n>0 && z[n-1]=='/' ) n--;
5706 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00005707 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00005708 if( SQLITE_ROW==sqlite3_step(pTest) ){
5709 bOk = 1;
5710 }
5711 shellReset(&rc, pTest);
5712 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00005713 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00005714 rc = SQLITE_ERROR;
5715 }
5716 }
5717 shellFinalize(&rc, pTest);
5718 }
dan3f67ddf2017-12-13 20:04:53 +00005719 return rc;
5720}
5721
5722/*
5723** Format a WHERE clause that can be used against the "sqlar" table to
5724** identify all archive members that match the command arguments held
5725** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5726** The caller is responsible for eventually calling sqlite3_free() on
5727** any non-NULL (*pzWhere) value.
5728*/
5729static void arWhereClause(
5730 int *pRc,
5731 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00005732 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00005733){
5734 char *zWhere = 0;
5735 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00005736 if( pAr->nArg==0 ){
5737 zWhere = sqlite3_mprintf("1");
5738 }else{
5739 int i;
5740 const char *zSep = "";
5741 for(i=0; i<pAr->nArg; i++){
5742 const char *z = pAr->azArg[i];
5743 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00005744 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5745 zWhere, zSep, z, strlen30(z)+1, z
5746 );
danac15e2d2017-12-14 19:15:07 +00005747 if( zWhere==0 ){
5748 *pRc = SQLITE_NOMEM;
5749 break;
5750 }
5751 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00005752 }
dan3f67ddf2017-12-13 20:04:53 +00005753 }
5754 }
5755 *pzWhere = zWhere;
5756}
5757
5758/*
dan88be0202017-12-09 17:58:02 +00005759** Implementation of .ar "lisT" command.
5760*/
drhb376b3d2018-01-10 13:11:51 +00005761static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00005762 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00005763 const char *azCols[] = {
5764 "name",
drh410cad92018-01-10 17:19:16 +00005765 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00005766 };
dan5a78b812017-12-27 18:54:11 +00005767
dan3f67ddf2017-12-13 20:04:53 +00005768 char *zWhere = 0;
5769 sqlite3_stmt *pSql = 0;
5770 int rc;
5771
drhb376b3d2018-01-10 13:11:51 +00005772 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005773 arWhereClause(&rc, pAr, &zWhere);
5774
drhb376b3d2018-01-10 13:11:51 +00005775 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5776 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00005777 if( pAr->bDryRun ){
5778 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5779 }else{
5780 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5781 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00005782 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5783 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00005784 sqlite3_column_int(pSql, 1),
5785 sqlite3_column_text(pSql, 2),
5786 sqlite3_column_text(pSql, 3)
5787 );
5788 }else{
5789 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5790 }
danb5090e42017-12-27 21:13:21 +00005791 }
dan3f67ddf2017-12-13 20:04:53 +00005792 }
dan5a78b812017-12-27 18:54:11 +00005793 shellFinalize(&rc, pSql);
drhd0f9cdc2018-05-17 14:09:06 +00005794 sqlite3_free(zWhere);
dan3f67ddf2017-12-13 20:04:53 +00005795 return rc;
dan88be0202017-12-09 17:58:02 +00005796}
5797
5798
danfd0245d2017-12-07 15:44:29 +00005799/*
5800** Implementation of .ar "eXtract" command.
5801*/
drhb376b3d2018-01-10 13:11:51 +00005802static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00005803 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00005804 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00005805 " ($dir || name),"
5806 " writefile(($dir || name), %s, mode, mtime) "
drh0cfd46a2018-06-06 01:18:01 +00005807 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5808 " AND name NOT GLOB '*..[/\\]*'";
dan5a78b812017-12-27 18:54:11 +00005809
5810 const char *azExtraArg[] = {
5811 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00005812 "data"
dan5a78b812017-12-27 18:54:11 +00005813 };
dan5a78b812017-12-27 18:54:11 +00005814
danfd0245d2017-12-07 15:44:29 +00005815 sqlite3_stmt *pSql = 0;
5816 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00005817 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00005818 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00005819 int i, j;
dan2ad09492017-12-09 18:28:22 +00005820
dan3f67ddf2017-12-13 20:04:53 +00005821 /* If arguments are specified, check that they actually exist within
5822 ** the archive before proceeding. And formulate a WHERE clause to
5823 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00005824 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005825 arWhereClause(&rc, pAr, &zWhere);
5826
5827 if( rc==SQLITE_OK ){
5828 if( pAr->zDir ){
5829 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5830 }else{
5831 zDir = sqlite3_mprintf("");
5832 }
5833 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00005834 }
danfd0245d2017-12-07 15:44:29 +00005835
drhb376b3d2018-01-10 13:11:51 +00005836 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5837 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00005838 );
5839
dan2ad09492017-12-09 18:28:22 +00005840 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005841 j = sqlite3_bind_parameter_index(pSql, "$dir");
5842 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00005843
danac15e2d2017-12-14 19:15:07 +00005844 /* Run the SELECT statement twice. The first time, writefile() is called
5845 ** for all archive members that should be extracted. The second time,
5846 ** only for the directories. This is because the timestamps for
5847 ** extracted directories must be reset after they are populated (as
5848 ** populating them changes the timestamp). */
5849 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00005850 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5851 sqlite3_bind_int(pSql, j, i);
5852 if( pAr->bDryRun ){
5853 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5854 }else{
5855 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5856 if( i==0 && pAr->bVerbose ){
5857 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5858 }
danac15e2d2017-12-14 19:15:07 +00005859 }
5860 }
5861 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005862 }
danac15e2d2017-12-14 19:15:07 +00005863 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005864 }
dan25c12182017-12-07 21:03:33 +00005865
dan2ad09492017-12-09 18:28:22 +00005866 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00005867 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00005868 return rc;
5869}
5870
drhb376b3d2018-01-10 13:11:51 +00005871/*
5872** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5873*/
5874static int arExecSql(ArCommand *pAr, const char *zSql){
5875 int rc;
5876 if( pAr->bDryRun ){
5877 utf8_printf(pAr->p->out, "%s\n", zSql);
5878 rc = SQLITE_OK;
5879 }else{
drh410cad92018-01-10 17:19:16 +00005880 char *zErr = 0;
5881 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5882 if( zErr ){
5883 utf8_printf(stdout, "ERROR: %s\n", zErr);
5884 sqlite3_free(zErr);
5885 }
drhb376b3d2018-01-10 13:11:51 +00005886 }
5887 return rc;
5888}
5889
dan1ad3f612017-12-11 20:22:02 +00005890
danfd0245d2017-12-07 15:44:29 +00005891/*
drhb17ea912019-03-25 14:24:19 +00005892** Implementation of .ar "create", "insert", and "update" commands.
5893**
5894** create -> Create a new SQL archive
5895** insert -> Insert or reinsert all files listed
5896** update -> Insert files that have changed or that were not
5897** previously in the archive
danfd0245d2017-12-07 15:44:29 +00005898**
5899** Create the "sqlar" table in the database if it does not already exist.
5900** Then add each file in the azFile[] array to the archive. Directories
5901** are added recursively. If argument bVerbose is non-zero, a message is
5902** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00005903**
5904** The create command is the same as update, except that it drops
drhb17ea912019-03-25 14:24:19 +00005905** any existing "sqlar" table before beginning. The "insert" command
5906** always overwrites every file named on the command-line, where as
5907** "update" only overwrites if the size or mtime or mode has changed.
danfd0245d2017-12-07 15:44:29 +00005908*/
drhb376b3d2018-01-10 13:11:51 +00005909static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00005910 ArCommand *pAr, /* Command arguments and options */
drhb17ea912019-03-25 14:24:19 +00005911 int bUpdate, /* true for a --create. */
5912 int bOnlyIfChanged /* Only update if file has changed */
danfd0245d2017-12-07 15:44:29 +00005913){
dand4b56e52017-12-12 20:04:59 +00005914 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00005915 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5916 " name TEXT PRIMARY KEY, -- name of the file\n"
5917 " mode INT, -- access permissions\n"
5918 " mtime INT, -- last modification time\n"
5919 " sz INT, -- original file size\n"
5920 " data BLOB -- compressed content\n"
5921 ")";
dand4b56e52017-12-12 20:04:59 +00005922 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh1bf208c2018-03-09 21:54:01 +00005923 const char *zInsertFmt[2] = {
5924 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
drh634c70f2018-01-10 16:50:18 +00005925 " SELECT\n"
5926 " %s,\n"
5927 " mode,\n"
5928 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00005929 " CASE substr(lsmode(mode),1,1)\n"
5930 " WHEN '-' THEN length(data)\n"
5931 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00005932 " ELSE -1 END,\n"
drh69d2d352018-03-09 22:18:53 +00005933 " sqlar_compress(data)\n"
drhb17ea912019-03-25 14:24:19 +00005934 " FROM fsdir(%Q,%Q) AS disk\n"
5935 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
5936 ,
drh1bf208c2018-03-09 21:54:01 +00005937 "REPLACE INTO %s(name,mode,mtime,data)\n"
5938 " SELECT\n"
5939 " %s,\n"
5940 " mode,\n"
5941 " mtime,\n"
5942 " data\n"
drhb17ea912019-03-25 14:24:19 +00005943 " FROM fsdir(%Q,%Q) AS disk\n"
5944 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
drh1bf208c2018-03-09 21:54:01 +00005945 };
danfd0245d2017-12-07 15:44:29 +00005946 int i; /* For iterating through azFile[] */
5947 int rc; /* Return code */
drh1bf208c2018-03-09 21:54:01 +00005948 const char *zTab = 0; /* SQL table into which to insert */
5949 char *zSql;
5950 char zTemp[50];
drhb17ea912019-03-25 14:24:19 +00005951 char *zExists = 0;
danfd0245d2017-12-07 15:44:29 +00005952
drh1bf208c2018-03-09 21:54:01 +00005953 arExecSql(pAr, "PRAGMA page_size=512");
drhb376b3d2018-01-10 13:11:51 +00005954 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00005955 if( rc!=SQLITE_OK ) return rc;
drh1bf208c2018-03-09 21:54:01 +00005956 zTemp[0] = 0;
5957 if( pAr->bZip ){
5958 /* Initialize the zipfile virtual table, if necessary */
5959 if( pAr->zFile ){
5960 sqlite3_uint64 r;
5961 sqlite3_randomness(sizeof(r),&r);
5962 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5963 zTab = zTemp;
5964 zSql = sqlite3_mprintf(
5965 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5966 zTab, pAr->zFile
5967 );
5968 rc = arExecSql(pAr, zSql);
5969 sqlite3_free(zSql);
5970 }else{
5971 zTab = "zip";
5972 }
5973 }else{
5974 /* Initialize the table for an SQLAR */
5975 zTab = "sqlar";
5976 if( bUpdate==0 ){
5977 rc = arExecSql(pAr, zDrop);
5978 if( rc!=SQLITE_OK ) goto end_ar_transaction;
5979 }
5980 rc = arExecSql(pAr, zCreate);
dan06741a32017-12-13 20:17:18 +00005981 }
drhb17ea912019-03-25 14:24:19 +00005982 if( bOnlyIfChanged ){
5983 zExists = sqlite3_mprintf(
5984 " AND NOT EXISTS("
5985 "SELECT 1 FROM %s AS mem"
5986 " WHERE mem.name=disk.name"
5987 " AND mem.mtime=disk.mtime"
5988 " AND mem.mode=disk.mode)", zTab);
5989 }else{
5990 zExists = sqlite3_mprintf("");
5991 }
5992 if( zExists==0 ) rc = SQLITE_NOMEM;
dan88be0202017-12-09 17:58:02 +00005993 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
mistachkince2052b2018-03-23 00:31:53 +00005994 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
drh634c70f2018-01-10 16:50:18 +00005995 pAr->bVerbose ? "shell_putsnl(name)" : "name",
drhb17ea912019-03-25 14:24:19 +00005996 pAr->azArg[i], pAr->zDir, zExists);
mistachkince2052b2018-03-23 00:31:53 +00005997 rc = arExecSql(pAr, zSql2);
5998 sqlite3_free(zSql2);
danfd0245d2017-12-07 15:44:29 +00005999 }
drh1bf208c2018-03-09 21:54:01 +00006000end_ar_transaction:
danfd0245d2017-12-07 15:44:29 +00006001 if( rc!=SQLITE_OK ){
drh2bd207f2019-01-11 17:19:59 +00006002 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00006003 }else{
drhb376b3d2018-01-10 13:11:51 +00006004 rc = arExecSql(pAr, "RELEASE ar;");
drh1bf208c2018-03-09 21:54:01 +00006005 if( pAr->bZip && pAr->zFile ){
6006 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6007 arExecSql(pAr, zSql);
6008 sqlite3_free(zSql);
6009 }
danfd0245d2017-12-07 15:44:29 +00006010 }
drhb17ea912019-03-25 14:24:19 +00006011 sqlite3_free(zExists);
danfd0245d2017-12-07 15:44:29 +00006012 return rc;
6013}
6014
6015/*
6016** Implementation of ".ar" dot command.
6017*/
6018static int arDotCommand(
6019 ShellState *pState, /* Current shell tool state */
drhd0f9cdc2018-05-17 14:09:06 +00006020 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
danfd0245d2017-12-07 15:44:29 +00006021 char **azArg, /* Array of arguments passed to dot command */
6022 int nArg /* Number of entries in azArg[] */
6023){
dan88be0202017-12-09 17:58:02 +00006024 ArCommand cmd;
6025 int rc;
drh34660642018-01-10 17:39:54 +00006026 memset(&cmd, 0, sizeof(cmd));
drhd0f9cdc2018-05-17 14:09:06 +00006027 cmd.fromCmdLine = fromCmdLine;
dan88be0202017-12-09 17:58:02 +00006028 rc = arParseCommand(azArg, nArg, &cmd);
6029 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00006030 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00006031 cmd.p = pState;
6032 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00006033 if( cmd.zFile ){
drh1bf208c2018-03-09 21:54:01 +00006034 eDbType = deduceDatabaseType(cmd.zFile, 1);
drha5676c42018-01-10 15:17:34 +00006035 }else{
6036 eDbType = pState->openMode;
6037 }
6038 if( eDbType==SHELL_OPEN_ZIPFILE ){
drh1bf208c2018-03-09 21:54:01 +00006039 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6040 if( cmd.zFile==0 ){
6041 cmd.zSrcTable = sqlite3_mprintf("zip");
6042 }else{
6043 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6044 }
dan5a78b812017-12-27 18:54:11 +00006045 }
drha5676c42018-01-10 15:17:34 +00006046 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00006047 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00006048 int flags;
drha5676c42018-01-10 15:17:34 +00006049 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
drhb17ea912019-03-25 14:24:19 +00006050 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6051 || cmd.eCmd==AR_CMD_UPDATE ){
dand4b56e52017-12-12 20:04:59 +00006052 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6053 }else{
6054 flags = SQLITE_OPEN_READONLY;
6055 }
drha82c95b2018-01-10 14:00:00 +00006056 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00006057 if( cmd.bDryRun ){
6058 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6059 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6060 }
6061 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6062 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00006063 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00006064 utf8_printf(stderr, "cannot open file: %s (%s)\n",
6065 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00006066 );
drha5676c42018-01-10 15:17:34 +00006067 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00006068 }
drhb376b3d2018-01-10 13:11:51 +00006069 sqlite3_fileio_init(cmd.db, 0, 0);
drhb376b3d2018-01-10 13:11:51 +00006070 sqlite3_sqlar_init(cmd.db, 0, 0);
drh34660642018-01-10 17:39:54 +00006071 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6072 shellPutsFunc, 0, 0);
6073
dand4b56e52017-12-12 20:04:59 +00006074 }
drhd0f9cdc2018-05-17 14:09:06 +00006075 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
drh634c70f2018-01-10 16:50:18 +00006076 if( cmd.eCmd!=AR_CMD_CREATE
6077 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6078 ){
drha5676c42018-01-10 15:17:34 +00006079 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6080 rc = SQLITE_ERROR;
6081 goto end_ar_command;
6082 }
6083 cmd.zSrcTable = sqlite3_mprintf("sqlar");
6084 }
dand4b56e52017-12-12 20:04:59 +00006085
dan88be0202017-12-09 17:58:02 +00006086 switch( cmd.eCmd ){
6087 case AR_CMD_CREATE:
drhb17ea912019-03-25 14:24:19 +00006088 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
dan88be0202017-12-09 17:58:02 +00006089 break;
danfd0245d2017-12-07 15:44:29 +00006090
dan88be0202017-12-09 17:58:02 +00006091 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00006092 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00006093 break;
6094
6095 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00006096 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00006097 break;
6098
dan0d0547f2017-12-14 15:40:42 +00006099 case AR_CMD_HELP:
6100 arUsage(pState->out);
6101 break;
6102
drhb17ea912019-03-25 14:24:19 +00006103 case AR_CMD_INSERT:
6104 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6105 break;
6106
dan88be0202017-12-09 17:58:02 +00006107 default:
6108 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb17ea912019-03-25 14:24:19 +00006109 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
dan88be0202017-12-09 17:58:02 +00006110 break;
danfd0245d2017-12-07 15:44:29 +00006111 }
6112 }
drha5676c42018-01-10 15:17:34 +00006113end_ar_command:
6114 if( cmd.db!=pState->db ){
drh9e804032018-05-18 17:11:50 +00006115 close_db(cmd.db);
drha5676c42018-01-10 15:17:34 +00006116 }
6117 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00006118
dan88be0202017-12-09 17:58:02 +00006119 return rc;
danfd0245d2017-12-07 15:44:29 +00006120}
drhe37c0e12018-01-06 19:19:50 +00006121/* End of the ".archive" or ".ar" command logic
6122**********************************************************************************/
6123#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00006124
dan68cb86e2019-04-20 20:57:28 +00006125static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6126 int rc = *pRc;
6127 if( rc==SQLITE_OK ){
6128 char *zErr = 0;
6129 rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6130 if( rc!=SQLITE_OK ){
6131 raw_printf(stderr, "SQL error: %s\n", zErr);
6132 }
6133 *pRc = rc;
6134 }
6135}
6136
6137static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6138 void *pRet = 0;
6139 if( *pRc==SQLITE_OK ){
6140 pRet = sqlite3_malloc64(nByte);
6141 if( pRet==0 ){
6142 *pRc = SQLITE_NOMEM;
6143 }else{
6144 memset(pRet, 0, nByte);
6145 }
6146 }
6147 return pRet;
6148}
6149
6150static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6151 char *z = 0;
6152 if( *pRc==SQLITE_OK ){
6153 va_list ap;
6154 va_start(ap, zFmt);
6155 z = sqlite3_vmprintf(zFmt, ap);
6156 va_end(ap);
6157 if( z==0 ){
6158 *pRc = SQLITE_NOMEM;
6159 }
6160 }
6161 return z;
6162}
6163
6164typedef struct RecoverTable RecoverTable;
6165struct RecoverTable {
6166 char *zName; /* Name of table */
6167 char *zQuoted; /* Quoted version of zName */
dan68cb86e2019-04-20 20:57:28 +00006168 int nCol; /* Number of columns in table */
6169 char **azlCol; /* Array of column lists */
danb40af492019-04-22 20:52:12 +00006170 int iPk;
dan68cb86e2019-04-20 20:57:28 +00006171};
6172
6173/*
6174** Free a RecoverTable object allocated by recoverNewTable()
6175*/
6176static void recoverFreeTable(RecoverTable *pTab){
6177 if( pTab ){
6178 sqlite3_free(pTab->zName);
6179 sqlite3_free(pTab->zQuoted);
dan68cb86e2019-04-20 20:57:28 +00006180 if( pTab->azlCol ){
6181 int i;
6182 for(i=0; i<pTab->nCol; i++){
6183 sqlite3_free(pTab->azlCol[i]);
6184 }
6185 sqlite3_free(pTab->azlCol);
6186 }
6187 sqlite3_free(pTab);
6188 }
6189}
6190
danb40af492019-04-22 20:52:12 +00006191static void recoverOldTable(
6192 int *pRc, /* IN/OUT: Error code */
6193 RecoverTable *pTab,
6194 const char *zName, /* Name of table */
6195 const char *zSql, /* CREATE TABLE statement */
6196 int bIntkey,
6197 int nCol
6198){
6199 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */
6200 int rc = *pRc;
6201
6202 if( rc==SQLITE_OK ){
6203 int nSqlCol = 0;
6204 int bSqlIntkey = 0;
6205 sqlite3_stmt *pStmt = 0;
6206
6207 rc = sqlite3_open("", &dbtmp);
6208 if( rc==SQLITE_OK ){
dan38f9c712019-04-23 18:03:02 +00006209 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
6210 }
6211 if( rc==SQLITE_OK ){
danb40af492019-04-22 20:52:12 +00006212 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
6213 if( rc==SQLITE_ERROR ){
6214 rc = SQLITE_OK;
6215 goto finished;
6216 }
6217 }
6218 shellPreparePrintf(dbtmp, &rc, &pStmt,
6219 "SELECT count(*) FROM pragma_table_info(%Q)", zName
6220 );
6221 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6222 nSqlCol = sqlite3_column_int(pStmt, 0);
6223 }
6224 shellFinalize(&rc, pStmt);
6225
6226 if( rc!=SQLITE_OK || nSqlCol<nCol ){
6227 goto finished;
6228 }
6229
6230 shellPreparePrintf(dbtmp, &rc, &pStmt,
6231 "SELECT ("
6232 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
6233 ") FROM sqlite_master WHERE name = %Q", zName
6234 );
6235 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6236 bSqlIntkey = sqlite3_column_int(pStmt, 0);
6237 }
6238 shellFinalize(&rc, pStmt);
6239
6240 if( bIntkey==bSqlIntkey ){
6241 const char *zPk = "_rowid_";
6242 sqlite3_stmt *pPkFinder = 0;
6243
6244 shellPreparePrintf(dbtmp, &rc, &pPkFinder,
6245 "SELECT cid, name FROM pragma_table_info(%Q) "
6246 " WHERE pk=1 AND type='integer' COLLATE nocase"
6247 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)",
6248 zName, zName
6249 );
6250 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
6251 pTab->iPk = sqlite3_column_int(pPkFinder, 0);
6252 zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
6253 }
6254
6255 pTab->zName = shellMPrintf(&rc, "%s", zName);
6256 pTab->zQuoted = shellMPrintf(&rc, "%Q", pTab->zName);
6257 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * nSqlCol);
6258 pTab->nCol = nSqlCol;
6259
6260 if( nSqlCol==1 && pTab->iPk==0 ){
6261 pTab->azlCol[0] = shellMPrintf(&rc, "%Q", zPk);
6262 }else{
6263 shellPreparePrintf(dbtmp, &rc, &pStmt,
6264 "SELECT -1+row_number() OVER (ORDER BY cid),"
6265 " %Q||%Q||group_concat(name, ', ') FILTER (WHERE cid!=%d) "
6266 " OVER (ORDER BY cid) "
6267 "FROM pragma_table_info(%Q)",
6268 (bIntkey ? zPk : ""), (bIntkey ? ", " : ""),
6269 pTab->iPk, zName
6270 );
6271 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6272 int idx = sqlite3_column_int(pStmt, 0);
6273 const char *zText = (const char*)sqlite3_column_text(pStmt, 1);
6274 pTab->azlCol[idx] = shellMPrintf(&rc, "%s", zText);
6275 }
6276 shellFinalize(&rc, pStmt);
6277 }
6278 shellFinalize(&rc, pPkFinder);
6279 }
6280 }
6281
6282 finished:
6283 sqlite3_close(dbtmp);
6284 *pRc = rc;
6285}
6286
dan68cb86e2019-04-20 20:57:28 +00006287static RecoverTable *recoverNewTable(
6288 ShellState *pState,
6289 int *pRc,
6290 int iRoot,
danb40af492019-04-22 20:52:12 +00006291 int bIntkey,
dan68cb86e2019-04-20 20:57:28 +00006292 int nCol
6293){
danb40af492019-04-22 20:52:12 +00006294 sqlite3_stmt *pStmt = 0;
dan68cb86e2019-04-20 20:57:28 +00006295 RecoverTable *pRet = 0;
danb40af492019-04-22 20:52:12 +00006296 int bNoop = 0;
6297 const char *zSql = 0;
6298 const char *zName = 0;
dan68cb86e2019-04-20 20:57:28 +00006299
6300 pRet = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
danb40af492019-04-22 20:52:12 +00006301 if( pRet ) pRet->iPk = -2;
6302
6303 /* Search the recovered schema for an object with root page iRoot. */
6304 shellPreparePrintf(pState->db, pRc, &pStmt,
6305 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
6306 );
6307 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6308 const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
6309 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
6310 bNoop = 1;
6311 break;
6312 }
6313 if( sqlite3_stricmp(zType, "table")==0 ){
6314 zName = (const char*)sqlite3_column_text(pStmt, 1);
6315 zSql = (const char*)sqlite3_column_text(pStmt, 2);
6316 recoverOldTable(pRc, pRet, zName, zSql, bIntkey, nCol);
6317 break;
6318 }
6319 }
6320 shellFinalize(pRc, pStmt);
6321 if( bNoop ){
6322 sqlite3_free(pRet);
6323 return 0;
6324 }
6325
6326 if( pRet && pRet->zName==0 ){
dan68cb86e2019-04-20 20:57:28 +00006327 sqlite3_stmt *pStmt = 0;
danb40af492019-04-22 20:52:12 +00006328
dan68cb86e2019-04-20 20:57:28 +00006329 pRet->zName = shellMPrintf(pRc, "orphan_%d_%d", nCol, iRoot);
6330 pRet->zQuoted = shellMPrintf(pRc, "%Q", pRet->zName);
6331 pRet->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * nCol);
6332 pRet->nCol = nCol;
6333
6334 shellPreparePrintf(pState->db, pRc, &pStmt,
6335 "WITH s(i) AS ("
6336 " SELECT 1 UNION ALL SELECT i+1 FROM s WHERE i<%d"
6337 ")"
danb40af492019-04-22 20:52:12 +00006338 "SELECT i-1, %Q || group_concat('c' || i, ', ') OVER (ORDER BY i) FROM s",
6339 nCol, (bIntkey ? "id, " : "")
dan68cb86e2019-04-20 20:57:28 +00006340 );
6341 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6342 int idx = sqlite3_column_int(pStmt, 0);
6343 const char *zText = (const char*)sqlite3_column_text(pStmt, 1);
6344 pRet->azlCol[idx] = shellMPrintf(pRc, "%s", zText);
6345 }
6346 shellFinalize(pRc, pStmt);
6347
danb40af492019-04-22 20:52:12 +00006348 if( *pRc==SQLITE_OK ){
6349 char *zCreate = shellMPrintf(pRc, "CREATE TABLE %Q (%s)",
dan68cb86e2019-04-20 20:57:28 +00006350 pRet->zName, pRet->azlCol[nCol-1]
danb40af492019-04-22 20:52:12 +00006351 );
6352 if( zCreate ){
6353 raw_printf(pState->out, "%s;\n", zCreate);
6354 sqlite3_free(zCreate);
6355 }
6356 }
dan68cb86e2019-04-20 20:57:28 +00006357 }
6358
6359 if( *pRc!=SQLITE_OK ){
6360 recoverFreeTable(pRet);
6361 pRet = 0;
6362 }
6363
6364 return pRet;
6365}
6366
6367/*
6368** This function is called to recover data from the database. A script
6369** to construct a new database containing all recovered data is output
6370** on stream pState->out.
6371*/
6372static int recoverDatabaseCmd(ShellState *pState){
dan68cb86e2019-04-20 20:57:28 +00006373 int rc = SQLITE_OK;
6374 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */
danefa363b2019-04-24 20:48:55 +00006375 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */
6376 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */
dan68cb86e2019-04-20 20:57:28 +00006377
6378 shellExec(pState->db, &rc,
6379 /* Attach an in-memory database named 'recovery'. Create an indexed
6380 ** cache of the sqlite_dbptr virtual table. */
6381 "ATTACH '' AS recovery;"
6382 "CREATE TABLE recovery.dbptr("
6383 " pgno, child, PRIMARY KEY(child, pgno)"
6384 ") WITHOUT ROWID;"
6385 "INSERT OR IGNORE INTO dbptr(pgno, child) SELECT * FROM sqlite_dbptr;"
6386
6387 /* Delete any pointer to page 1. This ensures that page 1 is considered
6388 ** a root page, regardless of how corrupt the db is. */
6389 "DELETE FROM recovery.dbptr WHERE child = 1;"
6390
6391 /* Delete all pointers to any pages that have more than one pointer
6392 ** to them. Such pages will be treated as root pages when recovering
6393 ** data. */
6394 "DELETE FROM recovery.dbptr WHERE child IN ("
6395 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
6396 ");"
6397
6398 /* Create the "map" table that will (eventually) contain instructions
6399 ** for dealing with each page in the db that contains one or more
6400 ** records. */
danb40af492019-04-22 20:52:12 +00006401 "CREATE TABLE recovery.map("
6402 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
6403 ");"
dan68cb86e2019-04-20 20:57:28 +00006404
6405 /* Populate table [map]. If there are circular loops of pages in the
6406 ** database, the following adds all pages in such a loop to the map
6407 ** as individual root pages. This could be handled better. */
6408 "WITH pages(i, maxlen) AS ("
6409 " SELECT page_count, max(field+1) "
6410 " FROM pragma_page_count, sqlite_dbdata WHERE pgno=page_count"
6411 " UNION ALL"
danb40af492019-04-22 20:52:12 +00006412 " SELECT i-1, ("
6413 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
6414 " ) FROM pages WHERE i>=2"
dan68cb86e2019-04-20 20:57:28 +00006415 ")"
danb40af492019-04-22 20:52:12 +00006416 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
6417 " SELECT i, maxlen, NULL, ("
dan68cb86e2019-04-20 20:57:28 +00006418 " WITH p(orig, pgno, parent) AS ("
6419 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
6420 " UNION ALL"
6421 " SELECT i, p.parent, "
6422 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
6423 " )"
6424 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
6425 ") "
6426 "FROM pages WHERE maxlen > 0;"
danb40af492019-04-22 20:52:12 +00006427 "UPDATE recovery.map AS o SET intkey = ("
6428 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
6429 ");"
dan68cb86e2019-04-20 20:57:28 +00006430
6431 /* Extract data from page 1 and any linked pages into table
6432 ** recovery.schema. With the same schema as an sqlite_master table. */
6433 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
6434 "INSERT INTO recovery.schema SELECT "
6435 " max(CASE WHEN field=0 THEN value ELSE NULL END),"
6436 " max(CASE WHEN field=1 THEN value ELSE NULL END),"
6437 " max(CASE WHEN field=2 THEN value ELSE NULL END),"
6438 " max(CASE WHEN field=3 THEN value ELSE NULL END),"
6439 " max(CASE WHEN field=4 THEN value ELSE NULL END)"
6440 "FROM sqlite_dbdata WHERE pgno IN ("
6441 " SELECT pgno FROM recovery.map WHERE root=1"
6442 ")"
6443 "GROUP BY pgno, cell;"
6444 );
6445
danb40af492019-04-22 20:52:12 +00006446 /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
6447 ** CREATE TABLE statements that extracted from the existing schema. */
6448 if( rc==SQLITE_OK ){
6449 sqlite3_stmt *pStmt = 0;
6450 raw_printf(pState->out, "BEGIN;\n");
dan38f9c712019-04-23 18:03:02 +00006451 raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
6452 shellPrepare(pState->db, &rc,
danb40af492019-04-22 20:52:12 +00006453 "SELECT sql FROM recovery.schema "
dan38f9c712019-04-23 18:03:02 +00006454 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
danb40af492019-04-22 20:52:12 +00006455 );
6456 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6457 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
dan38f9c712019-04-23 18:03:02 +00006458 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
6459 &zCreateTable[12]
6460 );
danb40af492019-04-22 20:52:12 +00006461 }
6462 shellFinalize(&rc, pStmt);
6463 }
6464
danefa363b2019-04-24 20:48:55 +00006465 shellPrepare(pState->db, &rc,
6466 "SELECT pgno FROM recovery.map WHERE root=?", &pPages
6467 );
6468 shellPrepare(pState->db, &rc,
6469 "SELECT max(field), group_concat(shell_escape_crnl(quote(value)), ', ')"
6470 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
6471 "GROUP BY cell", &pCells
6472 );
6473
dan68cb86e2019-04-20 20:57:28 +00006474 /* Loop through each root page. */
danb40af492019-04-22 20:52:12 +00006475 shellPrepare(pState->db, &rc,
6476 "SELECT root, intkey, max(maxlen) FROM recovery.map"
dan38f9c712019-04-23 18:03:02 +00006477 " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
6478 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
6479 ")", &pLoop
danb40af492019-04-22 20:52:12 +00006480 );
dan68cb86e2019-04-20 20:57:28 +00006481 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6482 int iRoot = sqlite3_column_int(pLoop, 0);
danb40af492019-04-22 20:52:12 +00006483 int bIntkey = sqlite3_column_int(pLoop, 1);
6484 int nCol = sqlite3_column_int(pLoop, 2);
dan68cb86e2019-04-20 20:57:28 +00006485 RecoverTable *pTab;
6486
danb40af492019-04-22 20:52:12 +00006487 pTab = recoverNewTable(pState, &rc, iRoot, bIntkey, nCol);
dan68cb86e2019-04-20 20:57:28 +00006488 if( pTab ){
dan38f9c712019-04-23 18:03:02 +00006489 if( 0==sqlite3_stricmp(pTab->zName, "sqlite_sequence") ){
6490 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
6491 }
danefa363b2019-04-24 20:48:55 +00006492 sqlite3_bind_int(pPages, 1, iRoot);
6493 sqlite3_bind_int(pCells, 2, pTab->iPk);
6494 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
6495 sqlite3_bind_int(pCells, 1, sqlite3_column_int(pPages, 0));
6496 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
6497 int iMax = sqlite3_column_int(pCells, 0);
6498 const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
6499 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
6500 pTab->zQuoted, pTab->azlCol[iMax>0?iMax:0], zVal
6501 );
6502 }
6503 shellReset(&rc, pCells);
dan68cb86e2019-04-20 20:57:28 +00006504 }
danefa363b2019-04-24 20:48:55 +00006505 shellReset(&rc, pPages);
dan68cb86e2019-04-20 20:57:28 +00006506 }
6507 recoverFreeTable(pTab);
6508 }
6509 shellFinalize(&rc, pLoop);
danefa363b2019-04-24 20:48:55 +00006510 shellFinalize(&rc, pPages);
6511 shellFinalize(&rc, pCells);
dan68cb86e2019-04-20 20:57:28 +00006512
dan38f9c712019-04-23 18:03:02 +00006513 /* The rest of the schema */
danb40af492019-04-22 20:52:12 +00006514 if( rc==SQLITE_OK ){
dan38f9c712019-04-23 18:03:02 +00006515 sqlite3_stmt *pStmt = 0;
6516 shellPrepare(pState->db, &rc,
6517 "SELECT sql, name FROM recovery.schema "
danb1825882019-04-23 20:48:32 +00006518 "WHERE sql NOT LIKE 'create table%'", &pStmt
dan38f9c712019-04-23 18:03:02 +00006519 );
6520 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6521 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
6522 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
6523 const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
6524 char *zPrint = shellMPrintf(&rc,
6525 "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)",
6526 zName, zName, zSql
6527 );
6528 raw_printf(pState->out, "%s;\n", zPrint);
6529 sqlite3_free(zPrint);
6530 }else{
6531 raw_printf(pState->out, "%s;\n", zSql);
6532 }
6533 }
6534 shellFinalize(&rc, pStmt);
6535 }
6536
6537 if( rc==SQLITE_OK ){
6538 raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
danb40af492019-04-22 20:52:12 +00006539 raw_printf(pState->out, "COMMIT;\n");
6540 }
dan68cb86e2019-04-20 20:57:28 +00006541 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
6542 return rc;
6543}
6544
drh2ce15c32017-07-11 13:34:40 +00006545
6546/*
6547** If an input line begins with "." then invoke this routine to
6548** process that line.
6549**
6550** Return 1 on error, 2 to exit, and 0 otherwise.
6551*/
6552static int do_meta_command(char *zLine, ShellState *p){
6553 int h = 1;
6554 int nArg = 0;
6555 int n, c;
6556 int rc = 0;
6557 char *azArg[50];
6558
dan6b046be2018-01-09 15:25:55 +00006559#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006560 if( p->expert.pExpert ){
6561 expertFinish(p, 1, 0);
6562 }
dan6b046be2018-01-09 15:25:55 +00006563#endif
dan43efc182017-12-19 17:42:13 +00006564
drh2ce15c32017-07-11 13:34:40 +00006565 /* Parse the input line into tokens.
6566 */
6567 while( zLine[h] && nArg<ArraySize(azArg) ){
6568 while( IsSpace(zLine[h]) ){ h++; }
6569 if( zLine[h]==0 ) break;
6570 if( zLine[h]=='\'' || zLine[h]=='"' ){
6571 int delim = zLine[h++];
6572 azArg[nArg++] = &zLine[h];
6573 while( zLine[h] && zLine[h]!=delim ){
6574 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
6575 h++;
6576 }
6577 if( zLine[h]==delim ){
6578 zLine[h++] = 0;
6579 }
6580 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
6581 }else{
6582 azArg[nArg++] = &zLine[h];
6583 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
6584 if( zLine[h] ) zLine[h++] = 0;
6585 resolve_backslashes(azArg[nArg-1]);
6586 }
6587 }
6588
6589 /* Process the input line.
6590 */
6591 if( nArg==0 ) return 0; /* no tokens, no error */
6592 n = strlen30(azArg[0]);
6593 c = azArg[0][0];
drh13c20932018-01-10 21:41:55 +00006594 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00006595
6596#ifndef SQLITE_OMIT_AUTHORIZATION
6597 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
6598 if( nArg!=2 ){
6599 raw_printf(stderr, "Usage: .auth ON|OFF\n");
6600 rc = 1;
6601 goto meta_command_exit;
6602 }
6603 open_db(p, 0);
6604 if( booleanValue(azArg[1]) ){
6605 sqlite3_set_authorizer(p->db, shellAuth, p);
6606 }else{
6607 sqlite3_set_authorizer(p->db, 0, 0);
6608 }
6609 }else
6610#endif
6611
drhe37c0e12018-01-06 19:19:50 +00006612#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6613 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00006614 open_db(p, 0);
drhd0f9cdc2018-05-17 14:09:06 +00006615 rc = arDotCommand(p, 0, azArg, nArg);
danfd0245d2017-12-07 15:44:29 +00006616 }else
6617#endif
6618
drh2ce15c32017-07-11 13:34:40 +00006619 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
6620 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
6621 ){
6622 const char *zDestFile = 0;
6623 const char *zDb = 0;
6624 sqlite3 *pDest;
6625 sqlite3_backup *pBackup;
6626 int j;
drha50bffb2018-12-08 01:09:14 +00006627 int bAsync = 0;
drh69ed38a2018-05-14 00:23:08 +00006628 const char *zVfs = 0;
drh2ce15c32017-07-11 13:34:40 +00006629 for(j=1; j<nArg; j++){
6630 const char *z = azArg[j];
6631 if( z[0]=='-' ){
drh69ed38a2018-05-14 00:23:08 +00006632 if( z[1]=='-' ) z++;
6633 if( strcmp(z, "-append")==0 ){
6634 zVfs = "apndvfs";
6635 }else
drha50bffb2018-12-08 01:09:14 +00006636 if( strcmp(z, "-async")==0 ){
6637 bAsync = 1;
6638 }else
drh2ce15c32017-07-11 13:34:40 +00006639 {
6640 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
6641 return 1;
6642 }
6643 }else if( zDestFile==0 ){
6644 zDestFile = azArg[j];
6645 }else if( zDb==0 ){
6646 zDb = zDestFile;
6647 zDestFile = azArg[j];
6648 }else{
drha50bffb2018-12-08 01:09:14 +00006649 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
drh2ce15c32017-07-11 13:34:40 +00006650 return 1;
6651 }
6652 }
6653 if( zDestFile==0 ){
6654 raw_printf(stderr, "missing FILENAME argument on .backup\n");
6655 return 1;
6656 }
6657 if( zDb==0 ) zDb = "main";
drh69ed38a2018-05-14 00:23:08 +00006658 rc = sqlite3_open_v2(zDestFile, &pDest,
6659 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
drh2ce15c32017-07-11 13:34:40 +00006660 if( rc!=SQLITE_OK ){
6661 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9e804032018-05-18 17:11:50 +00006662 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006663 return 1;
6664 }
drha50bffb2018-12-08 01:09:14 +00006665 if( bAsync ){
6666 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
6667 0, 0, 0);
6668 }
drh2ce15c32017-07-11 13:34:40 +00006669 open_db(p, 0);
6670 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
6671 if( pBackup==0 ){
6672 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9e804032018-05-18 17:11:50 +00006673 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006674 return 1;
6675 }
6676 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
6677 sqlite3_backup_finish(pBackup);
6678 if( rc==SQLITE_DONE ){
6679 rc = 0;
6680 }else{
6681 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
6682 rc = 1;
6683 }
drh9e804032018-05-18 17:11:50 +00006684 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006685 }else
6686
6687 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
6688 if( nArg==2 ){
6689 bail_on_error = booleanValue(azArg[1]);
6690 }else{
6691 raw_printf(stderr, "Usage: .bail on|off\n");
6692 rc = 1;
6693 }
6694 }else
6695
6696 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
6697 if( nArg==2 ){
6698 if( booleanValue(azArg[1]) ){
6699 setBinaryMode(p->out, 1);
6700 }else{
6701 setTextMode(p->out, 1);
6702 }
6703 }else{
6704 raw_printf(stderr, "Usage: .binary on|off\n");
6705 rc = 1;
6706 }
6707 }else
6708
6709 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
6710 if( nArg==2 ){
6711#if defined(_WIN32) || defined(WIN32)
6712 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
6713 rc = !SetCurrentDirectoryW(z);
6714 sqlite3_free(z);
6715#else
6716 rc = chdir(azArg[1]);
6717#endif
6718 if( rc ){
6719 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
6720 rc = 1;
6721 }
6722 }else{
6723 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
6724 rc = 1;
6725 }
6726 }else
6727
6728 /* The undocumented ".breakpoint" command causes a call to the no-op
6729 ** routine named test_breakpoint().
6730 */
6731 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
6732 test_breakpoint();
6733 }else
6734
6735 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
6736 if( nArg==2 ){
6737 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
6738 }else{
6739 raw_printf(stderr, "Usage: .changes on|off\n");
6740 rc = 1;
6741 }
6742 }else
6743
6744 /* Cancel output redirection, if it is currently set (by .testcase)
6745 ** Then read the content of the testcase-out.txt file and compare against
6746 ** azArg[1]. If there are differences, report an error and exit.
6747 */
6748 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
6749 char *zRes = 0;
6750 output_reset(p);
6751 if( nArg!=2 ){
6752 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
6753 rc = 2;
6754 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
6755 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
6756 rc = 2;
6757 }else if( testcase_glob(azArg[1],zRes)==0 ){
6758 utf8_printf(stderr,
6759 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
6760 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00006761 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00006762 }else{
6763 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
6764 p->nCheck++;
6765 }
6766 sqlite3_free(zRes);
6767 }else
6768
6769 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
6770 if( nArg==2 ){
6771 tryToClone(p, azArg[1]);
6772 }else{
6773 raw_printf(stderr, "Usage: .clone FILENAME\n");
6774 rc = 1;
6775 }
6776 }else
6777
6778 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
6779 ShellState data;
6780 char *zErrMsg = 0;
6781 open_db(p, 0);
6782 memcpy(&data, p, sizeof(data));
6783 data.showHeader = 0;
6784 data.cMode = data.mode = MODE_List;
6785 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
6786 data.cnt = 0;
6787 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
6788 callback, &data, &zErrMsg);
6789 if( zErrMsg ){
6790 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6791 sqlite3_free(zErrMsg);
6792 rc = 1;
6793 }
6794 }else
6795
drh7df01192018-04-28 12:43:16 +00006796 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
drheb7f2a02018-09-26 18:02:32 +00006797 static const struct DbConfigChoices {
6798 const char *zName;
6799 int op;
6800 } aDbConfig[] = {
drh7df01192018-04-28 12:43:16 +00006801 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
6802 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
6803 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
6804 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
6805 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
6806 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
6807 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
6808 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
drha296cda2018-11-03 16:09:59 +00006809 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
drh7df01192018-04-28 12:43:16 +00006810 };
6811 int ii, v;
6812 open_db(p, 0);
6813 for(ii=0; ii<ArraySize(aDbConfig); ii++){
6814 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
6815 if( nArg>=3 ){
6816 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
6817 }
6818 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
6819 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
6820 if( nArg>1 ) break;
6821 }
6822 if( nArg>1 && ii==ArraySize(aDbConfig) ){
6823 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
6824 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
6825 }
6826 }else
6827
6828 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00006829 rc = shell_dbinfo_command(p, nArg, azArg);
6830 }else
6831
dan68cb86e2019-04-20 20:57:28 +00006832 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
6833 open_db(p, 0);
6834 rc = recoverDatabaseCmd(p);
6835 }else
6836
drh2ce15c32017-07-11 13:34:40 +00006837 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
6838 const char *zLike = 0;
6839 int i;
6840 int savedShowHeader = p->showHeader;
drhf213b332018-07-05 17:35:46 +00006841 int savedShellFlags = p->shellFlgs;
6842 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
drh2ce15c32017-07-11 13:34:40 +00006843 for(i=1; i<nArg; i++){
6844 if( azArg[i][0]=='-' ){
6845 const char *z = azArg[i]+1;
6846 if( z[0]=='-' ) z++;
6847 if( strcmp(z,"preserve-rowids")==0 ){
6848#ifdef SQLITE_OMIT_VIRTUALTABLE
6849 raw_printf(stderr, "The --preserve-rowids option is not compatible"
6850 " with SQLITE_OMIT_VIRTUALTABLE\n");
6851 rc = 1;
6852 goto meta_command_exit;
6853#else
6854 ShellSetFlag(p, SHFLG_PreserveRowid);
6855#endif
6856 }else
6857 if( strcmp(z,"newlines")==0 ){
6858 ShellSetFlag(p, SHFLG_Newlines);
6859 }else
6860 {
6861 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
6862 rc = 1;
6863 goto meta_command_exit;
6864 }
6865 }else if( zLike ){
6866 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
6867 "?--newlines? ?LIKE-PATTERN?\n");
6868 rc = 1;
6869 goto meta_command_exit;
6870 }else{
6871 zLike = azArg[i];
6872 }
6873 }
dan68cb86e2019-04-20 20:57:28 +00006874
drh2ce15c32017-07-11 13:34:40 +00006875 open_db(p, 0);
dan68cb86e2019-04-20 20:57:28 +00006876
drh2ce15c32017-07-11 13:34:40 +00006877 /* When playing back a "dump", the content might appear in an order
6878 ** which causes immediate foreign key constraints to be violated.
6879 ** So disable foreign-key constraint enforcement to prevent problems. */
6880 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
6881 raw_printf(p->out, "BEGIN TRANSACTION;\n");
6882 p->writableSchema = 0;
6883 p->showHeader = 0;
6884 /* Set writable_schema=ON since doing so forces SQLite to initialize
6885 ** as much of the schema as it can even if the sqlite_master table is
6886 ** corrupt. */
6887 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
6888 p->nErr = 0;
6889 if( zLike==0 ){
6890 run_schema_dump_query(p,
dan68cb86e2019-04-20 20:57:28 +00006891 "SELECT name, type, sql FROM sqlite_master "
6892 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
6893 );
drh2ce15c32017-07-11 13:34:40 +00006894 run_schema_dump_query(p,
dan68cb86e2019-04-20 20:57:28 +00006895 "SELECT name, type, sql FROM sqlite_master "
6896 "WHERE name=='sqlite_sequence'"
6897 );
drh2ce15c32017-07-11 13:34:40 +00006898 run_table_dump_query(p,
dan68cb86e2019-04-20 20:57:28 +00006899 "SELECT sql FROM sqlite_master "
6900 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
6901 );
drh2ce15c32017-07-11 13:34:40 +00006902 }else{
6903 char *zSql;
6904 zSql = sqlite3_mprintf(
dan68cb86e2019-04-20 20:57:28 +00006905 "SELECT name, type, sql FROM sqlite_master "
6906 "WHERE tbl_name LIKE %Q AND type=='table'"
6907 " AND sql NOT NULL", zLike);
drh2ce15c32017-07-11 13:34:40 +00006908 run_schema_dump_query(p,zSql);
6909 sqlite3_free(zSql);
6910 zSql = sqlite3_mprintf(
dan68cb86e2019-04-20 20:57:28 +00006911 "SELECT sql FROM sqlite_master "
6912 "WHERE sql NOT NULL"
6913 " AND type IN ('index','trigger','view')"
6914 " AND tbl_name LIKE %Q", zLike);
drh2ce15c32017-07-11 13:34:40 +00006915 run_table_dump_query(p, zSql, 0);
6916 sqlite3_free(zSql);
6917 }
6918 if( p->writableSchema ){
6919 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
6920 p->writableSchema = 0;
6921 }
6922 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6923 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
dan68cb86e2019-04-20 20:57:28 +00006924 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
drh2ce15c32017-07-11 13:34:40 +00006925 p->showHeader = savedShowHeader;
drhf213b332018-07-05 17:35:46 +00006926 p->shellFlgs = savedShellFlags;
drh2ce15c32017-07-11 13:34:40 +00006927 }else
6928
6929 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
6930 if( nArg==2 ){
6931 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
6932 }else{
6933 raw_printf(stderr, "Usage: .echo on|off\n");
6934 rc = 1;
6935 }
6936 }else
6937
6938 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
6939 if( nArg==2 ){
drhe2ca99c2018-05-02 00:33:43 +00006940 p->autoEQPtest = 0;
drhb4e50392019-01-26 15:40:04 +00006941 if( p->autoEQPtrace ){
6942 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
6943 p->autoEQPtrace = 0;
6944 }
drh2ce15c32017-07-11 13:34:40 +00006945 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00006946 p->autoEQP = AUTOEQP_full;
6947 }else if( strcmp(azArg[1],"trigger")==0 ){
6948 p->autoEQP = AUTOEQP_trigger;
drhb4e50392019-01-26 15:40:04 +00006949#ifdef SQLITE_DEBUG
drhe2ca99c2018-05-02 00:33:43 +00006950 }else if( strcmp(azArg[1],"test")==0 ){
6951 p->autoEQP = AUTOEQP_on;
6952 p->autoEQPtest = 1;
drhb4e50392019-01-26 15:40:04 +00006953 }else if( strcmp(azArg[1],"trace")==0 ){
6954 p->autoEQP = AUTOEQP_full;
6955 p->autoEQPtrace = 1;
6956 open_db(p, 0);
drhc07eee72019-01-27 19:50:56 +00006957 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
drhb4e50392019-01-26 15:40:04 +00006958 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
6959#endif
drh2ce15c32017-07-11 13:34:40 +00006960 }else{
mistachkinb71aa092018-01-23 00:05:18 +00006961 p->autoEQP = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00006962 }
6963 }else{
drhb4e50392019-01-26 15:40:04 +00006964 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00006965 rc = 1;
6966 }
6967 }else
6968
6969 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
6970 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
6971 rc = 2;
6972 }else
6973
6974 /* The ".explain" command is automatic now. It is largely pointless. It
6975 ** retained purely for backwards compatibility */
6976 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
6977 int val = 1;
6978 if( nArg>=2 ){
6979 if( strcmp(azArg[1],"auto")==0 ){
6980 val = 99;
6981 }else{
6982 val = booleanValue(azArg[1]);
6983 }
6984 }
6985 if( val==1 && p->mode!=MODE_Explain ){
6986 p->normalMode = p->mode;
6987 p->mode = MODE_Explain;
6988 p->autoExplain = 0;
6989 }else if( val==0 ){
6990 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6991 p->autoExplain = 0;
6992 }else if( val==99 ){
6993 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6994 p->autoExplain = 1;
6995 }
6996 }else
6997
dan6b046be2018-01-09 15:25:55 +00006998#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006999 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
7000 open_db(p, 0);
7001 expertDotCommand(p, azArg, nArg);
7002 }else
dan6b046be2018-01-09 15:25:55 +00007003#endif
dan43efc182017-12-19 17:42:13 +00007004
drh2ce15c32017-07-11 13:34:40 +00007005 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
7006 ShellState data;
7007 char *zErrMsg = 0;
7008 int doStats = 0;
7009 memcpy(&data, p, sizeof(data));
7010 data.showHeader = 0;
7011 data.cMode = data.mode = MODE_Semi;
7012 if( nArg==2 && optionMatch(azArg[1], "indent") ){
7013 data.cMode = data.mode = MODE_Pretty;
7014 nArg = 1;
7015 }
7016 if( nArg!=1 ){
7017 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
7018 rc = 1;
7019 goto meta_command_exit;
7020 }
7021 open_db(p, 0);
7022 rc = sqlite3_exec(p->db,
7023 "SELECT sql FROM"
7024 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
7025 " FROM sqlite_master UNION ALL"
7026 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
7027 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
7028 "ORDER BY rowid",
7029 callback, &data, &zErrMsg
7030 );
7031 if( rc==SQLITE_OK ){
7032 sqlite3_stmt *pStmt;
7033 rc = sqlite3_prepare_v2(p->db,
7034 "SELECT rowid FROM sqlite_master"
7035 " WHERE name GLOB 'sqlite_stat[134]'",
7036 -1, &pStmt, 0);
7037 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
7038 sqlite3_finalize(pStmt);
7039 }
7040 if( doStats==0 ){
7041 raw_printf(p->out, "/* No STAT tables available */\n");
7042 }else{
7043 raw_printf(p->out, "ANALYZE sqlite_master;\n");
7044 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
7045 callback, &data, &zErrMsg);
7046 data.cMode = data.mode = MODE_Insert;
7047 data.zDestTable = "sqlite_stat1";
drh4c540452018-05-08 23:17:36 +00007048 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007049 data.zDestTable = "sqlite_stat3";
drh4c540452018-05-08 23:17:36 +00007050 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007051 data.zDestTable = "sqlite_stat4";
drh4c540452018-05-08 23:17:36 +00007052 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007053 raw_printf(p->out, "ANALYZE sqlite_master;\n");
7054 }
7055 }else
7056
7057 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
7058 if( nArg==2 ){
7059 p->showHeader = booleanValue(azArg[1]);
7060 }else{
7061 raw_printf(stderr, "Usage: .headers on|off\n");
7062 rc = 1;
7063 }
7064 }else
7065
7066 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
drh98aa2ab2018-09-26 16:53:51 +00007067 if( nArg>=2 ){
drhe93f8262018-10-11 16:53:37 +00007068 n = showHelp(p->out, azArg[1]);
drh98aa2ab2018-09-26 16:53:51 +00007069 if( n==0 ){
7070 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
7071 }
7072 }else{
7073 showHelp(p->out, 0);
7074 }
drh2ce15c32017-07-11 13:34:40 +00007075 }else
7076
7077 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
7078 char *zTable; /* Insert data into this table */
7079 char *zFile; /* Name of file to extra content from */
7080 sqlite3_stmt *pStmt = NULL; /* A statement */
7081 int nCol; /* Number of columns in the table */
7082 int nByte; /* Number of bytes in an SQL string */
7083 int i, j; /* Loop counters */
7084 int needCommit; /* True to COMMIT or ROLLBACK at end */
7085 int nSep; /* Number of bytes in p->colSeparator[] */
7086 char *zSql; /* An SQL statement */
7087 ImportCtx sCtx; /* Reader context */
7088 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
7089 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
7090
7091 if( nArg!=3 ){
7092 raw_printf(stderr, "Usage: .import FILE TABLE\n");
7093 goto meta_command_exit;
7094 }
7095 zFile = azArg[1];
7096 zTable = azArg[2];
7097 seenInterrupt = 0;
7098 memset(&sCtx, 0, sizeof(sCtx));
7099 open_db(p, 0);
7100 nSep = strlen30(p->colSeparator);
7101 if( nSep==0 ){
7102 raw_printf(stderr,
7103 "Error: non-null column separator required for import\n");
7104 return 1;
7105 }
7106 if( nSep>1 ){
7107 raw_printf(stderr, "Error: multi-character column separators not allowed"
7108 " for import\n");
7109 return 1;
7110 }
7111 nSep = strlen30(p->rowSeparator);
7112 if( nSep==0 ){
7113 raw_printf(stderr, "Error: non-null row separator required for import\n");
7114 return 1;
7115 }
7116 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
7117 /* When importing CSV (only), if the row separator is set to the
7118 ** default output row separator, change it to the default input
7119 ** row separator. This avoids having to maintain different input
7120 ** and output row separators. */
7121 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7122 nSep = strlen30(p->rowSeparator);
7123 }
7124 if( nSep>1 ){
7125 raw_printf(stderr, "Error: multi-character row separators not allowed"
7126 " for import\n");
7127 return 1;
7128 }
7129 sCtx.zFile = zFile;
7130 sCtx.nLine = 1;
7131 if( sCtx.zFile[0]=='|' ){
7132#ifdef SQLITE_OMIT_POPEN
7133 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7134 return 1;
7135#else
7136 sCtx.in = popen(sCtx.zFile+1, "r");
7137 sCtx.zFile = "<pipe>";
7138 xCloser = pclose;
7139#endif
7140 }else{
7141 sCtx.in = fopen(sCtx.zFile, "rb");
7142 xCloser = fclose;
7143 }
7144 if( p->mode==MODE_Ascii ){
7145 xRead = ascii_read_one_field;
7146 }else{
7147 xRead = csv_read_one_field;
7148 }
7149 if( sCtx.in==0 ){
7150 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
7151 return 1;
7152 }
7153 sCtx.cColSep = p->colSeparator[0];
7154 sCtx.cRowSep = p->rowSeparator[0];
7155 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
7156 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00007157 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00007158 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007159 }
7160 nByte = strlen30(zSql);
7161 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7162 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
7163 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
7164 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
7165 char cSep = '(';
7166 while( xRead(&sCtx) ){
7167 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
7168 cSep = ',';
7169 if( sCtx.cTerm!=sCtx.cColSep ) break;
7170 }
7171 if( cSep=='(' ){
7172 sqlite3_free(zCreate);
7173 sqlite3_free(sCtx.z);
7174 xCloser(sCtx.in);
7175 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
7176 return 1;
7177 }
7178 zCreate = sqlite3_mprintf("%z\n)", zCreate);
7179 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
7180 sqlite3_free(zCreate);
7181 if( rc ){
7182 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
7183 sqlite3_errmsg(p->db));
7184 sqlite3_free(sCtx.z);
7185 xCloser(sCtx.in);
7186 return 1;
7187 }
7188 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7189 }
7190 sqlite3_free(zSql);
7191 if( rc ){
7192 if (pStmt) sqlite3_finalize(pStmt);
7193 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
7194 xCloser(sCtx.in);
7195 return 1;
7196 }
7197 nCol = sqlite3_column_count(pStmt);
7198 sqlite3_finalize(pStmt);
7199 pStmt = 0;
7200 if( nCol==0 ) return 0; /* no columns, no error */
7201 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
7202 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00007203 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00007204 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007205 }
7206 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
7207 j = strlen30(zSql);
7208 for(i=1; i<nCol; i++){
7209 zSql[j++] = ',';
7210 zSql[j++] = '?';
7211 }
7212 zSql[j++] = ')';
7213 zSql[j] = 0;
7214 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7215 sqlite3_free(zSql);
7216 if( rc ){
7217 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7218 if (pStmt) sqlite3_finalize(pStmt);
7219 xCloser(sCtx.in);
7220 return 1;
7221 }
7222 needCommit = sqlite3_get_autocommit(p->db);
7223 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
7224 do{
7225 int startLine = sCtx.nLine;
7226 for(i=0; i<nCol; i++){
7227 char *z = xRead(&sCtx);
7228 /*
7229 ** Did we reach end-of-file before finding any columns?
7230 ** If so, stop instead of NULL filling the remaining columns.
7231 */
7232 if( z==0 && i==0 ) break;
7233 /*
7234 ** Did we reach end-of-file OR end-of-line before finding any
7235 ** columns in ASCII mode? If so, stop instead of NULL filling
7236 ** the remaining columns.
7237 */
7238 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
7239 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
7240 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
7241 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7242 "filling the rest with NULL\n",
7243 sCtx.zFile, startLine, nCol, i+1);
7244 i += 2;
7245 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
7246 }
7247 }
7248 if( sCtx.cTerm==sCtx.cColSep ){
7249 do{
7250 xRead(&sCtx);
7251 i++;
7252 }while( sCtx.cTerm==sCtx.cColSep );
7253 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7254 "extras ignored\n",
7255 sCtx.zFile, startLine, nCol, i);
7256 }
7257 if( i>=nCol ){
7258 sqlite3_step(pStmt);
7259 rc = sqlite3_reset(pStmt);
7260 if( rc!=SQLITE_OK ){
7261 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
7262 startLine, sqlite3_errmsg(p->db));
7263 }
7264 }
7265 }while( sCtx.cTerm!=EOF );
7266
7267 xCloser(sCtx.in);
7268 sqlite3_free(sCtx.z);
7269 sqlite3_finalize(pStmt);
7270 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
7271 }else
7272
7273#ifndef SQLITE_UNTESTABLE
7274 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
7275 char *zSql;
7276 char *zCollist = 0;
7277 sqlite3_stmt *pStmt;
7278 int tnum = 0;
7279 int i;
drh48d219a2018-04-23 18:38:48 +00007280 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
7281 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
7282 " .imposter off\n");
drh2ce15c32017-07-11 13:34:40 +00007283 rc = 1;
7284 goto meta_command_exit;
7285 }
7286 open_db(p, 0);
drh48d219a2018-04-23 18:38:48 +00007287 if( nArg==2 ){
7288 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
7289 goto meta_command_exit;
7290 }
drh2ce15c32017-07-11 13:34:40 +00007291 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
7292 " WHERE name='%q' AND type='index'", azArg[1]);
7293 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7294 sqlite3_free(zSql);
7295 if( sqlite3_step(pStmt)==SQLITE_ROW ){
7296 tnum = sqlite3_column_int(pStmt, 0);
7297 }
7298 sqlite3_finalize(pStmt);
7299 if( tnum==0 ){
7300 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
7301 rc = 1;
7302 goto meta_command_exit;
7303 }
7304 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
7305 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7306 sqlite3_free(zSql);
7307 i = 0;
7308 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7309 char zLabel[20];
7310 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
7311 i++;
7312 if( zCol==0 ){
7313 if( sqlite3_column_int(pStmt,1)==-1 ){
7314 zCol = "_ROWID_";
7315 }else{
7316 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
7317 zCol = zLabel;
7318 }
7319 }
7320 if( zCollist==0 ){
7321 zCollist = sqlite3_mprintf("\"%w\"", zCol);
7322 }else{
7323 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
7324 }
7325 }
7326 sqlite3_finalize(pStmt);
7327 zSql = sqlite3_mprintf(
7328 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
7329 azArg[2], zCollist, zCollist);
7330 sqlite3_free(zCollist);
7331 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
7332 if( rc==SQLITE_OK ){
7333 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
7334 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
7335 if( rc ){
7336 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
7337 }else{
7338 utf8_printf(stdout, "%s;\n", zSql);
7339 raw_printf(stdout,
7340 "WARNING: writing to an imposter table will corrupt the index!\n"
7341 );
7342 }
7343 }else{
7344 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
7345 rc = 1;
7346 }
7347 sqlite3_free(zSql);
7348 }else
7349#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
7350
7351#ifdef SQLITE_ENABLE_IOTRACE
7352 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
7353 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
7354 if( iotrace && iotrace!=stdout ) fclose(iotrace);
7355 iotrace = 0;
7356 if( nArg<2 ){
7357 sqlite3IoTrace = 0;
7358 }else if( strcmp(azArg[1], "-")==0 ){
7359 sqlite3IoTrace = iotracePrintf;
7360 iotrace = stdout;
7361 }else{
7362 iotrace = fopen(azArg[1], "w");
7363 if( iotrace==0 ){
7364 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
7365 sqlite3IoTrace = 0;
7366 rc = 1;
7367 }else{
7368 sqlite3IoTrace = iotracePrintf;
7369 }
7370 }
7371 }else
7372#endif
7373
7374 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
7375 static const struct {
7376 const char *zLimitName; /* Name of a limit */
7377 int limitCode; /* Integer code for that limit */
7378 } aLimit[] = {
7379 { "length", SQLITE_LIMIT_LENGTH },
7380 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
7381 { "column", SQLITE_LIMIT_COLUMN },
7382 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
7383 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
7384 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
7385 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
7386 { "attached", SQLITE_LIMIT_ATTACHED },
7387 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
7388 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
7389 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
7390 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
7391 };
7392 int i, n2;
7393 open_db(p, 0);
7394 if( nArg==1 ){
7395 for(i=0; i<ArraySize(aLimit); i++){
7396 printf("%20s %d\n", aLimit[i].zLimitName,
7397 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
7398 }
7399 }else if( nArg>3 ){
7400 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
7401 rc = 1;
7402 goto meta_command_exit;
7403 }else{
7404 int iLimit = -1;
7405 n2 = strlen30(azArg[1]);
7406 for(i=0; i<ArraySize(aLimit); i++){
7407 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
7408 if( iLimit<0 ){
7409 iLimit = i;
7410 }else{
7411 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
7412 rc = 1;
7413 goto meta_command_exit;
7414 }
7415 }
7416 }
7417 if( iLimit<0 ){
7418 utf8_printf(stderr, "unknown limit: \"%s\"\n"
7419 "enter \".limits\" with no arguments for a list.\n",
7420 azArg[1]);
7421 rc = 1;
7422 goto meta_command_exit;
7423 }
7424 if( nArg==3 ){
7425 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
7426 (int)integerValue(azArg[2]));
7427 }
7428 printf("%20s %d\n", aLimit[iLimit].zLimitName,
7429 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
7430 }
7431 }else
7432
7433 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
7434 open_db(p, 0);
7435 lintDotCommand(p, azArg, nArg);
7436 }else
7437
7438#ifndef SQLITE_OMIT_LOAD_EXTENSION
7439 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
7440 const char *zFile, *zProc;
7441 char *zErrMsg = 0;
7442 if( nArg<2 ){
7443 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
7444 rc = 1;
7445 goto meta_command_exit;
7446 }
7447 zFile = azArg[1];
7448 zProc = nArg>=3 ? azArg[2] : 0;
7449 open_db(p, 0);
7450 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
7451 if( rc!=SQLITE_OK ){
7452 utf8_printf(stderr, "Error: %s\n", zErrMsg);
7453 sqlite3_free(zErrMsg);
7454 rc = 1;
7455 }
7456 }else
7457#endif
7458
7459 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
7460 if( nArg!=2 ){
7461 raw_printf(stderr, "Usage: .log FILENAME\n");
7462 rc = 1;
7463 }else{
7464 const char *zFile = azArg[1];
7465 output_file_close(p->pLog);
drha92a01a2018-01-10 22:15:37 +00007466 p->pLog = output_file_open(zFile, 0);
drh2ce15c32017-07-11 13:34:40 +00007467 }
7468 }else
7469
7470 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
7471 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00007472 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00007473 int c2 = zMode[0];
7474 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
7475 p->mode = MODE_Line;
7476 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7477 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
7478 p->mode = MODE_Column;
7479 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7480 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
7481 p->mode = MODE_List;
7482 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
7483 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7484 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
7485 p->mode = MODE_Html;
7486 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
7487 p->mode = MODE_Tcl;
7488 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
7489 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7490 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
7491 p->mode = MODE_Csv;
7492 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
7493 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
7494 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
7495 p->mode = MODE_List;
7496 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
7497 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
7498 p->mode = MODE_Insert;
7499 set_table_name(p, nArg>=3 ? azArg[2] : "table");
7500 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
7501 p->mode = MODE_Quote;
7502 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
7503 p->mode = MODE_Ascii;
7504 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
7505 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
7506 }else if( nArg==1 ){
7507 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
7508 }else{
7509 raw_printf(stderr, "Error: mode should be one of: "
7510 "ascii column csv html insert line list quote tabs tcl\n");
7511 rc = 1;
7512 }
7513 p->cMode = p->mode;
7514 }else
7515
7516 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
7517 if( nArg==2 ){
7518 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
7519 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
7520 }else{
7521 raw_printf(stderr, "Usage: .nullvalue STRING\n");
7522 rc = 1;
7523 }
7524 }else
7525
7526 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
7527 char *zNewFilename; /* Name of the database file to open */
7528 int iName = 1; /* Index in azArg[] of the filename */
7529 int newFlag = 0; /* True to delete file before opening */
7530 /* Close the existing database */
7531 session_close_all(p);
drh9e804032018-05-18 17:11:50 +00007532 close_db(p->db);
drh2ce15c32017-07-11 13:34:40 +00007533 p->db = 0;
7534 p->zDbFilename = 0;
7535 sqlite3_free(p->zFreeOnClose);
7536 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00007537 p->openMode = SHELL_OPEN_UNSPEC;
drh6ca64482019-01-22 16:06:20 +00007538 p->szMax = 0;
drh2ce15c32017-07-11 13:34:40 +00007539 /* Check for command-line arguments */
7540 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
7541 const char *z = azArg[iName];
7542 if( optionMatch(z,"new") ){
7543 newFlag = 1;
drh3baed312018-03-08 18:14:41 +00007544#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00007545 }else if( optionMatch(z, "zip") ){
7546 p->openMode = SHELL_OPEN_ZIPFILE;
7547#endif
7548 }else if( optionMatch(z, "append") ){
7549 p->openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00007550 }else if( optionMatch(z, "readonly") ){
7551 p->openMode = SHELL_OPEN_READONLY;
drha751f392018-10-30 15:31:22 +00007552#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00007553 }else if( optionMatch(z, "deserialize") ){
7554 p->openMode = SHELL_OPEN_DESERIALIZE;
drh33746482018-12-13 15:06:26 +00007555 }else if( optionMatch(z, "hexdb") ){
7556 p->openMode = SHELL_OPEN_HEXDB;
drh6ca64482019-01-22 16:06:20 +00007557 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
7558 p->szMax = integerValue(azArg[++iName]);
drh33746482018-12-13 15:06:26 +00007559#endif /* SQLITE_ENABLE_DESERIALIZE */
drh2ce15c32017-07-11 13:34:40 +00007560 }else if( z[0]=='-' ){
7561 utf8_printf(stderr, "unknown option: %s\n", z);
7562 rc = 1;
7563 goto meta_command_exit;
7564 }
7565 }
7566 /* If a filename is specified, try to open it first */
7567 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
drh33746482018-12-13 15:06:26 +00007568 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
drh2ce15c32017-07-11 13:34:40 +00007569 if( newFlag ) shellDeleteFile(zNewFilename);
7570 p->zDbFilename = zNewFilename;
drhbe4ccb22018-05-17 20:04:24 +00007571 open_db(p, OPEN_DB_KEEPALIVE);
drh2ce15c32017-07-11 13:34:40 +00007572 if( p->db==0 ){
7573 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
7574 sqlite3_free(zNewFilename);
7575 }else{
7576 p->zFreeOnClose = zNewFilename;
7577 }
7578 }
7579 if( p->db==0 ){
7580 /* As a fall-back open a TEMP database */
7581 p->zDbFilename = 0;
7582 open_db(p, 0);
7583 }
7584 }else
7585
drh13c20932018-01-10 21:41:55 +00007586 if( (c=='o'
7587 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
7588 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
drh2ce15c32017-07-11 13:34:40 +00007589 ){
7590 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
drha92a01a2018-01-10 22:15:37 +00007591 int bTxtMode = 0;
drh13c20932018-01-10 21:41:55 +00007592 if( azArg[0][0]=='e' ){
7593 /* Transform the ".excel" command into ".once -x" */
7594 nArg = 2;
7595 azArg[0] = "once";
7596 zFile = azArg[1] = "-x";
7597 n = 4;
7598 }
drh2ce15c32017-07-11 13:34:40 +00007599 if( nArg>2 ){
drh13c20932018-01-10 21:41:55 +00007600 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00007601 rc = 1;
7602 goto meta_command_exit;
7603 }
7604 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
7605 if( nArg<2 ){
drh13c20932018-01-10 21:41:55 +00007606 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
drh2ce15c32017-07-11 13:34:40 +00007607 rc = 1;
7608 goto meta_command_exit;
7609 }
7610 p->outCount = 2;
7611 }else{
7612 p->outCount = 0;
7613 }
7614 output_reset(p);
drh13c20932018-01-10 21:41:55 +00007615 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
drh04a28c32018-01-31 01:38:44 +00007616#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00007617 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
drh3c484e82018-01-10 22:27:21 +00007618 p->doXdgOpen = 1;
7619 outputModePush(p);
drh13c20932018-01-10 21:41:55 +00007620 if( zFile[1]=='x' ){
7621 newTempFile(p, "csv");
7622 p->mode = MODE_Csv;
7623 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
7624 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
7625 }else{
7626 newTempFile(p, "txt");
drha92a01a2018-01-10 22:15:37 +00007627 bTxtMode = 1;
drh13c20932018-01-10 21:41:55 +00007628 }
7629 zFile = p->zTempFile;
7630 }
drh04a28c32018-01-31 01:38:44 +00007631#endif /* SQLITE_NOHAVE_SYSTEM */
drh2ce15c32017-07-11 13:34:40 +00007632 if( zFile[0]=='|' ){
7633#ifdef SQLITE_OMIT_POPEN
7634 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7635 rc = 1;
7636 p->out = stdout;
7637#else
7638 p->out = popen(zFile + 1, "w");
7639 if( p->out==0 ){
7640 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
7641 p->out = stdout;
7642 rc = 1;
7643 }else{
7644 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7645 }
7646#endif
7647 }else{
drha92a01a2018-01-10 22:15:37 +00007648 p->out = output_file_open(zFile, bTxtMode);
drh2ce15c32017-07-11 13:34:40 +00007649 if( p->out==0 ){
7650 if( strcmp(zFile,"off")!=0 ){
7651 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
7652 }
7653 p->out = stdout;
7654 rc = 1;
7655 } else {
7656 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7657 }
7658 }
7659 }else
7660
drh9cb02642019-02-28 20:10:52 +00007661 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
7662 open_db(p,0);
7663 if( nArg<=1 ) goto parameter_syntax_error;
7664
7665 /* .parameter clear
7666 ** Clear all bind parameters by dropping the TEMP table that holds them.
7667 */
7668 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
drh346f4e22019-03-25 21:35:41 +00007669 int wrSchema = 0;
7670 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
7671 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
drh65c29fd2019-03-25 21:56:26 +00007672 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
drh9cb02642019-02-28 20:10:52 +00007673 0, 0, 0);
drh346f4e22019-03-25 21:35:41 +00007674 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
drh9cb02642019-02-28 20:10:52 +00007675 }else
7676
7677 /* .parameter list
7678 ** List all bind parameters.
7679 */
7680 if( nArg==2 && strcmp(azArg[1],"list")==0 ){
7681 sqlite3_stmt *pStmt = 0;
7682 int rx;
7683 int len = 0;
7684 rx = sqlite3_prepare_v2(p->db,
7685 "SELECT max(length(key)) "
drh65c29fd2019-03-25 21:56:26 +00007686 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
drh9cb02642019-02-28 20:10:52 +00007687 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
7688 len = sqlite3_column_int(pStmt, 0);
7689 if( len>40 ) len = 40;
7690 }
7691 sqlite3_finalize(pStmt);
7692 pStmt = 0;
7693 if( len ){
7694 rx = sqlite3_prepare_v2(p->db,
7695 "SELECT key, quote(value) "
drh65c29fd2019-03-25 21:56:26 +00007696 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
drh9cb02642019-02-28 20:10:52 +00007697 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7698 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
7699 sqlite3_column_text(pStmt,1));
7700 }
7701 sqlite3_finalize(pStmt);
7702 }
7703 }else
7704
7705 /* .parameter init
7706 ** Make sure the TEMP table used to hold bind parameters exists.
7707 ** Create it if necessary.
7708 */
7709 if( nArg==2 && strcmp(azArg[1],"init")==0 ){
7710 bind_table_init(p);
7711 }else
7712
7713 /* .parameter set NAME VALUE
7714 ** Set or reset a bind parameter. NAME should be the full parameter
7715 ** name exactly as it appears in the query. (ex: $abc, @def). The
7716 ** VALUE can be in either SQL literal notation, or if not it will be
7717 ** understood to be a text string.
7718 */
7719 if( nArg==4 && strcmp(azArg[1],"set")==0 ){
7720 int rx;
7721 char *zSql;
7722 sqlite3_stmt *pStmt;
7723 const char *zKey = azArg[2];
7724 const char *zValue = azArg[3];
7725 bind_table_init(p);
7726 zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007727 "REPLACE INTO temp.sqlite_parameters(key,value)"
drh9cb02642019-02-28 20:10:52 +00007728 "VALUES(%Q,%s);", zKey, zValue);
7729 if( zSql==0 ) shell_out_of_memory();
7730 pStmt = 0;
7731 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7732 sqlite3_free(zSql);
7733 if( rx!=SQLITE_OK ){
7734 sqlite3_finalize(pStmt);
7735 pStmt = 0;
7736 zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007737 "REPLACE INTO temp.sqlite_parameters(key,value)"
drh9cb02642019-02-28 20:10:52 +00007738 "VALUES(%Q,%Q);", zKey, zValue);
7739 if( zSql==0 ) shell_out_of_memory();
7740 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7741 sqlite3_free(zSql);
7742 if( rx!=SQLITE_OK ){
7743 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
7744 sqlite3_finalize(pStmt);
7745 pStmt = 0;
7746 rc = 1;
7747 }
7748 }
7749 sqlite3_step(pStmt);
7750 sqlite3_finalize(pStmt);
7751 }else
7752
7753 /* .parameter unset NAME
7754 ** Remove the NAME binding from the parameter binding table, if it
7755 ** exists.
7756 */
7757 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
7758 char *zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007759 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
drh9cb02642019-02-28 20:10:52 +00007760 if( zSql==0 ) shell_out_of_memory();
7761 sqlite3_exec(p->db, zSql, 0, 0, 0);
7762 sqlite3_free(zSql);
7763 }else
7764 /* If no command name matches, show a syntax error */
7765 parameter_syntax_error:
7766 showHelp(p->out, "parameter");
7767 }else
7768
drh2ce15c32017-07-11 13:34:40 +00007769 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
7770 int i;
7771 for(i=1; i<nArg; i++){
7772 if( i>1 ) raw_printf(p->out, " ");
7773 utf8_printf(p->out, "%s", azArg[i]);
7774 }
7775 raw_printf(p->out, "\n");
7776 }else
7777
drh569b1d92019-02-05 20:51:41 +00007778#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00007779 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
7780 int i;
drhfc4eeef2019-02-05 19:48:46 +00007781 int nn = 0;
drh3f83f592019-02-04 14:53:18 +00007782 p->flgProgress = 0;
7783 p->mxProgress = 0;
7784 p->nProgress = 0;
7785 for(i=1; i<nArg; i++){
7786 const char *z = azArg[i];
7787 if( z[0]=='-' ){
7788 z++;
7789 if( z[0]=='-' ) z++;
7790 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007791 p->flgProgress |= SHELL_PROGRESS_QUIET;
drh3f83f592019-02-04 14:53:18 +00007792 continue;
7793 }
7794 if( strcmp(z,"reset")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007795 p->flgProgress |= SHELL_PROGRESS_RESET;
drh3f83f592019-02-04 14:53:18 +00007796 continue;
7797 }
7798 if( strcmp(z,"once")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007799 p->flgProgress |= SHELL_PROGRESS_ONCE;
drh3f83f592019-02-04 14:53:18 +00007800 continue;
7801 }
7802 if( strcmp(z,"limit")==0 ){
7803 if( i+1>=nArg ){
7804 utf8_printf(stderr, "Error: missing argument on --limit\n");
7805 rc = 1;
7806 goto meta_command_exit;
7807 }else{
7808 p->mxProgress = (int)integerValue(azArg[++i]);
7809 }
7810 continue;
7811 }
7812 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
7813 rc = 1;
7814 goto meta_command_exit;
7815 }else{
drhfc4eeef2019-02-05 19:48:46 +00007816 nn = (int)integerValue(z);
drh3f83f592019-02-04 14:53:18 +00007817 }
7818 }
7819 open_db(p, 0);
drhfc4eeef2019-02-05 19:48:46 +00007820 sqlite3_progress_handler(p->db, nn, progress_handler, p);
drh3f83f592019-02-04 14:53:18 +00007821 }else
drh569b1d92019-02-05 20:51:41 +00007822#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00007823
drh2ce15c32017-07-11 13:34:40 +00007824 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
7825 if( nArg >= 2) {
7826 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
7827 }
7828 if( nArg >= 3) {
7829 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
7830 }
7831 }else
7832
7833 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
7834 rc = 2;
7835 }else
7836
7837 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
drh60379d42018-12-13 18:30:01 +00007838 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00007839 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00007840 if( nArg!=2 ){
7841 raw_printf(stderr, "Usage: .read FILE\n");
7842 rc = 1;
7843 goto meta_command_exit;
7844 }
drh60379d42018-12-13 18:30:01 +00007845 p->in = fopen(azArg[1], "rb");
7846 if( p->in==0 ){
drh2ce15c32017-07-11 13:34:40 +00007847 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
7848 rc = 1;
7849 }else{
drh60379d42018-12-13 18:30:01 +00007850 rc = process_input(p);
7851 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00007852 }
drh60379d42018-12-13 18:30:01 +00007853 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00007854 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00007855 }else
7856
7857 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
7858 const char *zSrcFile;
7859 const char *zDb;
7860 sqlite3 *pSrc;
7861 sqlite3_backup *pBackup;
7862 int nTimeout = 0;
7863
7864 if( nArg==2 ){
7865 zSrcFile = azArg[1];
7866 zDb = "main";
7867 }else if( nArg==3 ){
7868 zSrcFile = azArg[2];
7869 zDb = azArg[1];
7870 }else{
7871 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
7872 rc = 1;
7873 goto meta_command_exit;
7874 }
7875 rc = sqlite3_open(zSrcFile, &pSrc);
7876 if( rc!=SQLITE_OK ){
7877 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9e804032018-05-18 17:11:50 +00007878 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00007879 return 1;
7880 }
7881 open_db(p, 0);
7882 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
7883 if( pBackup==0 ){
7884 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9e804032018-05-18 17:11:50 +00007885 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00007886 return 1;
7887 }
7888 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
7889 || rc==SQLITE_BUSY ){
7890 if( rc==SQLITE_BUSY ){
7891 if( nTimeout++ >= 3 ) break;
7892 sqlite3_sleep(100);
7893 }
7894 }
7895 sqlite3_backup_finish(pBackup);
7896 if( rc==SQLITE_DONE ){
7897 rc = 0;
7898 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
7899 raw_printf(stderr, "Error: source database is busy\n");
7900 rc = 1;
7901 }else{
7902 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7903 rc = 1;
7904 }
drh9e804032018-05-18 17:11:50 +00007905 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00007906 }else
7907
drh2ce15c32017-07-11 13:34:40 +00007908 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
7909 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00007910 p->scanstatsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007911#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
7912 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
7913#endif
7914 }else{
7915 raw_printf(stderr, "Usage: .scanstats on|off\n");
7916 rc = 1;
7917 }
7918 }else
7919
7920 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
7921 ShellText sSelect;
7922 ShellState data;
7923 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00007924 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00007925 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00007926 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00007927 int bDebug = 0;
7928 int ii;
drh2ce15c32017-07-11 13:34:40 +00007929
7930 open_db(p, 0);
7931 memcpy(&data, p, sizeof(data));
7932 data.showHeader = 0;
7933 data.cMode = data.mode = MODE_Semi;
7934 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00007935 for(ii=1; ii<nArg; ii++){
7936 if( optionMatch(azArg[ii],"indent") ){
7937 data.cMode = data.mode = MODE_Pretty;
7938 }else if( optionMatch(azArg[ii],"debug") ){
7939 bDebug = 1;
7940 }else if( zName==0 ){
7941 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00007942 }else{
drhceba7922018-01-01 21:28:25 +00007943 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
7944 rc = 1;
7945 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00007946 }
drh2ce15c32017-07-11 13:34:40 +00007947 }
drhceba7922018-01-01 21:28:25 +00007948 if( zName!=0 ){
mistachkin9d107262018-03-23 14:24:34 +00007949 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
7950 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
drh2ce15c32017-07-11 13:34:40 +00007951 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00007952 new_argv[0] = sqlite3_mprintf(
7953 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00007954 " type text,\n"
7955 " name text,\n"
7956 " tbl_name text,\n"
7957 " rootpage integer,\n"
7958 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00007959 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00007960 new_argv[1] = 0;
7961 new_colv[0] = "sql";
7962 new_colv[1] = 0;
7963 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00007964 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00007965 }
drh2ce15c32017-07-11 13:34:40 +00007966 }
7967 if( zDiv ){
7968 sqlite3_stmt *pStmt = 0;
7969 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
7970 -1, &pStmt, 0);
7971 if( rc ){
7972 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7973 sqlite3_finalize(pStmt);
7974 rc = 1;
7975 goto meta_command_exit;
7976 }
7977 appendText(&sSelect, "SELECT sql FROM", 0);
7978 iSchema = 0;
7979 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7980 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
7981 char zScNum[30];
7982 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
7983 appendText(&sSelect, zDiv, 0);
7984 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00007985 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
7986 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00007987 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00007988 }else{
drhceba7922018-01-01 21:28:25 +00007989 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00007990 }
drhceba7922018-01-01 21:28:25 +00007991 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
7992 appendText(&sSelect, zScNum, 0);
7993 appendText(&sSelect, " AS snum, ", 0);
7994 appendText(&sSelect, zDb, '\'');
7995 appendText(&sSelect, " AS sname FROM ", 0);
7996 appendText(&sSelect, zDb, '"');
7997 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00007998 }
7999 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00008000#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00008001 if( zName ){
8002 appendText(&sSelect,
8003 " UNION ALL SELECT shell_module_schema(name),"
8004 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
8005 }
drhcde7b772018-01-02 12:50:40 +00008006#endif
drh2ce15c32017-07-11 13:34:40 +00008007 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00008008 if( zName ){
8009 char *zQarg = sqlite3_mprintf("%Q", zName);
mistachkin9d107262018-03-23 14:24:34 +00008010 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
8011 strchr(zName, '[') != 0;
drhceba7922018-01-01 21:28:25 +00008012 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00008013 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
8014 }else{
8015 appendText(&sSelect, "lower(tbl_name)", 0);
8016 }
mistachkin9d107262018-03-23 14:24:34 +00008017 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00008018 appendText(&sSelect, zQarg, 0);
mistachkin9d107262018-03-23 14:24:34 +00008019 if( !bGlob ){
8020 appendText(&sSelect, " ESCAPE '\\' ", 0);
8021 }
drh2ce15c32017-07-11 13:34:40 +00008022 appendText(&sSelect, " AND ", 0);
8023 sqlite3_free(zQarg);
8024 }
8025 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
8026 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00008027 if( bDebug ){
8028 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
8029 }else{
8030 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
8031 }
drh2ce15c32017-07-11 13:34:40 +00008032 freeText(&sSelect);
8033 }
8034 if( zErrMsg ){
8035 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8036 sqlite3_free(zErrMsg);
8037 rc = 1;
8038 }else if( rc != SQLITE_OK ){
8039 raw_printf(stderr,"Error: querying schema information\n");
8040 rc = 1;
8041 }else{
8042 rc = 0;
8043 }
8044 }else
8045
8046#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
8047 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
8048 sqlite3SelectTrace = (int)integerValue(azArg[1]);
8049 }else
8050#endif
8051
8052#if defined(SQLITE_ENABLE_SESSION)
8053 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
8054 OpenSession *pSession = &p->aSession[0];
8055 char **azCmd = &azArg[1];
8056 int iSes = 0;
8057 int nCmd = nArg - 1;
8058 int i;
8059 if( nArg<=1 ) goto session_syntax_error;
8060 open_db(p, 0);
8061 if( nArg>=3 ){
8062 for(iSes=0; iSes<p->nSession; iSes++){
8063 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
8064 }
8065 if( iSes<p->nSession ){
8066 pSession = &p->aSession[iSes];
8067 azCmd++;
8068 nCmd--;
8069 }else{
8070 pSession = &p->aSession[0];
8071 iSes = 0;
8072 }
8073 }
8074
8075 /* .session attach TABLE
8076 ** Invoke the sqlite3session_attach() interface to attach a particular
8077 ** table so that it is never filtered.
8078 */
8079 if( strcmp(azCmd[0],"attach")==0 ){
8080 if( nCmd!=2 ) goto session_syntax_error;
8081 if( pSession->p==0 ){
8082 session_not_open:
8083 raw_printf(stderr, "ERROR: No sessions are open\n");
8084 }else{
8085 rc = sqlite3session_attach(pSession->p, azCmd[1]);
8086 if( rc ){
8087 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
8088 rc = 0;
8089 }
8090 }
8091 }else
8092
8093 /* .session changeset FILE
8094 ** .session patchset FILE
8095 ** Write a changeset or patchset into a file. The file is overwritten.
8096 */
8097 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
8098 FILE *out = 0;
8099 if( nCmd!=2 ) goto session_syntax_error;
8100 if( pSession->p==0 ) goto session_not_open;
8101 out = fopen(azCmd[1], "wb");
8102 if( out==0 ){
8103 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
8104 }else{
8105 int szChng;
8106 void *pChng;
8107 if( azCmd[0][0]=='c' ){
8108 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
8109 }else{
8110 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
8111 }
8112 if( rc ){
8113 printf("Error: error code %d\n", rc);
8114 rc = 0;
8115 }
8116 if( pChng
8117 && fwrite(pChng, szChng, 1, out)!=1 ){
8118 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
8119 szChng);
8120 }
8121 sqlite3_free(pChng);
8122 fclose(out);
8123 }
8124 }else
8125
8126 /* .session close
8127 ** Close the identified session
8128 */
8129 if( strcmp(azCmd[0], "close")==0 ){
8130 if( nCmd!=1 ) goto session_syntax_error;
8131 if( p->nSession ){
8132 session_close(pSession);
8133 p->aSession[iSes] = p->aSession[--p->nSession];
8134 }
8135 }else
8136
8137 /* .session enable ?BOOLEAN?
8138 ** Query or set the enable flag
8139 */
8140 if( strcmp(azCmd[0], "enable")==0 ){
8141 int ii;
8142 if( nCmd>2 ) goto session_syntax_error;
8143 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8144 if( p->nSession ){
8145 ii = sqlite3session_enable(pSession->p, ii);
8146 utf8_printf(p->out, "session %s enable flag = %d\n",
8147 pSession->zName, ii);
8148 }
8149 }else
8150
8151 /* .session filter GLOB ....
8152 ** Set a list of GLOB patterns of table names to be excluded.
8153 */
8154 if( strcmp(azCmd[0], "filter")==0 ){
8155 int ii, nByte;
8156 if( nCmd<2 ) goto session_syntax_error;
8157 if( p->nSession ){
8158 for(ii=0; ii<pSession->nFilter; ii++){
8159 sqlite3_free(pSession->azFilter[ii]);
8160 }
8161 sqlite3_free(pSession->azFilter);
8162 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
8163 pSession->azFilter = sqlite3_malloc( nByte );
8164 if( pSession->azFilter==0 ){
8165 raw_printf(stderr, "Error: out or memory\n");
8166 exit(1);
8167 }
8168 for(ii=1; ii<nCmd; ii++){
8169 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
8170 }
8171 pSession->nFilter = ii-1;
8172 }
8173 }else
8174
8175 /* .session indirect ?BOOLEAN?
8176 ** Query or set the indirect flag
8177 */
8178 if( strcmp(azCmd[0], "indirect")==0 ){
8179 int ii;
8180 if( nCmd>2 ) goto session_syntax_error;
8181 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8182 if( p->nSession ){
8183 ii = sqlite3session_indirect(pSession->p, ii);
8184 utf8_printf(p->out, "session %s indirect flag = %d\n",
8185 pSession->zName, ii);
8186 }
8187 }else
8188
8189 /* .session isempty
8190 ** Determine if the session is empty
8191 */
8192 if( strcmp(azCmd[0], "isempty")==0 ){
8193 int ii;
8194 if( nCmd!=1 ) goto session_syntax_error;
8195 if( p->nSession ){
8196 ii = sqlite3session_isempty(pSession->p);
8197 utf8_printf(p->out, "session %s isempty flag = %d\n",
8198 pSession->zName, ii);
8199 }
8200 }else
8201
8202 /* .session list
8203 ** List all currently open sessions
8204 */
8205 if( strcmp(azCmd[0],"list")==0 ){
8206 for(i=0; i<p->nSession; i++){
8207 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
8208 }
8209 }else
8210
8211 /* .session open DB NAME
8212 ** Open a new session called NAME on the attached database DB.
8213 ** DB is normally "main".
8214 */
8215 if( strcmp(azCmd[0],"open")==0 ){
8216 char *zName;
8217 if( nCmd!=3 ) goto session_syntax_error;
8218 zName = azCmd[2];
8219 if( zName[0]==0 ) goto session_syntax_error;
8220 for(i=0; i<p->nSession; i++){
8221 if( strcmp(p->aSession[i].zName,zName)==0 ){
8222 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
8223 goto meta_command_exit;
8224 }
8225 }
8226 if( p->nSession>=ArraySize(p->aSession) ){
8227 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
8228 goto meta_command_exit;
8229 }
8230 pSession = &p->aSession[p->nSession];
8231 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
8232 if( rc ){
8233 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
8234 rc = 0;
8235 goto meta_command_exit;
8236 }
8237 pSession->nFilter = 0;
8238 sqlite3session_table_filter(pSession->p, session_filter, pSession);
8239 p->nSession++;
8240 pSession->zName = sqlite3_mprintf("%s", zName);
8241 }else
8242 /* If no command name matches, show a syntax error */
8243 session_syntax_error:
drheb7f2a02018-09-26 18:02:32 +00008244 showHelp(p->out, "session");
drh2ce15c32017-07-11 13:34:40 +00008245 }else
8246#endif
8247
8248#ifdef SQLITE_DEBUG
8249 /* Undocumented commands for internal testing. Subject to change
8250 ** without notice. */
8251 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
8252 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
8253 int i, v;
8254 for(i=1; i<nArg; i++){
8255 v = booleanValue(azArg[i]);
8256 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
8257 }
8258 }
8259 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
8260 int i; sqlite3_int64 v;
8261 for(i=1; i<nArg; i++){
8262 char zBuf[200];
8263 v = integerValue(azArg[i]);
8264 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
8265 utf8_printf(p->out, "%s", zBuf);
8266 }
8267 }
8268 }else
8269#endif
8270
8271 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
8272 int bIsInit = 0; /* True to initialize the SELFTEST table */
8273 int bVerbose = 0; /* Verbose output */
8274 int bSelftestExists; /* True if SELFTEST already exists */
8275 int i, k; /* Loop counters */
8276 int nTest = 0; /* Number of tests runs */
8277 int nErr = 0; /* Number of errors seen */
8278 ShellText str; /* Answer for a query */
8279 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
8280
8281 open_db(p,0);
8282 for(i=1; i<nArg; i++){
8283 const char *z = azArg[i];
8284 if( z[0]=='-' && z[1]=='-' ) z++;
8285 if( strcmp(z,"-init")==0 ){
8286 bIsInit = 1;
8287 }else
8288 if( strcmp(z,"-v")==0 ){
8289 bVerbose++;
8290 }else
8291 {
8292 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8293 azArg[i], azArg[0]);
8294 raw_printf(stderr, "Should be one of: --init -v\n");
8295 rc = 1;
8296 goto meta_command_exit;
8297 }
8298 }
8299 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
8300 != SQLITE_OK ){
8301 bSelftestExists = 0;
8302 }else{
8303 bSelftestExists = 1;
8304 }
8305 if( bIsInit ){
8306 createSelftestTable(p);
8307 bSelftestExists = 1;
8308 }
8309 initText(&str);
8310 appendText(&str, "x", 0);
8311 for(k=bSelftestExists; k>=0; k--){
8312 if( k==1 ){
8313 rc = sqlite3_prepare_v2(p->db,
8314 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
8315 -1, &pStmt, 0);
8316 }else{
8317 rc = sqlite3_prepare_v2(p->db,
8318 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
8319 " (1,'run','PRAGMA integrity_check','ok')",
8320 -1, &pStmt, 0);
8321 }
8322 if( rc ){
8323 raw_printf(stderr, "Error querying the selftest table\n");
8324 rc = 1;
8325 sqlite3_finalize(pStmt);
8326 goto meta_command_exit;
8327 }
8328 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
8329 int tno = sqlite3_column_int(pStmt, 0);
8330 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
8331 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
8332 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
8333
8334 k = 0;
8335 if( bVerbose>0 ){
8336 char *zQuote = sqlite3_mprintf("%q", zSql);
8337 printf("%d: %s %s\n", tno, zOp, zSql);
8338 sqlite3_free(zQuote);
8339 }
8340 if( strcmp(zOp,"memo")==0 ){
8341 utf8_printf(p->out, "%s\n", zSql);
8342 }else
8343 if( strcmp(zOp,"run")==0 ){
8344 char *zErrMsg = 0;
8345 str.n = 0;
8346 str.z[0] = 0;
8347 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
8348 nTest++;
8349 if( bVerbose ){
8350 utf8_printf(p->out, "Result: %s\n", str.z);
8351 }
8352 if( rc || zErrMsg ){
8353 nErr++;
8354 rc = 1;
8355 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
8356 sqlite3_free(zErrMsg);
8357 }else if( strcmp(zAns,str.z)!=0 ){
8358 nErr++;
8359 rc = 1;
8360 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
8361 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
8362 }
8363 }else
8364 {
8365 utf8_printf(stderr,
8366 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
8367 rc = 1;
8368 break;
8369 }
8370 } /* End loop over rows of content from SELFTEST */
8371 sqlite3_finalize(pStmt);
8372 } /* End loop over k */
8373 freeText(&str);
8374 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
8375 }else
8376
8377 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
8378 if( nArg<2 || nArg>3 ){
8379 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
8380 rc = 1;
8381 }
8382 if( nArg>=2 ){
8383 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
8384 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
8385 }
8386 if( nArg>=3 ){
8387 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
8388 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
8389 }
8390 }else
8391
8392 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
8393 const char *zLike = 0; /* Which table to checksum. 0 means everything */
8394 int i; /* Loop counter */
8395 int bSchema = 0; /* Also hash the schema */
8396 int bSeparate = 0; /* Hash each table separately */
8397 int iSize = 224; /* Hash algorithm to use */
8398 int bDebug = 0; /* Only show the query that would have run */
8399 sqlite3_stmt *pStmt; /* For querying tables names */
8400 char *zSql; /* SQL to be run */
8401 char *zSep; /* Separator */
8402 ShellText sSql; /* Complete SQL for the query to run the hash */
8403 ShellText sQuery; /* Set of queries used to read all content */
8404 open_db(p, 0);
8405 for(i=1; i<nArg; i++){
8406 const char *z = azArg[i];
8407 if( z[0]=='-' ){
8408 z++;
8409 if( z[0]=='-' ) z++;
8410 if( strcmp(z,"schema")==0 ){
8411 bSchema = 1;
8412 }else
8413 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
8414 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
8415 ){
8416 iSize = atoi(&z[5]);
8417 }else
8418 if( strcmp(z,"debug")==0 ){
8419 bDebug = 1;
8420 }else
8421 {
8422 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8423 azArg[i], azArg[0]);
8424 raw_printf(stderr, "Should be one of: --schema"
drh003edba2018-05-11 15:10:43 +00008425 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
drh2ce15c32017-07-11 13:34:40 +00008426 rc = 1;
8427 goto meta_command_exit;
8428 }
8429 }else if( zLike ){
8430 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
8431 rc = 1;
8432 goto meta_command_exit;
8433 }else{
8434 zLike = z;
8435 bSeparate = 1;
drhcedfecf2018-03-23 12:59:10 +00008436 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
drh2ce15c32017-07-11 13:34:40 +00008437 }
8438 }
8439 if( bSchema ){
8440 zSql = "SELECT lower(name) FROM sqlite_master"
8441 " WHERE type='table' AND coalesce(rootpage,0)>1"
8442 " UNION ALL SELECT 'sqlite_master'"
8443 " ORDER BY 1 collate nocase";
8444 }else{
8445 zSql = "SELECT lower(name) FROM sqlite_master"
8446 " WHERE type='table' AND coalesce(rootpage,0)>1"
8447 " AND name NOT LIKE 'sqlite_%'"
8448 " ORDER BY 1 collate nocase";
8449 }
8450 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8451 initText(&sQuery);
8452 initText(&sSql);
8453 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
8454 zSep = "VALUES(";
8455 while( SQLITE_ROW==sqlite3_step(pStmt) ){
8456 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
8457 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
8458 if( strncmp(zTab, "sqlite_",7)!=0 ){
8459 appendText(&sQuery,"SELECT * FROM ", 0);
8460 appendText(&sQuery,zTab,'"');
8461 appendText(&sQuery," NOT INDEXED;", 0);
8462 }else if( strcmp(zTab, "sqlite_master")==0 ){
8463 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
8464 " ORDER BY name;", 0);
8465 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
8466 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
8467 " ORDER BY name;", 0);
8468 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
8469 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
8470 " ORDER BY tbl,idx;", 0);
8471 }else if( strcmp(zTab, "sqlite_stat3")==0
8472 || strcmp(zTab, "sqlite_stat4")==0 ){
8473 appendText(&sQuery, "SELECT * FROM ", 0);
8474 appendText(&sQuery, zTab, 0);
8475 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
8476 }
8477 appendText(&sSql, zSep, 0);
8478 appendText(&sSql, sQuery.z, '\'');
8479 sQuery.n = 0;
8480 appendText(&sSql, ",", 0);
8481 appendText(&sSql, zTab, '\'');
8482 zSep = "),(";
8483 }
8484 sqlite3_finalize(pStmt);
8485 if( bSeparate ){
8486 zSql = sqlite3_mprintf(
8487 "%s))"
8488 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
8489 " FROM [sha3sum$query]",
8490 sSql.z, iSize);
8491 }else{
8492 zSql = sqlite3_mprintf(
8493 "%s))"
8494 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
8495 " FROM [sha3sum$query]",
8496 sSql.z, iSize);
8497 }
8498 freeText(&sQuery);
8499 freeText(&sSql);
8500 if( bDebug ){
8501 utf8_printf(p->out, "%s\n", zSql);
8502 }else{
drha10b9992018-03-09 15:24:33 +00008503 shell_exec(p, zSql, 0);
drh2ce15c32017-07-11 13:34:40 +00008504 }
8505 sqlite3_free(zSql);
8506 }else
8507
drh04a28c32018-01-31 01:38:44 +00008508#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00008509 if( c=='s'
8510 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
8511 ){
8512 char *zCmd;
8513 int i, x;
8514 if( nArg<2 ){
8515 raw_printf(stderr, "Usage: .system COMMAND\n");
8516 rc = 1;
8517 goto meta_command_exit;
8518 }
8519 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
8520 for(i=2; i<nArg; i++){
8521 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
8522 zCmd, azArg[i]);
8523 }
8524 x = system(zCmd);
8525 sqlite3_free(zCmd);
8526 if( x ) raw_printf(stderr, "System command returns %d\n", x);
8527 }else
drh04a28c32018-01-31 01:38:44 +00008528#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00008529
8530 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00008531 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00008532 int i;
8533 if( nArg!=1 ){
8534 raw_printf(stderr, "Usage: .show\n");
8535 rc = 1;
8536 goto meta_command_exit;
8537 }
8538 utf8_printf(p->out, "%12.12s: %s\n","echo",
8539 azBool[ShellHasFlag(p, SHFLG_Echo)]);
8540 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
8541 utf8_printf(p->out, "%12.12s: %s\n","explain",
8542 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
8543 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
8544 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
8545 utf8_printf(p->out, "%12.12s: ", "nullvalue");
8546 output_c_string(p->out, p->nullValue);
8547 raw_printf(p->out, "\n");
8548 utf8_printf(p->out,"%12.12s: %s\n","output",
8549 strlen30(p->outfile) ? p->outfile : "stdout");
8550 utf8_printf(p->out,"%12.12s: ", "colseparator");
8551 output_c_string(p->out, p->colSeparator);
8552 raw_printf(p->out, "\n");
8553 utf8_printf(p->out,"%12.12s: ", "rowseparator");
8554 output_c_string(p->out, p->rowSeparator);
8555 raw_printf(p->out, "\n");
8556 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
8557 utf8_printf(p->out, "%12.12s: ", "width");
8558 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
8559 raw_printf(p->out, "%d ", p->colWidth[i]);
8560 }
8561 raw_printf(p->out, "\n");
8562 utf8_printf(p->out, "%12.12s: %s\n", "filename",
8563 p->zDbFilename ? p->zDbFilename : "");
8564 }else
8565
8566 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
8567 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00008568 p->statsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00008569 }else if( nArg==1 ){
8570 display_stats(p->db, p, 0);
8571 }else{
8572 raw_printf(stderr, "Usage: .stats ?on|off?\n");
8573 rc = 1;
8574 }
8575 }else
8576
8577 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
8578 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
8579 || strncmp(azArg[0], "indexes", n)==0) )
8580 ){
8581 sqlite3_stmt *pStmt;
8582 char **azResult;
8583 int nRow, nAlloc;
8584 int ii;
8585 ShellText s;
8586 initText(&s);
8587 open_db(p, 0);
8588 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
drh9e804032018-05-18 17:11:50 +00008589 if( rc ){
8590 sqlite3_finalize(pStmt);
8591 return shellDatabaseError(p->db);
8592 }
drh2ce15c32017-07-11 13:34:40 +00008593
8594 if( nArg>2 && c=='i' ){
8595 /* It is an historical accident that the .indexes command shows an error
8596 ** when called with the wrong number of arguments whereas the .tables
8597 ** command does not. */
8598 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
8599 rc = 1;
drh9e804032018-05-18 17:11:50 +00008600 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00008601 goto meta_command_exit;
8602 }
8603 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
8604 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
8605 if( zDbName==0 ) continue;
8606 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
8607 if( sqlite3_stricmp(zDbName, "main")==0 ){
8608 appendText(&s, "SELECT name FROM ", 0);
8609 }else{
8610 appendText(&s, "SELECT ", 0);
8611 appendText(&s, zDbName, '\'');
8612 appendText(&s, "||'.'||name FROM ", 0);
8613 }
8614 appendText(&s, zDbName, '"');
8615 appendText(&s, ".sqlite_master ", 0);
8616 if( c=='t' ){
8617 appendText(&s," WHERE type IN ('table','view')"
8618 " AND name NOT LIKE 'sqlite_%'"
8619 " AND name LIKE ?1", 0);
8620 }else{
8621 appendText(&s," WHERE type='index'"
8622 " AND tbl_name LIKE ?1", 0);
8623 }
8624 }
8625 rc = sqlite3_finalize(pStmt);
8626 appendText(&s, " ORDER BY 1", 0);
8627 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
8628 freeText(&s);
8629 if( rc ) return shellDatabaseError(p->db);
8630
8631 /* Run the SQL statement prepared by the above block. Store the results
8632 ** as an array of nul-terminated strings in azResult[]. */
8633 nRow = nAlloc = 0;
8634 azResult = 0;
8635 if( nArg>1 ){
8636 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
8637 }else{
8638 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
8639 }
8640 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8641 if( nRow>=nAlloc ){
8642 char **azNew;
8643 int n2 = nAlloc*2 + 10;
8644 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh4b5345c2018-04-24 13:07:40 +00008645 if( azNew==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008646 nAlloc = n2;
8647 azResult = azNew;
8648 }
8649 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
drh4b5345c2018-04-24 13:07:40 +00008650 if( 0==azResult[nRow] ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008651 nRow++;
8652 }
8653 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
8654 rc = shellDatabaseError(p->db);
8655 }
8656
8657 /* Pretty-print the contents of array azResult[] to the output */
8658 if( rc==0 && nRow>0 ){
8659 int len, maxlen = 0;
8660 int i, j;
8661 int nPrintCol, nPrintRow;
8662 for(i=0; i<nRow; i++){
8663 len = strlen30(azResult[i]);
8664 if( len>maxlen ) maxlen = len;
8665 }
8666 nPrintCol = 80/(maxlen+2);
8667 if( nPrintCol<1 ) nPrintCol = 1;
8668 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
8669 for(i=0; i<nPrintRow; i++){
8670 for(j=i; j<nRow; j+=nPrintRow){
8671 char *zSp = j<nPrintRow ? "" : " ";
8672 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
8673 azResult[j] ? azResult[j]:"");
8674 }
8675 raw_printf(p->out, "\n");
8676 }
8677 }
8678
8679 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
8680 sqlite3_free(azResult);
8681 }else
8682
8683 /* Begin redirecting output to the file "testcase-out.txt" */
8684 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
8685 output_reset(p);
drha92a01a2018-01-10 22:15:37 +00008686 p->out = output_file_open("testcase-out.txt", 0);
drh2ce15c32017-07-11 13:34:40 +00008687 if( p->out==0 ){
8688 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
8689 }
8690 if( nArg>=2 ){
8691 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
8692 }else{
8693 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
8694 }
8695 }else
8696
8697#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00008698 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00008699 static const struct {
8700 const char *zCtrlName; /* Name of a test-control option */
8701 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00008702 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00008703 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00008704 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
8705 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
8706 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
8707 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
8708 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
8709 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
8710 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
drheea8eb62018-11-26 18:09:15 +00008711 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" },
drhef302e82017-11-15 19:14:08 +00008712 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
8713 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
8714 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00008715#ifdef YYCOVERAGE
8716 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
8717#endif
drhef302e82017-11-15 19:14:08 +00008718 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
8719 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
8720 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
8721 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
8722 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00008723 };
8724 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00008725 int iCtrl = -1;
8726 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
8727 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00008728 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00008729 const char *zCmd = 0;
8730
drh2ce15c32017-07-11 13:34:40 +00008731 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00008732 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00008733
8734 /* The argument can optionally begin with "-" or "--" */
8735 if( zCmd[0]=='-' && zCmd[1] ){
8736 zCmd++;
8737 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8738 }
8739
8740 /* --help lists all test-controls */
8741 if( strcmp(zCmd,"help")==0 ){
8742 utf8_printf(p->out, "Available test-controls:\n");
8743 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00008744 utf8_printf(p->out, " .testctrl %s %s\n",
8745 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00008746 }
8747 rc = 1;
8748 goto meta_command_exit;
8749 }
drh2ce15c32017-07-11 13:34:40 +00008750
8751 /* convert testctrl text option to value. allow any unique prefix
8752 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00008753 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00008754 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00008755 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00008756 if( testctrl<0 ){
8757 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00008758 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00008759 }else{
drh35f51a42017-11-15 17:07:22 +00008760 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
8761 "Use \".testctrl --help\" for help\n", zCmd);
8762 rc = 1;
8763 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00008764 }
8765 }
8766 }
drhef302e82017-11-15 19:14:08 +00008767 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00008768 utf8_printf(stderr,"Error: unknown test-control: %s\n"
8769 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00008770 }else{
8771 switch(testctrl){
8772
8773 /* sqlite3_test_control(int, db, int) */
8774 case SQLITE_TESTCTRL_OPTIMIZATIONS:
8775 case SQLITE_TESTCTRL_RESERVE:
8776 if( nArg==3 ){
8777 int opt = (int)strtol(azArg[2], 0, 0);
8778 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00008779 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008780 }
8781 break;
8782
8783 /* sqlite3_test_control(int) */
8784 case SQLITE_TESTCTRL_PRNG_SAVE:
8785 case SQLITE_TESTCTRL_PRNG_RESTORE:
8786 case SQLITE_TESTCTRL_PRNG_RESET:
8787 case SQLITE_TESTCTRL_BYTEORDER:
8788 if( nArg==2 ){
8789 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00008790 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00008791 }
8792 break;
8793
8794 /* sqlite3_test_control(int, uint) */
8795 case SQLITE_TESTCTRL_PENDING_BYTE:
8796 if( nArg==3 ){
8797 unsigned int opt = (unsigned int)integerValue(azArg[2]);
8798 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00008799 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008800 }
8801 break;
8802
8803 /* sqlite3_test_control(int, int) */
8804 case SQLITE_TESTCTRL_ASSERT:
8805 case SQLITE_TESTCTRL_ALWAYS:
drheea8eb62018-11-26 18:09:15 +00008806 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
drhef302e82017-11-15 19:14:08 +00008807 if( nArg==3 ){
8808 int opt = booleanValue(azArg[2]);
8809 rc2 = sqlite3_test_control(testctrl, opt);
8810 isOk = 1;
8811 }
8812 break;
8813
8814 /* sqlite3_test_control(int, int) */
8815 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00008816 case SQLITE_TESTCTRL_NEVER_CORRUPT:
8817 if( nArg==3 ){
8818 int opt = booleanValue(azArg[2]);
8819 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00008820 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008821 }
8822 break;
8823
drh2ce15c32017-07-11 13:34:40 +00008824 case SQLITE_TESTCTRL_IMPOSTER:
8825 if( nArg==5 ){
8826 rc2 = sqlite3_test_control(testctrl, p->db,
8827 azArg[2],
8828 integerValue(azArg[3]),
8829 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00008830 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008831 }
8832 break;
drh0d9de992017-12-26 18:04:23 +00008833
8834#ifdef YYCOVERAGE
8835 case SQLITE_TESTCTRL_PARSER_COVERAGE:
8836 if( nArg==2 ){
8837 sqlite3_test_control(testctrl, p->out);
8838 isOk = 3;
8839 }
8840#endif
drh2ce15c32017-07-11 13:34:40 +00008841 }
8842 }
drhef302e82017-11-15 19:14:08 +00008843 if( isOk==0 && iCtrl>=0 ){
8844 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
8845 rc = 1;
8846 }else if( isOk==1 ){
8847 raw_printf(p->out, "%d\n", rc2);
8848 }else if( isOk==2 ){
8849 raw_printf(p->out, "0x%08x\n", rc2);
8850 }
drh2ce15c32017-07-11 13:34:40 +00008851 }else
8852#endif /* !defined(SQLITE_UNTESTABLE) */
8853
8854 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
8855 open_db(p, 0);
8856 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
8857 }else
8858
8859 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
8860 if( nArg==2 ){
8861 enableTimer = booleanValue(azArg[1]);
8862 if( enableTimer && !HAS_TIMER ){
8863 raw_printf(stderr, "Error: timer not available on this system.\n");
8864 enableTimer = 0;
8865 }
8866 }else{
8867 raw_printf(stderr, "Usage: .timer on|off\n");
8868 rc = 1;
8869 }
8870 }else
8871
drh707821f2018-12-05 13:39:06 +00008872#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00008873 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh707821f2018-12-05 13:39:06 +00008874 int mType = 0;
8875 int jj;
drh2ce15c32017-07-11 13:34:40 +00008876 open_db(p, 0);
drh707821f2018-12-05 13:39:06 +00008877 for(jj=1; jj<nArg; jj++){
8878 const char *z = azArg[jj];
8879 if( z[0]=='-' ){
8880 if( optionMatch(z, "expanded") ){
8881 p->eTraceType = SHELL_TRACE_EXPANDED;
8882 }
8883#ifdef SQLITE_ENABLE_NORMALIZE
8884 else if( optionMatch(z, "normalized") ){
8885 p->eTraceType = SHELL_TRACE_NORMALIZED;
8886 }
8887#endif
8888 else if( optionMatch(z, "plain") ){
8889 p->eTraceType = SHELL_TRACE_PLAIN;
8890 }
8891 else if( optionMatch(z, "profile") ){
8892 mType |= SQLITE_TRACE_PROFILE;
8893 }
8894 else if( optionMatch(z, "row") ){
8895 mType |= SQLITE_TRACE_ROW;
8896 }
8897 else if( optionMatch(z, "stmt") ){
8898 mType |= SQLITE_TRACE_STMT;
8899 }
8900 else if( optionMatch(z, "close") ){
8901 mType |= SQLITE_TRACE_CLOSE;
8902 }
8903 else {
8904 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
8905 rc = 1;
8906 goto meta_command_exit;
8907 }
8908 }else{
8909 output_file_close(p->traceOut);
8910 p->traceOut = output_file_open(azArg[1], 0);
8911 }
drh2ce15c32017-07-11 13:34:40 +00008912 }
drh2ce15c32017-07-11 13:34:40 +00008913 if( p->traceOut==0 ){
8914 sqlite3_trace_v2(p->db, 0, 0, 0);
8915 }else{
drh707821f2018-12-05 13:39:06 +00008916 if( mType==0 ) mType = SQLITE_TRACE_STMT;
8917 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
drh2ce15c32017-07-11 13:34:40 +00008918 }
drh2ce15c32017-07-11 13:34:40 +00008919 }else
drh707821f2018-12-05 13:39:06 +00008920#endif /* !defined(SQLITE_OMIT_TRACE) */
drh2ce15c32017-07-11 13:34:40 +00008921
8922#if SQLITE_USER_AUTHENTICATION
8923 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
8924 if( nArg<2 ){
8925 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
8926 rc = 1;
8927 goto meta_command_exit;
8928 }
8929 open_db(p, 0);
8930 if( strcmp(azArg[1],"login")==0 ){
8931 if( nArg!=4 ){
8932 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
8933 rc = 1;
8934 goto meta_command_exit;
8935 }
drhaf2770f2018-01-05 14:55:43 +00008936 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00008937 if( rc ){
8938 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
8939 rc = 1;
8940 }
8941 }else if( strcmp(azArg[1],"add")==0 ){
8942 if( nArg!=5 ){
8943 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
8944 rc = 1;
8945 goto meta_command_exit;
8946 }
drhaf2770f2018-01-05 14:55:43 +00008947 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00008948 booleanValue(azArg[4]));
8949 if( rc ){
8950 raw_printf(stderr, "User-Add failed: %d\n", rc);
8951 rc = 1;
8952 }
8953 }else if( strcmp(azArg[1],"edit")==0 ){
8954 if( nArg!=5 ){
8955 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
8956 rc = 1;
8957 goto meta_command_exit;
8958 }
drhaf2770f2018-01-05 14:55:43 +00008959 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00008960 booleanValue(azArg[4]));
8961 if( rc ){
8962 raw_printf(stderr, "User-Edit failed: %d\n", rc);
8963 rc = 1;
8964 }
8965 }else if( strcmp(azArg[1],"delete")==0 ){
8966 if( nArg!=3 ){
8967 raw_printf(stderr, "Usage: .user delete USER\n");
8968 rc = 1;
8969 goto meta_command_exit;
8970 }
8971 rc = sqlite3_user_delete(p->db, azArg[2]);
8972 if( rc ){
8973 raw_printf(stderr, "User-Delete failed: %d\n", rc);
8974 rc = 1;
8975 }
8976 }else{
8977 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
8978 rc = 1;
8979 goto meta_command_exit;
8980 }
8981 }else
8982#endif /* SQLITE_USER_AUTHENTICATION */
8983
8984 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
8985 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
8986 sqlite3_libversion(), sqlite3_sourceid());
drh0ed2fd82018-01-16 20:05:27 +00008987#if SQLITE_HAVE_ZLIB
8988 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
8989#endif
8990#define CTIMEOPT_VAL_(opt) #opt
8991#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
8992#if defined(__clang__) && defined(__clang_major__)
8993 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
8994 CTIMEOPT_VAL(__clang_minor__) "."
8995 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
8996#elif defined(_MSC_VER)
8997 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
8998#elif defined(__GNUC__) && defined(__VERSION__)
8999 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
9000#endif
drh2ce15c32017-07-11 13:34:40 +00009001 }else
9002
9003 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
9004 const char *zDbName = nArg==2 ? azArg[1] : "main";
9005 sqlite3_vfs *pVfs = 0;
9006 if( p->db ){
9007 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
9008 if( pVfs ){
9009 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
9010 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
9011 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
9012 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9013 }
9014 }
9015 }else
9016
9017 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
9018 sqlite3_vfs *pVfs;
9019 sqlite3_vfs *pCurrent = 0;
9020 if( p->db ){
9021 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
9022 }
9023 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
9024 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
9025 pVfs==pCurrent ? " <--- CURRENT" : "");
9026 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
9027 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
9028 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9029 if( pVfs->pNext ){
9030 raw_printf(p->out, "-----------------------------------\n");
9031 }
9032 }
9033 }else
9034
9035 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
9036 const char *zDbName = nArg==2 ? azArg[1] : "main";
9037 char *zVfsName = 0;
9038 if( p->db ){
9039 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
9040 if( zVfsName ){
9041 utf8_printf(p->out, "%s\n", zVfsName);
9042 sqlite3_free(zVfsName);
9043 }
9044 }
9045 }else
9046
9047#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
9048 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
9049 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
9050 }else
9051#endif
9052
9053 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
9054 int j;
9055 assert( nArg<=ArraySize(azArg) );
9056 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
9057 p->colWidth[j-1] = (int)integerValue(azArg[j]);
9058 }
9059 }else
9060
9061 {
9062 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
9063 " \"%s\". Enter \".help\" for help\n", azArg[0]);
9064 rc = 1;
9065 }
9066
9067meta_command_exit:
9068 if( p->outCount ){
9069 p->outCount--;
9070 if( p->outCount==0 ) output_reset(p);
9071 }
9072 return rc;
9073}
9074
9075/*
9076** Return TRUE if a semicolon occurs anywhere in the first N characters
9077** of string z[].
9078*/
9079static int line_contains_semicolon(const char *z, int N){
9080 int i;
9081 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
9082 return 0;
9083}
9084
9085/*
9086** Test to see if a line consists entirely of whitespace.
9087*/
9088static int _all_whitespace(const char *z){
9089 for(; *z; z++){
9090 if( IsSpace(z[0]) ) continue;
9091 if( *z=='/' && z[1]=='*' ){
9092 z += 2;
9093 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
9094 if( *z==0 ) return 0;
9095 z++;
9096 continue;
9097 }
9098 if( *z=='-' && z[1]=='-' ){
9099 z += 2;
9100 while( *z && *z!='\n' ){ z++; }
9101 if( *z==0 ) return 1;
9102 continue;
9103 }
9104 return 0;
9105 }
9106 return 1;
9107}
9108
9109/*
9110** Return TRUE if the line typed in is an SQL command terminator other
9111** than a semi-colon. The SQL Server style "go" command is understood
9112** as is the Oracle "/".
9113*/
9114static int line_is_command_terminator(const char *zLine){
9115 while( IsSpace(zLine[0]) ){ zLine++; };
9116 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
9117 return 1; /* Oracle */
9118 }
9119 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
9120 && _all_whitespace(&zLine[2]) ){
9121 return 1; /* SQL Server */
9122 }
9123 return 0;
9124}
9125
9126/*
drh56f17742018-01-24 01:58:49 +00009127** We need a default sqlite3_complete() implementation to use in case
9128** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
9129** any arbitrary text is a complete SQL statement. This is not very
9130** user-friendly, but it does seem to work.
9131*/
9132#ifdef SQLITE_OMIT_COMPLETE
danc86b23b2018-11-16 14:36:42 +00009133#define sqlite3_complete(x) 1
drh56f17742018-01-24 01:58:49 +00009134#endif
9135
9136/*
drh2ce15c32017-07-11 13:34:40 +00009137** Return true if zSql is a complete SQL statement. Return false if it
9138** ends in the middle of a string literal or C-style comment.
9139*/
9140static int line_is_complete(char *zSql, int nSql){
9141 int rc;
9142 if( zSql==0 ) return 1;
9143 zSql[nSql] = ';';
9144 zSql[nSql+1] = 0;
9145 rc = sqlite3_complete(zSql);
9146 zSql[nSql] = 0;
9147 return rc;
9148}
9149
9150/*
drhfc29a862018-05-11 19:11:18 +00009151** Run a single line of SQL. Return the number of errors.
drh2ce15c32017-07-11 13:34:40 +00009152*/
9153static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
9154 int rc;
9155 char *zErrMsg = 0;
9156
9157 open_db(p, 0);
9158 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drhfc4eeef2019-02-05 19:48:46 +00009159 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
drh2ce15c32017-07-11 13:34:40 +00009160 BEGIN_TIMER;
drha10b9992018-03-09 15:24:33 +00009161 rc = shell_exec(p, zSql, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00009162 END_TIMER;
9163 if( rc || zErrMsg ){
9164 char zPrefix[100];
9165 if( in!=0 || !stdin_is_interactive ){
9166 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
9167 "Error: near line %d:", startline);
9168 }else{
9169 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
9170 }
9171 if( zErrMsg!=0 ){
9172 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
9173 sqlite3_free(zErrMsg);
9174 zErrMsg = 0;
9175 }else{
9176 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
9177 }
9178 return 1;
9179 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
9180 raw_printf(p->out, "changes: %3d total_changes: %d\n",
9181 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
9182 }
9183 return 0;
9184}
9185
9186
9187/*
9188** Read input from *in and process it. If *in==0 then input
9189** is interactive - the user is typing it it. Otherwise, input
9190** is coming from a file or device. A prompt is issued and history
9191** is saved only if input is interactive. An interrupt signal will
9192** cause this routine to exit immediately, unless input is interactive.
9193**
9194** Return the number of errors.
9195*/
drh60379d42018-12-13 18:30:01 +00009196static int process_input(ShellState *p){
drh2ce15c32017-07-11 13:34:40 +00009197 char *zLine = 0; /* A single input line */
9198 char *zSql = 0; /* Accumulated SQL text */
9199 int nLine; /* Length of current line */
9200 int nSql = 0; /* Bytes of zSql[] used */
9201 int nAlloc = 0; /* Allocated zSql[] space */
9202 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
9203 int rc; /* Error code */
9204 int errCnt = 0; /* Number of errors seen */
drh2ce15c32017-07-11 13:34:40 +00009205 int startline = 0; /* Line number for start of current input */
9206
drh2c8ee022018-12-13 18:59:30 +00009207 p->lineno = 0;
drh60379d42018-12-13 18:30:01 +00009208 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
drh2ce15c32017-07-11 13:34:40 +00009209 fflush(p->out);
drh60379d42018-12-13 18:30:01 +00009210 zLine = one_input_line(p->in, zLine, nSql>0);
drh2ce15c32017-07-11 13:34:40 +00009211 if( zLine==0 ){
9212 /* End of input */
drh60379d42018-12-13 18:30:01 +00009213 if( p->in==0 && stdin_is_interactive ) printf("\n");
drh2ce15c32017-07-11 13:34:40 +00009214 break;
9215 }
9216 if( seenInterrupt ){
drh60379d42018-12-13 18:30:01 +00009217 if( p->in!=0 ) break;
drh2ce15c32017-07-11 13:34:40 +00009218 seenInterrupt = 0;
9219 }
drh2c8ee022018-12-13 18:59:30 +00009220 p->lineno++;
drh2ce15c32017-07-11 13:34:40 +00009221 if( nSql==0 && _all_whitespace(zLine) ){
9222 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
9223 continue;
9224 }
drh1615c372018-05-12 23:56:22 +00009225 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00009226 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh1615c372018-05-12 23:56:22 +00009227 if( zLine[0]=='.' ){
9228 rc = do_meta_command(zLine, p);
9229 if( rc==2 ){ /* exit requested */
9230 break;
9231 }else if( rc ){
9232 errCnt++;
9233 }
drh2ce15c32017-07-11 13:34:40 +00009234 }
9235 continue;
9236 }
9237 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
9238 memcpy(zLine,";",2);
9239 }
9240 nLine = strlen30(zLine);
9241 if( nSql+nLine+2>=nAlloc ){
9242 nAlloc = nSql+nLine+100;
9243 zSql = realloc(zSql, nAlloc);
drh4b5345c2018-04-24 13:07:40 +00009244 if( zSql==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009245 }
9246 nSqlPrior = nSql;
9247 if( nSql==0 ){
9248 int i;
9249 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
9250 assert( nAlloc>0 && zSql!=0 );
9251 memcpy(zSql, zLine+i, nLine+1-i);
drh2c8ee022018-12-13 18:59:30 +00009252 startline = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00009253 nSql = nLine-i;
9254 }else{
9255 zSql[nSql++] = '\n';
9256 memcpy(zSql+nSql, zLine, nLine+1);
9257 nSql += nLine;
9258 }
9259 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
9260 && sqlite3_complete(zSql) ){
drh60379d42018-12-13 18:30:01 +00009261 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00009262 nSql = 0;
9263 if( p->outCount ){
9264 output_reset(p);
9265 p->outCount = 0;
drh13c20932018-01-10 21:41:55 +00009266 }else{
9267 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00009268 }
9269 }else if( nSql && _all_whitespace(zSql) ){
9270 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
9271 nSql = 0;
9272 }
9273 }
9274 if( nSql && !_all_whitespace(zSql) ){
drh60379d42018-12-13 18:30:01 +00009275 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00009276 }
9277 free(zSql);
9278 free(zLine);
9279 return errCnt>0;
9280}
9281
9282/*
9283** Return a pathname which is the user's home directory. A
9284** 0 return indicates an error of some kind.
9285*/
9286static char *find_home_dir(int clearFlag){
9287 static char *home_dir = NULL;
9288 if( clearFlag ){
9289 free(home_dir);
9290 home_dir = 0;
9291 return 0;
9292 }
9293 if( home_dir ) return home_dir;
9294
9295#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
9296 && !defined(__RTP__) && !defined(_WRS_KERNEL)
9297 {
9298 struct passwd *pwent;
9299 uid_t uid = getuid();
9300 if( (pwent=getpwuid(uid)) != NULL) {
9301 home_dir = pwent->pw_dir;
9302 }
9303 }
9304#endif
9305
9306#if defined(_WIN32_WCE)
9307 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
9308 */
9309 home_dir = "/";
9310#else
9311
9312#if defined(_WIN32) || defined(WIN32)
9313 if (!home_dir) {
9314 home_dir = getenv("USERPROFILE");
9315 }
9316#endif
9317
9318 if (!home_dir) {
9319 home_dir = getenv("HOME");
9320 }
9321
9322#if defined(_WIN32) || defined(WIN32)
9323 if (!home_dir) {
9324 char *zDrive, *zPath;
9325 int n;
9326 zDrive = getenv("HOMEDRIVE");
9327 zPath = getenv("HOMEPATH");
9328 if( zDrive && zPath ){
9329 n = strlen30(zDrive) + strlen30(zPath) + 1;
9330 home_dir = malloc( n );
9331 if( home_dir==0 ) return 0;
9332 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
9333 return home_dir;
9334 }
9335 home_dir = "c:\\";
9336 }
9337#endif
9338
9339#endif /* !_WIN32_WCE */
9340
9341 if( home_dir ){
9342 int n = strlen30(home_dir) + 1;
9343 char *z = malloc( n );
9344 if( z ) memcpy(z, home_dir, n);
9345 home_dir = z;
9346 }
9347
9348 return home_dir;
9349}
9350
9351/*
9352** Read input from the file given by sqliterc_override. Or if that
9353** parameter is NULL, take input from ~/.sqliterc
9354**
9355** Returns the number of errors.
9356*/
9357static void process_sqliterc(
9358 ShellState *p, /* Configuration data */
9359 const char *sqliterc_override /* Name of config file. NULL to use default */
9360){
9361 char *home_dir = NULL;
9362 const char *sqliterc = sqliterc_override;
9363 char *zBuf = 0;
drh60379d42018-12-13 18:30:01 +00009364 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00009365 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00009366
9367 if (sqliterc == NULL) {
9368 home_dir = find_home_dir(0);
9369 if( home_dir==0 ){
9370 raw_printf(stderr, "-- warning: cannot find home directory;"
9371 " cannot read ~/.sqliterc\n");
9372 return;
9373 }
drh2ce15c32017-07-11 13:34:40 +00009374 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
9375 sqliterc = zBuf;
9376 }
drh60379d42018-12-13 18:30:01 +00009377 p->in = fopen(sqliterc,"rb");
9378 if( p->in ){
drh2ce15c32017-07-11 13:34:40 +00009379 if( stdin_is_interactive ){
9380 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
9381 }
drh60379d42018-12-13 18:30:01 +00009382 process_input(p);
9383 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00009384 }
drh60379d42018-12-13 18:30:01 +00009385 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00009386 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00009387 sqlite3_free(zBuf);
9388}
9389
9390/*
9391** Show available command line options
9392*/
9393static const char zOptions[] =
drhda57d962018-03-05 19:34:05 +00009394#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhad7fd5d2018-03-05 20:21:50 +00009395 " -A ARGS... run \".archive ARGS\" and exit\n"
drhda57d962018-03-05 19:34:05 +00009396#endif
drh3baed312018-03-08 18:14:41 +00009397 " -append append the database to the end of the file\n"
drh2ce15c32017-07-11 13:34:40 +00009398 " -ascii set output mode to 'ascii'\n"
9399 " -bail stop after hitting an error\n"
9400 " -batch force batch I/O\n"
9401 " -column set output mode to 'column'\n"
9402 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
9403 " -csv set output mode to 'csv'\n"
drh6ca64482019-01-22 16:06:20 +00009404#if defined(SQLITE_ENABLE_DESERIALIZE)
9405 " -deserialize open the database using sqlite3_deserialize()\n"
9406#endif
drh2ce15c32017-07-11 13:34:40 +00009407 " -echo print commands before execution\n"
9408 " -init FILENAME read/process named file\n"
9409 " -[no]header turn headers on or off\n"
9410#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
9411 " -heap SIZE Size of heap for memsys3 or memsys5\n"
9412#endif
9413 " -help show this message\n"
9414 " -html set output mode to HTML\n"
9415 " -interactive force interactive I/O\n"
9416 " -line set output mode to 'line'\n"
9417 " -list set output mode to 'list'\n"
9418 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh6ca64482019-01-22 16:06:20 +00009419#if defined(SQLITE_ENABLE_DESERIALIZE)
9420 " -maxsize N maximum size for a --deserialize database\n"
9421#endif
drhaf482572019-02-04 19:52:39 +00009422 " -memtrace trace all memory allocations and deallocations\n"
drh2ce15c32017-07-11 13:34:40 +00009423 " -mmap N default mmap size set to N\n"
9424#ifdef SQLITE_ENABLE_MULTIPLEX
9425 " -multiplex enable the multiplexor VFS\n"
9426#endif
9427 " -newline SEP set output row separator. Default: '\\n'\n"
9428 " -nullvalue TEXT set text string for NULL values. Default ''\n"
9429 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
9430 " -quote set output mode to 'quote'\n"
drhee269a62018-02-14 23:27:43 +00009431 " -readonly open the database read-only\n"
drh2ce15c32017-07-11 13:34:40 +00009432 " -separator SEP set output column separator. Default: '|'\n"
drha90d84f2018-04-18 15:21:13 +00009433#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9434 " -sorterref SIZE sorter references threshold size\n"
9435#endif
drh2ce15c32017-07-11 13:34:40 +00009436 " -stats print memory stats before each finalize\n"
9437 " -version show SQLite version\n"
9438 " -vfs NAME use NAME as the default VFS\n"
9439#ifdef SQLITE_ENABLE_VFSTRACE
9440 " -vfstrace enable tracing of all VFS calls\n"
9441#endif
drh3baed312018-03-08 18:14:41 +00009442#ifdef SQLITE_HAVE_ZLIB
9443 " -zip open the file as a ZIP Archive\n"
9444#endif
drh2ce15c32017-07-11 13:34:40 +00009445;
9446static void usage(int showDetail){
9447 utf8_printf(stderr,
9448 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
9449 "FILENAME is the name of an SQLite database. A new database is created\n"
9450 "if the file does not previously exist.\n", Argv0);
9451 if( showDetail ){
9452 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
9453 }else{
9454 raw_printf(stderr, "Use the -help option for additional information\n");
9455 }
9456 exit(1);
9457}
9458
9459/*
drhe7df8922018-04-18 10:44:58 +00009460** Internal check: Verify that the SQLite is uninitialized. Print a
9461** error message if it is initialized.
9462*/
9463static void verify_uninitialized(void){
9464 if( sqlite3_config(-1)==SQLITE_MISUSE ){
drh8e02a182018-05-30 07:24:41 +00009465 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
drhe7df8922018-04-18 10:44:58 +00009466 " initialization.\n");
9467 }
9468}
9469
9470/*
drh2ce15c32017-07-11 13:34:40 +00009471** Initialize the state information in data
9472*/
9473static void main_init(ShellState *data) {
9474 memset(data, 0, sizeof(*data));
9475 data->normalMode = data->cMode = data->mode = MODE_List;
9476 data->autoExplain = 1;
9477 memcpy(data->colSeparator,SEP_Column, 2);
9478 memcpy(data->rowSeparator,SEP_Row, 2);
9479 data->showHeader = 0;
9480 data->shellFlgs = SHFLG_Lookaside;
drhe7df8922018-04-18 10:44:58 +00009481 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00009482 sqlite3_config(SQLITE_CONFIG_URI, 1);
9483 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
9484 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
9485 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
9486 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
9487}
9488
9489/*
9490** Output text to the console in a font that attracts extra attention.
9491*/
9492#ifdef _WIN32
9493static void printBold(const char *zText){
9494 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
9495 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
9496 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
9497 SetConsoleTextAttribute(out,
9498 FOREGROUND_RED|FOREGROUND_INTENSITY
9499 );
9500 printf("%s", zText);
9501 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
9502}
9503#else
9504static void printBold(const char *zText){
9505 printf("\033[1m%s\033[0m", zText);
9506}
9507#endif
9508
9509/*
9510** Get the argument to an --option. Throw an error and die if no argument
9511** is available.
9512*/
9513static char *cmdline_option_value(int argc, char **argv, int i){
9514 if( i==argc ){
9515 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
9516 argv[0], argv[argc-1]);
9517 exit(1);
9518 }
9519 return argv[i];
9520}
9521
9522#ifndef SQLITE_SHELL_IS_UTF8
9523# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
9524# define SQLITE_SHELL_IS_UTF8 (0)
9525# else
9526# define SQLITE_SHELL_IS_UTF8 (1)
9527# endif
9528#endif
9529
9530#if SQLITE_SHELL_IS_UTF8
9531int SQLITE_CDECL main(int argc, char **argv){
9532#else
9533int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
9534 char **argv;
9535#endif
9536 char *zErrMsg = 0;
9537 ShellState data;
9538 const char *zInitFile = 0;
9539 int i;
9540 int rc = 0;
9541 int warnInmemoryDb = 0;
9542 int readStdin = 1;
9543 int nCmd = 0;
9544 char **azCmd = 0;
dan16a47422018-04-18 09:16:11 +00009545 const char *zVfs = 0; /* Value of -vfs command-line option */
drh1f22f622018-05-17 13:29:14 +00009546#if !SQLITE_SHELL_IS_UTF8
9547 char **argvToFree = 0;
9548 int argcToFree = 0;
9549#endif
drh2ce15c32017-07-11 13:34:40 +00009550
9551 setBinaryMode(stdin, 0);
9552 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
9553 stdin_is_interactive = isatty(0);
9554 stdout_is_console = isatty(1);
9555
mistachkin1e8487d2018-07-22 06:25:35 +00009556#if !defined(_WIN32_WCE)
9557 if( getenv("SQLITE_DEBUG_BREAK") ){
9558 if( isatty(0) && isatty(2) ){
9559 fprintf(stderr,
9560 "attach debugger to process %d and press any key to continue.\n",
9561 GETPID());
9562 fgetc(stdin);
9563 }else{
9564#if defined(_WIN32) || defined(WIN32)
9565 DebugBreak();
9566#elif defined(SIGTRAP)
9567 raise(SIGTRAP);
9568#endif
9569 }
9570 }
9571#endif
9572
drh2ce15c32017-07-11 13:34:40 +00009573#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00009574 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00009575 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
9576 sqlite3_sourceid(), SQLITE_SOURCE_ID);
9577 exit(1);
9578 }
9579#endif
9580 main_init(&data);
drh501ea052018-02-15 01:03:37 +00009581
9582 /* On Windows, we must translate command-line arguments into UTF-8.
9583 ** The SQLite memory allocator subsystem has to be enabled in order to
9584 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
9585 ** subsequent sqlite3_config() calls will work. So copy all results into
9586 ** memory that does not come from the SQLite memory allocator.
9587 */
drh4b18c1d2018-02-04 20:33:13 +00009588#if !SQLITE_SHELL_IS_UTF8
drh501ea052018-02-15 01:03:37 +00009589 sqlite3_initialize();
drh1f22f622018-05-17 13:29:14 +00009590 argvToFree = malloc(sizeof(argv[0])*argc*2);
9591 argcToFree = argc;
9592 argv = argvToFree + argc;
drh4b5345c2018-04-24 13:07:40 +00009593 if( argv==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009594 for(i=0; i<argc; i++){
drh501ea052018-02-15 01:03:37 +00009595 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
9596 int n;
drh4b5345c2018-04-24 13:07:40 +00009597 if( z==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00009598 n = (int)strlen(z);
9599 argv[i] = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00009600 if( argv[i]==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00009601 memcpy(argv[i], z, n+1);
drh1f22f622018-05-17 13:29:14 +00009602 argvToFree[i] = argv[i];
drh501ea052018-02-15 01:03:37 +00009603 sqlite3_free(z);
drh2ce15c32017-07-11 13:34:40 +00009604 }
drh501ea052018-02-15 01:03:37 +00009605 sqlite3_shutdown();
drh2ce15c32017-07-11 13:34:40 +00009606#endif
drh501ea052018-02-15 01:03:37 +00009607
drh2ce15c32017-07-11 13:34:40 +00009608 assert( argc>=1 && argv && argv[0] );
9609 Argv0 = argv[0];
9610
9611 /* Make sure we have a valid signal handler early, before anything
9612 ** else is done.
9613 */
9614#ifdef SIGINT
9615 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00009616#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
9617 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00009618#endif
9619
9620#ifdef SQLITE_SHELL_DBNAME_PROC
9621 {
9622 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
9623 ** of a C-function that will provide the name of the database file. Use
9624 ** this compile-time option to embed this shell program in larger
9625 ** applications. */
9626 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
9627 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
9628 warnInmemoryDb = 0;
9629 }
9630#endif
9631
9632 /* Do an initial pass through the command-line argument to locate
9633 ** the name of the database file, the name of the initialization file,
9634 ** the size of the alternative malloc heap,
9635 ** and the first command to execute.
9636 */
drhe7df8922018-04-18 10:44:58 +00009637 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00009638 for(i=1; i<argc; i++){
9639 char *z;
9640 z = argv[i];
9641 if( z[0]!='-' ){
9642 if( data.zDbFilename==0 ){
9643 data.zDbFilename = z;
9644 }else{
9645 /* Excesss arguments are interpreted as SQL (or dot-commands) and
9646 ** mean that nothing is read from stdin */
9647 readStdin = 0;
9648 nCmd++;
9649 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
drh4b5345c2018-04-24 13:07:40 +00009650 if( azCmd==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009651 azCmd[nCmd-1] = z;
9652 }
9653 }
9654 if( z[1]=='-' ) z++;
9655 if( strcmp(z,"-separator")==0
9656 || strcmp(z,"-nullvalue")==0
9657 || strcmp(z,"-newline")==0
9658 || strcmp(z,"-cmd")==0
9659 ){
9660 (void)cmdline_option_value(argc, argv, ++i);
9661 }else if( strcmp(z,"-init")==0 ){
9662 zInitFile = cmdline_option_value(argc, argv, ++i);
9663 }else if( strcmp(z,"-batch")==0 ){
9664 /* Need to check for batch mode here to so we can avoid printing
9665 ** informational messages (like from process_sqliterc) before
9666 ** we do the actual processing of arguments later in a second pass.
9667 */
9668 stdin_is_interactive = 0;
9669 }else if( strcmp(z,"-heap")==0 ){
9670#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
9671 const char *zSize;
9672 sqlite3_int64 szHeap;
9673
9674 zSize = cmdline_option_value(argc, argv, ++i);
9675 szHeap = integerValue(zSize);
9676 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
9677 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
9678#else
9679 (void)cmdline_option_value(argc, argv, ++i);
9680#endif
drh2ce15c32017-07-11 13:34:40 +00009681 }else if( strcmp(z,"-pagecache")==0 ){
9682 int n, sz;
9683 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
9684 if( sz>70000 ) sz = 70000;
9685 if( sz<0 ) sz = 0;
9686 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
9687 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
9688 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
9689 data.shellFlgs |= SHFLG_Pagecache;
9690 }else if( strcmp(z,"-lookaside")==0 ){
9691 int n, sz;
9692 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
9693 if( sz<0 ) sz = 0;
9694 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
9695 if( n<0 ) n = 0;
9696 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
9697 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
9698#ifdef SQLITE_ENABLE_VFSTRACE
9699 }else if( strcmp(z,"-vfstrace")==0 ){
9700 extern int vfstrace_register(
9701 const char *zTraceName,
9702 const char *zOldVfsName,
9703 int (*xOut)(const char*,void*),
9704 void *pOutArg,
9705 int makeDefault
9706 );
9707 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
9708#endif
9709#ifdef SQLITE_ENABLE_MULTIPLEX
9710 }else if( strcmp(z,"-multiplex")==0 ){
9711 extern int sqlite3_multiple_initialize(const char*,int);
9712 sqlite3_multiplex_initialize(0, 1);
9713#endif
9714 }else if( strcmp(z,"-mmap")==0 ){
9715 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
9716 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drha90d84f2018-04-18 15:21:13 +00009717#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9718 }else if( strcmp(z,"-sorterref")==0 ){
9719 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
9720 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
9721#endif
drh2ce15c32017-07-11 13:34:40 +00009722 }else if( strcmp(z,"-vfs")==0 ){
dan16a47422018-04-18 09:16:11 +00009723 zVfs = cmdline_option_value(argc, argv, ++i);
drh3baed312018-03-08 18:14:41 +00009724#ifdef SQLITE_HAVE_ZLIB
drh8682e122018-01-07 20:38:10 +00009725 }else if( strcmp(z,"-zip")==0 ){
9726 data.openMode = SHELL_OPEN_ZIPFILE;
9727#endif
9728 }else if( strcmp(z,"-append")==0 ){
9729 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +00009730#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00009731 }else if( strcmp(z,"-deserialize")==0 ){
9732 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +00009733 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
9734 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +00009735#endif
drhee269a62018-02-14 23:27:43 +00009736 }else if( strcmp(z,"-readonly")==0 ){
9737 data.openMode = SHELL_OPEN_READONLY;
drhda57d962018-03-05 19:34:05 +00009738#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00009739 }else if( strncmp(z, "-A",2)==0 ){
drhda57d962018-03-05 19:34:05 +00009740 /* All remaining command-line arguments are passed to the ".archive"
9741 ** command, so ignore them */
9742 break;
9743#endif
drh50b910a2019-01-21 14:55:03 +00009744 }else if( strcmp(z, "-memtrace")==0 ){
9745 sqlite3MemTraceActivate(stderr);
drh2ce15c32017-07-11 13:34:40 +00009746 }
9747 }
drhe7df8922018-04-18 10:44:58 +00009748 verify_uninitialized();
9749
dan16a47422018-04-18 09:16:11 +00009750
drhd11b8f62018-04-25 13:27:07 +00009751#ifdef SQLITE_SHELL_INIT_PROC
9752 {
9753 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
9754 ** of a C-function that will perform initialization actions on SQLite that
9755 ** occur just before or after sqlite3_initialize(). Use this compile-time
9756 ** option to embed this shell program in larger applications. */
9757 extern void SQLITE_SHELL_INIT_PROC(void);
9758 SQLITE_SHELL_INIT_PROC();
9759 }
9760#else
dan16a47422018-04-18 09:16:11 +00009761 /* All the sqlite3_config() calls have now been made. So it is safe
9762 ** to call sqlite3_initialize() and process any command line -vfs option. */
9763 sqlite3_initialize();
drhd11b8f62018-04-25 13:27:07 +00009764#endif
9765
dan16a47422018-04-18 09:16:11 +00009766 if( zVfs ){
9767 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
9768 if( pVfs ){
9769 sqlite3_vfs_register(pVfs, 1);
9770 }else{
9771 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
9772 exit(1);
9773 }
9774 }
9775
drh2ce15c32017-07-11 13:34:40 +00009776 if( data.zDbFilename==0 ){
9777#ifndef SQLITE_OMIT_MEMORYDB
9778 data.zDbFilename = ":memory:";
9779 warnInmemoryDb = argc==1;
9780#else
9781 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
9782 return 1;
9783#endif
9784 }
9785 data.out = stdout;
drh8682e122018-01-07 20:38:10 +00009786 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +00009787
9788 /* Go ahead and open the database file if it already exists. If the
9789 ** file does not exist, delay opening it. This prevents empty database
9790 ** files from being created if a user mistypes the database name argument
9791 ** to the sqlite command-line tool.
9792 */
9793 if( access(data.zDbFilename, 0)==0 ){
9794 open_db(&data, 0);
9795 }
9796
9797 /* Process the initialization file if there is one. If no -init option
9798 ** is given on the command line, look for a file named ~/.sqliterc and
9799 ** try to process it.
9800 */
9801 process_sqliterc(&data,zInitFile);
9802
9803 /* Make a second pass through the command-line argument and set
9804 ** options. This second pass is delayed until after the initialization
9805 ** file is processed so that the command-line arguments will override
9806 ** settings in the initialization file.
9807 */
9808 for(i=1; i<argc; i++){
9809 char *z = argv[i];
9810 if( z[0]!='-' ) continue;
9811 if( z[1]=='-' ){ z++; }
9812 if( strcmp(z,"-init")==0 ){
9813 i++;
9814 }else if( strcmp(z,"-html")==0 ){
9815 data.mode = MODE_Html;
9816 }else if( strcmp(z,"-list")==0 ){
9817 data.mode = MODE_List;
9818 }else if( strcmp(z,"-quote")==0 ){
9819 data.mode = MODE_Quote;
9820 }else if( strcmp(z,"-line")==0 ){
9821 data.mode = MODE_Line;
9822 }else if( strcmp(z,"-column")==0 ){
9823 data.mode = MODE_Column;
9824 }else if( strcmp(z,"-csv")==0 ){
9825 data.mode = MODE_Csv;
9826 memcpy(data.colSeparator,",",2);
drh3baed312018-03-08 18:14:41 +00009827#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00009828 }else if( strcmp(z,"-zip")==0 ){
9829 data.openMode = SHELL_OPEN_ZIPFILE;
9830#endif
9831 }else if( strcmp(z,"-append")==0 ){
9832 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +00009833#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00009834 }else if( strcmp(z,"-deserialize")==0 ){
9835 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +00009836 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
9837 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +00009838#endif
drh4aafe592018-03-23 16:08:30 +00009839 }else if( strcmp(z,"-readonly")==0 ){
9840 data.openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +00009841 }else if( strcmp(z,"-ascii")==0 ){
9842 data.mode = MODE_Ascii;
9843 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
9844 SEP_Unit);
9845 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
9846 SEP_Record);
9847 }else if( strcmp(z,"-separator")==0 ){
9848 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
9849 "%s",cmdline_option_value(argc,argv,++i));
9850 }else if( strcmp(z,"-newline")==0 ){
9851 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
9852 "%s",cmdline_option_value(argc,argv,++i));
9853 }else if( strcmp(z,"-nullvalue")==0 ){
9854 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
9855 "%s",cmdline_option_value(argc,argv,++i));
9856 }else if( strcmp(z,"-header")==0 ){
9857 data.showHeader = 1;
9858 }else if( strcmp(z,"-noheader")==0 ){
9859 data.showHeader = 0;
9860 }else if( strcmp(z,"-echo")==0 ){
9861 ShellSetFlag(&data, SHFLG_Echo);
9862 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +00009863 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +00009864 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +00009865 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +00009866 }else if( strcmp(z,"-stats")==0 ){
9867 data.statsOn = 1;
9868 }else if( strcmp(z,"-scanstats")==0 ){
9869 data.scanstatsOn = 1;
9870 }else if( strcmp(z,"-backslash")==0 ){
9871 /* Undocumented command-line option: -backslash
9872 ** Causes C-style backslash escapes to be evaluated in SQL statements
9873 ** prior to sending the SQL into SQLite. Useful for injecting
9874 ** crazy bytes in the middle of SQL statements for testing and debugging.
9875 */
9876 ShellSetFlag(&data, SHFLG_Backslash);
9877 }else if( strcmp(z,"-bail")==0 ){
9878 bail_on_error = 1;
9879 }else if( strcmp(z,"-version")==0 ){
9880 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
9881 return 0;
9882 }else if( strcmp(z,"-interactive")==0 ){
9883 stdin_is_interactive = 1;
9884 }else if( strcmp(z,"-batch")==0 ){
9885 stdin_is_interactive = 0;
9886 }else if( strcmp(z,"-heap")==0 ){
9887 i++;
drh2ce15c32017-07-11 13:34:40 +00009888 }else if( strcmp(z,"-pagecache")==0 ){
9889 i+=2;
9890 }else if( strcmp(z,"-lookaside")==0 ){
9891 i+=2;
9892 }else if( strcmp(z,"-mmap")==0 ){
9893 i++;
drh50b910a2019-01-21 14:55:03 +00009894 }else if( strcmp(z,"-memtrace")==0 ){
9895 i++;
drha90d84f2018-04-18 15:21:13 +00009896#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9897 }else if( strcmp(z,"-sorterref")==0 ){
9898 i++;
9899#endif
drh2ce15c32017-07-11 13:34:40 +00009900 }else if( strcmp(z,"-vfs")==0 ){
9901 i++;
9902#ifdef SQLITE_ENABLE_VFSTRACE
9903 }else if( strcmp(z,"-vfstrace")==0 ){
9904 i++;
9905#endif
9906#ifdef SQLITE_ENABLE_MULTIPLEX
9907 }else if( strcmp(z,"-multiplex")==0 ){
9908 i++;
9909#endif
9910 }else if( strcmp(z,"-help")==0 ){
9911 usage(1);
9912 }else if( strcmp(z,"-cmd")==0 ){
9913 /* Run commands that follow -cmd first and separately from commands
9914 ** that simply appear on the command-line. This seems goofy. It would
9915 ** be better if all commands ran in the order that they appear. But
9916 ** we retain the goofy behavior for historical compatibility. */
9917 if( i==argc-1 ) break;
9918 z = cmdline_option_value(argc,argv,++i);
9919 if( z[0]=='.' ){
9920 rc = do_meta_command(z, &data);
9921 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
9922 }else{
9923 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00009924 rc = shell_exec(&data, z, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00009925 if( zErrMsg!=0 ){
9926 utf8_printf(stderr,"Error: %s\n", zErrMsg);
9927 if( bail_on_error ) return rc!=0 ? rc : 1;
9928 }else if( rc!=0 ){
9929 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
9930 if( bail_on_error ) return rc;
9931 }
9932 }
drhda57d962018-03-05 19:34:05 +00009933#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00009934 }else if( strncmp(z, "-A", 2)==0 ){
drhda57d962018-03-05 19:34:05 +00009935 if( nCmd>0 ){
9936 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
9937 " with \"%s\"\n", z);
9938 return 1;
9939 }
drhbe4ccb22018-05-17 20:04:24 +00009940 open_db(&data, OPEN_DB_ZIPFILE);
drh93b77312018-03-05 20:20:22 +00009941 if( z[2] ){
9942 argv[i] = &z[2];
drhd0f9cdc2018-05-17 14:09:06 +00009943 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
drh93b77312018-03-05 20:20:22 +00009944 }else{
drhd0f9cdc2018-05-17 14:09:06 +00009945 arDotCommand(&data, 1, argv+i, argc-i);
drh93b77312018-03-05 20:20:22 +00009946 }
drhda57d962018-03-05 19:34:05 +00009947 readStdin = 0;
9948 break;
9949#endif
drh2ce15c32017-07-11 13:34:40 +00009950 }else{
9951 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
9952 raw_printf(stderr,"Use -help for a list of options.\n");
9953 return 1;
9954 }
9955 data.cMode = data.mode;
9956 }
9957
9958 if( !readStdin ){
9959 /* Run all arguments that do not begin with '-' as if they were separate
9960 ** command-line inputs, except for the argToSkip argument which contains
9961 ** the database filename.
9962 */
9963 for(i=0; i<nCmd; i++){
9964 if( azCmd[i][0]=='.' ){
9965 rc = do_meta_command(azCmd[i], &data);
9966 if( rc ) return rc==2 ? 0 : rc;
9967 }else{
9968 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00009969 rc = shell_exec(&data, azCmd[i], &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00009970 if( zErrMsg!=0 ){
9971 utf8_printf(stderr,"Error: %s\n", zErrMsg);
9972 return rc!=0 ? rc : 1;
9973 }else if( rc!=0 ){
9974 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
9975 return rc;
9976 }
9977 }
9978 }
9979 free(azCmd);
9980 }else{
9981 /* Run commands received from standard input
9982 */
9983 if( stdin_is_interactive ){
9984 char *zHome;
drha9e4be32018-10-10 18:56:40 +00009985 char *zHistory;
drh2ce15c32017-07-11 13:34:40 +00009986 int nHistory;
9987 printf(
9988 "SQLite version %s %.19s\n" /*extra-version-info*/
9989 "Enter \".help\" for usage hints.\n",
9990 sqlite3_libversion(), sqlite3_sourceid()
9991 );
9992 if( warnInmemoryDb ){
9993 printf("Connected to a ");
9994 printBold("transient in-memory database");
9995 printf(".\nUse \".open FILENAME\" to reopen on a "
9996 "persistent database.\n");
9997 }
drha9e4be32018-10-10 18:56:40 +00009998 zHistory = getenv("SQLITE_HISTORY");
9999 if( zHistory ){
10000 zHistory = strdup(zHistory);
10001 }else if( (zHome = find_home_dir(0))!=0 ){
drh2ce15c32017-07-11 13:34:40 +000010002 nHistory = strlen30(zHome) + 20;
10003 if( (zHistory = malloc(nHistory))!=0 ){
10004 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
10005 }
10006 }
10007 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +000010008#if HAVE_READLINE || HAVE_EDITLINE
10009 rl_attempted_completion_function = readline_completion;
10010#elif HAVE_LINENOISE
10011 linenoiseSetCompletionCallback(linenoise_completion);
10012#endif
drh60379d42018-12-13 18:30:01 +000010013 data.in = 0;
10014 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +000010015 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +000010016 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +000010017 shell_write_history(zHistory);
10018 free(zHistory);
10019 }
10020 }else{
drh60379d42018-12-13 18:30:01 +000010021 data.in = stdin;
10022 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +000010023 }
10024 }
10025 set_table_name(&data, 0);
10026 if( data.db ){
10027 session_close_all(&data);
drh9e804032018-05-18 17:11:50 +000010028 close_db(data.db);
drh2ce15c32017-07-11 13:34:40 +000010029 }
10030 sqlite3_free(data.zFreeOnClose);
10031 find_home_dir(1);
drh536c3452018-01-11 00:38:39 +000010032 output_reset(&data);
10033 data.doXdgOpen = 0;
drh13c20932018-01-10 21:41:55 +000010034 clearTempFile(&data);
drh2ce15c32017-07-11 13:34:40 +000010035#if !SQLITE_SHELL_IS_UTF8
drh1f22f622018-05-17 13:29:14 +000010036 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
10037 free(argvToFree);
drh2ce15c32017-07-11 13:34:40 +000010038#endif
drh9e804032018-05-18 17:11:50 +000010039 /* Clear the global data structure so that valgrind will detect memory
10040 ** leaks */
10041 memset(&data, 0, sizeof(data));
drh2ce15c32017-07-11 13:34:40 +000010042 return rc;
10043}