blob: c7d94dbee810d3644aaf220f7e773ed891c9291c [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
951#if defined(SQLITE_ENABLE_SESSION)
952/*
953** State information for a single open session
954*/
955typedef struct OpenSession OpenSession;
956struct OpenSession {
957 char *zName; /* Symbolic name for this session */
958 int nFilter; /* Number of xFilter rejection GLOB patterns */
959 char **azFilter; /* Array of xFilter rejection GLOB patterns */
960 sqlite3_session *p; /* The open session */
961};
962#endif
963
964/*
965** Shell output mode information from before ".explain on",
966** saved so that it can be restored by ".explain off"
967*/
968typedef struct SavedModeInfo SavedModeInfo;
969struct SavedModeInfo {
970 int valid; /* Is there legit data in here? */
971 int mode; /* Mode prior to ".explain on" */
972 int showHeader; /* The ".header" setting prior to ".explain on" */
973 int colWidth[100]; /* Column widths prior to ".explain on" */
974};
975
dan43efc182017-12-19 17:42:13 +0000976typedef struct ExpertInfo ExpertInfo;
977struct ExpertInfo {
978 sqlite3expert *pExpert;
979 int bVerbose;
980};
981
drh4b5345c2018-04-24 13:07:40 +0000982/* A single line in the EQP output */
983typedef struct EQPGraphRow EQPGraphRow;
984struct EQPGraphRow {
drhe2ca99c2018-05-02 00:33:43 +0000985 int iEqpId; /* ID for this row */
986 int iParentId; /* ID of the parent row */
drh4b5345c2018-04-24 13:07:40 +0000987 EQPGraphRow *pNext; /* Next row in sequence */
988 char zText[1]; /* Text to display for this row */
989};
990
991/* All EQP output is collected into an instance of the following */
992typedef struct EQPGraph EQPGraph;
993struct EQPGraph {
994 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
995 EQPGraphRow *pLast; /* Last element of the pRow list */
996 char zPrefix[100]; /* Graph prefix */
997};
998
drh2ce15c32017-07-11 13:34:40 +0000999/*
1000** State information about the database connection is contained in an
1001** instance of the following structure.
1002*/
1003typedef struct ShellState ShellState;
1004struct ShellState {
1005 sqlite3 *db; /* The database */
drh1fa6d9f2018-01-06 21:46:01 +00001006 u8 autoExplain; /* Automatically turn on .explain mode */
1007 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
drhe2ca99c2018-05-02 00:33:43 +00001008 u8 autoEQPtest; /* autoEQP is in test mode */
drhb4e50392019-01-26 15:40:04 +00001009 u8 autoEQPtrace; /* autoEQP is in trace mode */
drh1fa6d9f2018-01-06 21:46:01 +00001010 u8 statsOn; /* True to display memory stats before each finalize */
1011 u8 scanstatsOn; /* True to display scan stats before each finalize */
1012 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
drh13c20932018-01-10 21:41:55 +00001013 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
drh4b5345c2018-04-24 13:07:40 +00001014 u8 nEqpLevel; /* Depth of the EQP output graph */
drh707821f2018-12-05 13:39:06 +00001015 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
drh4b5345c2018-04-24 13:07:40 +00001016 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
drh2ce15c32017-07-11 13:34:40 +00001017 int outCount; /* Revert to stdout when reaching zero */
1018 int cnt; /* Number of records displayed so far */
drh2c8ee022018-12-13 18:59:30 +00001019 int lineno; /* Line number of last line read from in */
drh60379d42018-12-13 18:30:01 +00001020 FILE *in; /* Read commands from this stream */
drh2ce15c32017-07-11 13:34:40 +00001021 FILE *out; /* Write results here */
1022 FILE *traceOut; /* Output for sqlite3_trace() */
1023 int nErr; /* Number of errors seen */
1024 int mode; /* An output mode setting */
drh3c484e82018-01-10 22:27:21 +00001025 int modePrior; /* Saved mode */
drh2ce15c32017-07-11 13:34:40 +00001026 int cMode; /* temporary output mode for the current query */
1027 int normalMode; /* Output mode before ".explain on" */
1028 int writableSchema; /* True if PRAGMA writable_schema=ON */
1029 int showHeader; /* True to show column names in List or Column mode */
1030 int nCheck; /* Number of ".check" commands run */
drh3f83f592019-02-04 14:53:18 +00001031 unsigned nProgress; /* Number of progress callbacks encountered */
1032 unsigned mxProgress; /* Maximum progress callbacks before failing */
1033 unsigned flgProgress; /* Flags for the progress callback */
drh2ce15c32017-07-11 13:34:40 +00001034 unsigned shellFlgs; /* Various flags */
drh6ca64482019-01-22 16:06:20 +00001035 sqlite3_int64 szMax; /* --maxsize argument to .open */
drh2ce15c32017-07-11 13:34:40 +00001036 char *zDestTable; /* Name of destination table when MODE_Insert */
drh13c20932018-01-10 21:41:55 +00001037 char *zTempFile; /* Temporary file that might need deleting */
drh2ce15c32017-07-11 13:34:40 +00001038 char zTestcase[30]; /* Name of current test case */
1039 char colSeparator[20]; /* Column separator character for several modes */
1040 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drh3c484e82018-01-10 22:27:21 +00001041 char colSepPrior[20]; /* Saved column separator */
1042 char rowSepPrior[20]; /* Saved row separator */
drh2ce15c32017-07-11 13:34:40 +00001043 int colWidth[100]; /* Requested width of each column when in column mode*/
1044 int actualWidth[100]; /* Actual width of each column */
1045 char nullValue[20]; /* The text to print when a NULL comes back from
1046 ** the database */
1047 char outfile[FILENAME_MAX]; /* Filename for *out */
1048 const char *zDbFilename; /* name of the database file */
1049 char *zFreeOnClose; /* Filename to free when closing */
1050 const char *zVfs; /* Name of VFS to use */
1051 sqlite3_stmt *pStmt; /* Current statement if any. */
1052 FILE *pLog; /* Write log output here */
1053 int *aiIndent; /* Array of indents used in MODE_Explain */
1054 int nIndent; /* Size of array aiIndent[] */
1055 int iIndent; /* Index of current op in aiIndent[] */
drh4b5345c2018-04-24 13:07:40 +00001056 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
drh2ce15c32017-07-11 13:34:40 +00001057#if defined(SQLITE_ENABLE_SESSION)
1058 int nSession; /* Number of active sessions */
1059 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1060#endif
dan43efc182017-12-19 17:42:13 +00001061 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
drh2ce15c32017-07-11 13:34:40 +00001062};
1063
drh1fa6d9f2018-01-06 21:46:01 +00001064
drhada70452017-12-21 21:02:27 +00001065/* Allowed values for ShellState.autoEQP
1066*/
drhe2ca99c2018-05-02 00:33:43 +00001067#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1068#define AUTOEQP_on 1 /* Automatic EQP is on */
1069#define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1070#define AUTOEQP_full 3 /* Show full EXPLAIN */
drhada70452017-12-21 21:02:27 +00001071
drh1fa6d9f2018-01-06 21:46:01 +00001072/* Allowed values for ShellState.openMode
1073*/
drh60f34ae2018-10-30 13:19:49 +00001074#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1075#define SHELL_OPEN_NORMAL 1 /* Normal database file */
1076#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1077#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1078#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1079#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
drh33746482018-12-13 15:06:26 +00001080#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
drh1fa6d9f2018-01-06 21:46:01 +00001081
drh707821f2018-12-05 13:39:06 +00001082/* Allowed values for ShellState.eTraceType
1083*/
1084#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1085#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1086#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1087
drh3f83f592019-02-04 14:53:18 +00001088/* Bits in the ShellState.flgProgress variable */
drhfc4eeef2019-02-05 19:48:46 +00001089#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1090#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1091 ** callback limit is reached, and for each
1092 ** top-level SQL statement */
1093#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
drh3f83f592019-02-04 14:53:18 +00001094
drh2ce15c32017-07-11 13:34:40 +00001095/*
1096** These are the allowed shellFlgs values
1097*/
drhb2a0f752017-08-28 15:51:35 +00001098#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1099#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1100#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1101#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1102#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1103#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1104#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
drh2ce15c32017-07-11 13:34:40 +00001105
1106/*
1107** Macros for testing and setting shellFlgs
1108*/
1109#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1110#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1111#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1112
1113/*
1114** These are the allowed modes.
1115*/
1116#define MODE_Line 0 /* One column per line. Blank line between records */
1117#define MODE_Column 1 /* One record per line in neat columns */
1118#define MODE_List 2 /* One record per line with a separator */
1119#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1120#define MODE_Html 4 /* Generate an XHTML table */
1121#define MODE_Insert 5 /* Generate SQL "insert" statements */
1122#define MODE_Quote 6 /* Quote values as for SQL */
1123#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1124#define MODE_Csv 8 /* Quote strings, numbers are plain */
1125#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1126#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1127#define MODE_Pretty 11 /* Pretty-print schemas */
drh4b5345c2018-04-24 13:07:40 +00001128#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
drh2ce15c32017-07-11 13:34:40 +00001129
1130static const char *modeDescr[] = {
1131 "line",
1132 "column",
1133 "list",
1134 "semi",
1135 "html",
1136 "insert",
1137 "quote",
1138 "tcl",
1139 "csv",
1140 "explain",
1141 "ascii",
1142 "prettyprint",
drh4b5345c2018-04-24 13:07:40 +00001143 "eqp"
drh2ce15c32017-07-11 13:34:40 +00001144};
1145
1146/*
1147** These are the column/row/line separators used by the various
1148** import/export modes.
1149*/
1150#define SEP_Column "|"
1151#define SEP_Row "\n"
1152#define SEP_Tab "\t"
1153#define SEP_Space " "
1154#define SEP_Comma ","
1155#define SEP_CrLf "\r\n"
1156#define SEP_Unit "\x1F"
1157#define SEP_Record "\x1E"
1158
1159/*
drh2ce15c32017-07-11 13:34:40 +00001160** A callback for the sqlite3_log() interface.
1161*/
1162static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1163 ShellState *p = (ShellState*)pArg;
1164 if( p->pLog==0 ) return;
1165 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1166 fflush(p->pLog);
1167}
1168
1169/*
drh634c70f2018-01-10 16:50:18 +00001170** SQL function: shell_putsnl(X)
1171**
1172** Write the text X to the screen (or whatever output is being directed)
1173** adding a newline at the end, and then return X.
1174*/
1175static void shellPutsFunc(
1176 sqlite3_context *pCtx,
1177 int nVal,
1178 sqlite3_value **apVal
1179){
1180 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
drhb9685182018-01-17 13:15:23 +00001181 (void)nVal;
drh634c70f2018-01-10 16:50:18 +00001182 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1183 sqlite3_result_value(pCtx, apVal[0]);
1184}
1185
1186/*
drh97913132018-01-11 00:04:00 +00001187** SQL function: edit(VALUE)
1188** edit(VALUE,EDITOR)
1189**
1190** These steps:
1191**
1192** (1) Write VALUE into a temporary file.
1193** (2) Run program EDITOR on that temporary file.
1194** (3) Read the temporary file back and return its content as the result.
1195** (4) Delete the temporary file
1196**
1197** If the EDITOR argument is omitted, use the value in the VISUAL
1198** environment variable. If still there is no EDITOR, through an error.
1199**
1200** Also throw an error if the EDITOR program returns a non-zero exit code.
1201*/
drh04a28c32018-01-31 01:38:44 +00001202#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00001203static void editFunc(
1204 sqlite3_context *context,
1205 int argc,
1206 sqlite3_value **argv
1207){
1208 const char *zEditor;
1209 char *zTempFile = 0;
1210 sqlite3 *db;
1211 char *zCmd = 0;
1212 int bBin;
1213 int rc;
drhf018fd52018-08-06 02:08:53 +00001214 int hasCRNL = 0;
drh97913132018-01-11 00:04:00 +00001215 FILE *f = 0;
1216 sqlite3_int64 sz;
1217 sqlite3_int64 x;
1218 unsigned char *p = 0;
1219
1220 if( argc==2 ){
1221 zEditor = (const char*)sqlite3_value_text(argv[1]);
1222 }else{
1223 zEditor = getenv("VISUAL");
1224 }
1225 if( zEditor==0 ){
1226 sqlite3_result_error(context, "no editor for edit()", -1);
1227 return;
1228 }
1229 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1230 sqlite3_result_error(context, "NULL input to edit()", -1);
1231 return;
1232 }
1233 db = sqlite3_context_db_handle(context);
1234 zTempFile = 0;
1235 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1236 if( zTempFile==0 ){
1237 sqlite3_uint64 r = 0;
1238 sqlite3_randomness(sizeof(r), &r);
1239 zTempFile = sqlite3_mprintf("temp%llx", r);
1240 if( zTempFile==0 ){
1241 sqlite3_result_error_nomem(context);
1242 return;
1243 }
1244 }
1245 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
drhf018fd52018-08-06 02:08:53 +00001246 /* When writing the file to be edited, do \n to \r\n conversions on systems
1247 ** that want \r\n line endings */
drh97913132018-01-11 00:04:00 +00001248 f = fopen(zTempFile, bBin ? "wb" : "w");
1249 if( f==0 ){
1250 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1251 goto edit_func_end;
1252 }
1253 sz = sqlite3_value_bytes(argv[0]);
1254 if( bBin ){
1255 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
1256 }else{
drhf018fd52018-08-06 02:08:53 +00001257 const char *z = (const char*)sqlite3_value_text(argv[0]);
1258 /* Remember whether or not the value originally contained \r\n */
1259 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
drh97913132018-01-11 00:04:00 +00001260 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
1261 }
1262 fclose(f);
1263 f = 0;
1264 if( x!=sz ){
1265 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1266 goto edit_func_end;
1267 }
1268 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1269 if( zCmd==0 ){
1270 sqlite3_result_error_nomem(context);
1271 goto edit_func_end;
1272 }
1273 rc = system(zCmd);
1274 sqlite3_free(zCmd);
1275 if( rc ){
1276 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1277 goto edit_func_end;
1278 }
drhf018fd52018-08-06 02:08:53 +00001279 f = fopen(zTempFile, "rb");
drh97913132018-01-11 00:04:00 +00001280 if( f==0 ){
1281 sqlite3_result_error(context,
1282 "edit() cannot reopen temp file after edit", -1);
1283 goto edit_func_end;
1284 }
1285 fseek(f, 0, SEEK_END);
1286 sz = ftell(f);
1287 rewind(f);
1288 p = sqlite3_malloc64( sz+(bBin==0) );
1289 if( p==0 ){
1290 sqlite3_result_error_nomem(context);
1291 goto edit_func_end;
1292 }
drhf018fd52018-08-06 02:08:53 +00001293 x = fread(p, 1, sz, f);
drh97913132018-01-11 00:04:00 +00001294 fclose(f);
1295 f = 0;
1296 if( x!=sz ){
1297 sqlite3_result_error(context, "could not read back the whole file", -1);
1298 goto edit_func_end;
1299 }
1300 if( bBin ){
mistachkinb71aa092018-01-23 00:05:18 +00001301 sqlite3_result_blob64(context, p, sz, sqlite3_free);
drh97913132018-01-11 00:04:00 +00001302 }else{
dan60bdcf52018-10-03 11:13:30 +00001303 sqlite3_int64 i, j;
drhf018fd52018-08-06 02:08:53 +00001304 if( hasCRNL ){
1305 /* If the original contains \r\n then do no conversions back to \n */
1306 j = sz;
1307 }else{
1308 /* If the file did not originally contain \r\n then convert any new
1309 ** \r\n back into \n */
1310 for(i=j=0; i<sz; i++){
1311 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1312 p[j++] = p[i];
1313 }
1314 sz = j;
1315 p[sz] = 0;
1316 }
mistachkinb71aa092018-01-23 00:05:18 +00001317 sqlite3_result_text64(context, (const char*)p, sz,
1318 sqlite3_free, SQLITE_UTF8);
drh97913132018-01-11 00:04:00 +00001319 }
1320 p = 0;
1321
1322edit_func_end:
1323 if( f ) fclose(f);
1324 unlink(zTempFile);
1325 sqlite3_free(zTempFile);
1326 sqlite3_free(p);
1327}
drh04a28c32018-01-31 01:38:44 +00001328#endif /* SQLITE_NOHAVE_SYSTEM */
drh97913132018-01-11 00:04:00 +00001329
1330/*
drh3c484e82018-01-10 22:27:21 +00001331** Save or restore the current output mode
1332*/
1333static void outputModePush(ShellState *p){
1334 p->modePrior = p->mode;
1335 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1336 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1337}
1338static void outputModePop(ShellState *p){
1339 p->mode = p->modePrior;
1340 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1341 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1342}
1343
1344/*
drh2ce15c32017-07-11 13:34:40 +00001345** Output the given string as a hex-encoded blob (eg. X'1234' )
1346*/
1347static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1348 int i;
1349 char *zBlob = (char *)pBlob;
1350 raw_printf(out,"X'");
1351 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1352 raw_printf(out,"'");
1353}
1354
1355/*
1356** Find a string that is not found anywhere in z[]. Return a pointer
1357** to that string.
1358**
1359** Try to use zA and zB first. If both of those are already found in z[]
1360** then make up some string and store it in the buffer zBuf.
1361*/
1362static const char *unused_string(
1363 const char *z, /* Result must not appear anywhere in z */
1364 const char *zA, const char *zB, /* Try these first */
1365 char *zBuf /* Space to store a generated string */
1366){
1367 unsigned i = 0;
1368 if( strstr(z, zA)==0 ) return zA;
1369 if( strstr(z, zB)==0 ) return zB;
1370 do{
1371 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1372 }while( strstr(z,zBuf)!=0 );
1373 return zBuf;
1374}
1375
1376/*
1377** Output the given string as a quoted string using SQL quoting conventions.
1378**
1379** See also: output_quoted_escaped_string()
1380*/
1381static void output_quoted_string(FILE *out, const char *z){
1382 int i;
1383 char c;
1384 setBinaryMode(out, 1);
1385 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1386 if( c==0 ){
1387 utf8_printf(out,"'%s'",z);
1388 }else{
1389 raw_printf(out, "'");
1390 while( *z ){
1391 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1392 if( c=='\'' ) i++;
1393 if( i ){
1394 utf8_printf(out, "%.*s", i, z);
1395 z += i;
1396 }
1397 if( c=='\'' ){
1398 raw_printf(out, "'");
1399 continue;
1400 }
1401 if( c==0 ){
1402 break;
1403 }
1404 z++;
1405 }
1406 raw_printf(out, "'");
1407 }
1408 setTextMode(out, 1);
1409}
1410
1411/*
1412** Output the given string as a quoted string using SQL quoting conventions.
1413** Additionallly , escape the "\n" and "\r" characters so that they do not
1414** get corrupted by end-of-line translation facilities in some operating
1415** systems.
1416**
1417** This is like output_quoted_string() but with the addition of the \r\n
1418** escape mechanism.
1419*/
1420static void output_quoted_escaped_string(FILE *out, const char *z){
1421 int i;
1422 char c;
1423 setBinaryMode(out, 1);
1424 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1425 if( c==0 ){
1426 utf8_printf(out,"'%s'",z);
1427 }else{
1428 const char *zNL = 0;
1429 const char *zCR = 0;
1430 int nNL = 0;
1431 int nCR = 0;
1432 char zBuf1[20], zBuf2[20];
1433 for(i=0; z[i]; i++){
1434 if( z[i]=='\n' ) nNL++;
1435 if( z[i]=='\r' ) nCR++;
1436 }
1437 if( nNL ){
1438 raw_printf(out, "replace(");
1439 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1440 }
1441 if( nCR ){
1442 raw_printf(out, "replace(");
1443 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1444 }
1445 raw_printf(out, "'");
1446 while( *z ){
1447 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1448 if( c=='\'' ) i++;
1449 if( i ){
1450 utf8_printf(out, "%.*s", i, z);
1451 z += i;
1452 }
1453 if( c=='\'' ){
1454 raw_printf(out, "'");
1455 continue;
1456 }
1457 if( c==0 ){
1458 break;
1459 }
1460 z++;
1461 if( c=='\n' ){
1462 raw_printf(out, "%s", zNL);
1463 continue;
1464 }
1465 raw_printf(out, "%s", zCR);
1466 }
1467 raw_printf(out, "'");
1468 if( nCR ){
1469 raw_printf(out, ",'%s',char(13))", zCR);
1470 }
1471 if( nNL ){
1472 raw_printf(out, ",'%s',char(10))", zNL);
1473 }
1474 }
1475 setTextMode(out, 1);
1476}
1477
1478/*
1479** Output the given string as a quoted according to C or TCL quoting rules.
1480*/
1481static void output_c_string(FILE *out, const char *z){
1482 unsigned int c;
1483 fputc('"', out);
1484 while( (c = *(z++))!=0 ){
1485 if( c=='\\' ){
1486 fputc(c, out);
1487 fputc(c, out);
1488 }else if( c=='"' ){
1489 fputc('\\', out);
1490 fputc('"', out);
1491 }else if( c=='\t' ){
1492 fputc('\\', out);
1493 fputc('t', out);
1494 }else if( c=='\n' ){
1495 fputc('\\', out);
1496 fputc('n', out);
1497 }else if( c=='\r' ){
1498 fputc('\\', out);
1499 fputc('r', out);
1500 }else if( !isprint(c&0xff) ){
1501 raw_printf(out, "\\%03o", c&0xff);
1502 }else{
1503 fputc(c, out);
1504 }
1505 }
1506 fputc('"', out);
1507}
1508
1509/*
1510** Output the given string with characters that are special to
1511** HTML escaped.
1512*/
1513static void output_html_string(FILE *out, const char *z){
1514 int i;
1515 if( z==0 ) z = "";
1516 while( *z ){
1517 for(i=0; z[i]
1518 && z[i]!='<'
1519 && z[i]!='&'
1520 && z[i]!='>'
1521 && z[i]!='\"'
1522 && z[i]!='\'';
1523 i++){}
1524 if( i>0 ){
1525 utf8_printf(out,"%.*s",i,z);
1526 }
1527 if( z[i]=='<' ){
1528 raw_printf(out,"&lt;");
1529 }else if( z[i]=='&' ){
1530 raw_printf(out,"&amp;");
1531 }else if( z[i]=='>' ){
1532 raw_printf(out,"&gt;");
1533 }else if( z[i]=='\"' ){
1534 raw_printf(out,"&quot;");
1535 }else if( z[i]=='\'' ){
1536 raw_printf(out,"&#39;");
1537 }else{
1538 break;
1539 }
1540 z += i + 1;
1541 }
1542}
1543
1544/*
1545** If a field contains any character identified by a 1 in the following
1546** array, then the string must be quoted for CSV.
1547*/
1548static const char needCsvQuote[] = {
1549 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1550 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1551 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1552 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1553 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1554 0, 0, 0, 0, 0, 0, 0, 0, 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, 1,
1557 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1558 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1559 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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};
1566
1567/*
1568** Output a single term of CSV. Actually, p->colSeparator is used for
1569** the separator, which may or may not be a comma. p->nullValue is
1570** the null value. Strings are quoted if necessary. The separator
1571** is only issued if bSep is true.
1572*/
1573static void output_csv(ShellState *p, const char *z, int bSep){
1574 FILE *out = p->out;
1575 if( z==0 ){
1576 utf8_printf(out,"%s",p->nullValue);
1577 }else{
1578 int i;
1579 int nSep = strlen30(p->colSeparator);
1580 for(i=0; z[i]; i++){
1581 if( needCsvQuote[((unsigned char*)z)[i]]
1582 || (z[i]==p->colSeparator[0] &&
1583 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1584 i = 0;
1585 break;
1586 }
1587 }
1588 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001589 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1590 utf8_printf(out, "%s", zQuoted);
1591 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001592 }else{
1593 utf8_printf(out, "%s", z);
1594 }
1595 }
1596 if( bSep ){
1597 utf8_printf(p->out, "%s", p->colSeparator);
1598 }
1599}
1600
drh2ce15c32017-07-11 13:34:40 +00001601/*
1602** This routine runs when the user presses Ctrl-C
1603*/
1604static void interrupt_handler(int NotUsed){
1605 UNUSED_PARAMETER(NotUsed);
1606 seenInterrupt++;
1607 if( seenInterrupt>2 ) exit(1);
1608 if( globalDb ) sqlite3_interrupt(globalDb);
1609}
mistachkinb4bab902017-10-27 17:09:44 +00001610
1611#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1612/*
1613** This routine runs for console events (e.g. Ctrl-C) on Win32
1614*/
1615static BOOL WINAPI ConsoleCtrlHandler(
1616 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1617){
1618 if( dwCtrlType==CTRL_C_EVENT ){
1619 interrupt_handler(0);
1620 return TRUE;
1621 }
1622 return FALSE;
1623}
drh2ce15c32017-07-11 13:34:40 +00001624#endif
1625
1626#ifndef SQLITE_OMIT_AUTHORIZATION
1627/*
1628** When the ".auth ON" is set, the following authorizer callback is
1629** invoked. It always returns SQLITE_OK.
1630*/
1631static int shellAuth(
1632 void *pClientData,
1633 int op,
1634 const char *zA1,
1635 const char *zA2,
1636 const char *zA3,
1637 const char *zA4
1638){
1639 ShellState *p = (ShellState*)pClientData;
1640 static const char *azAction[] = { 0,
1641 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1642 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1643 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1644 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1645 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1646 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1647 "PRAGMA", "READ", "SELECT",
1648 "TRANSACTION", "UPDATE", "ATTACH",
1649 "DETACH", "ALTER_TABLE", "REINDEX",
1650 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1651 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1652 };
1653 int i;
1654 const char *az[4];
1655 az[0] = zA1;
1656 az[1] = zA2;
1657 az[2] = zA3;
1658 az[3] = zA4;
1659 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1660 for(i=0; i<4; i++){
1661 raw_printf(p->out, " ");
1662 if( az[i] ){
1663 output_c_string(p->out, az[i]);
1664 }else{
1665 raw_printf(p->out, "NULL");
1666 }
1667 }
1668 raw_printf(p->out, "\n");
1669 return SQLITE_OK;
1670}
1671#endif
1672
1673/*
1674** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1675**
1676** This routine converts some CREATE TABLE statements for shadow tables
1677** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1678*/
1679static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1680 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1681 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1682 }else{
1683 utf8_printf(out, "%s%s", z, zTail);
1684 }
1685}
1686static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1687 char c = z[n];
1688 z[n] = 0;
1689 printSchemaLine(out, z, zTail);
1690 z[n] = c;
1691}
1692
1693/*
drh11be81d2018-01-06 15:46:20 +00001694** Return true if string z[] has nothing but whitespace and comments to the
1695** end of the first line.
1696*/
1697static int wsToEol(const char *z){
1698 int i;
1699 for(i=0; z[i]; i++){
1700 if( z[i]=='\n' ) return 1;
1701 if( IsSpace(z[i]) ) continue;
1702 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1703 return 0;
1704 }
1705 return 1;
1706}
drh4b5345c2018-04-24 13:07:40 +00001707
1708/*
1709** Add a new entry to the EXPLAIN QUERY PLAN data
1710*/
drhe2ca99c2018-05-02 00:33:43 +00001711static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
drh4b5345c2018-04-24 13:07:40 +00001712 EQPGraphRow *pNew;
1713 int nText = strlen30(zText);
drhe2ca99c2018-05-02 00:33:43 +00001714 if( p->autoEQPtest ){
1715 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1716 }
drh4b5345c2018-04-24 13:07:40 +00001717 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1718 if( pNew==0 ) shell_out_of_memory();
drhe2ca99c2018-05-02 00:33:43 +00001719 pNew->iEqpId = iEqpId;
1720 pNew->iParentId = p2;
drh4b5345c2018-04-24 13:07:40 +00001721 memcpy(pNew->zText, zText, nText+1);
1722 pNew->pNext = 0;
1723 if( p->sGraph.pLast ){
1724 p->sGraph.pLast->pNext = pNew;
1725 }else{
1726 p->sGraph.pRow = pNew;
1727 }
1728 p->sGraph.pLast = pNew;
1729}
1730
1731/*
1732** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1733** in p->sGraph.
1734*/
1735static void eqp_reset(ShellState *p){
1736 EQPGraphRow *pRow, *pNext;
1737 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1738 pNext = pRow->pNext;
1739 sqlite3_free(pRow);
1740 }
1741 memset(&p->sGraph, 0, sizeof(p->sGraph));
1742}
1743
drhe2ca99c2018-05-02 00:33:43 +00001744/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
drh4b5345c2018-04-24 13:07:40 +00001745** pOld, or return the first such line if pOld is NULL
1746*/
drhe2ca99c2018-05-02 00:33:43 +00001747static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
drh4b5345c2018-04-24 13:07:40 +00001748 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
drhe2ca99c2018-05-02 00:33:43 +00001749 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
drh4b5345c2018-04-24 13:07:40 +00001750 return pRow;
1751}
1752
drhe2ca99c2018-05-02 00:33:43 +00001753/* Render a single level of the graph that has iEqpId as its parent. Called
drh4b5345c2018-04-24 13:07:40 +00001754** recursively to render sublevels.
1755*/
drhe2ca99c2018-05-02 00:33:43 +00001756static void eqp_render_level(ShellState *p, int iEqpId){
drh4b5345c2018-04-24 13:07:40 +00001757 EQPGraphRow *pRow, *pNext;
drh4b5345c2018-04-24 13:07:40 +00001758 int n = strlen30(p->sGraph.zPrefix);
1759 char *z;
drhe2ca99c2018-05-02 00:33:43 +00001760 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1761 pNext = eqp_next_row(p, iEqpId, pRow);
drh4b5345c2018-04-24 13:07:40 +00001762 z = pRow->zText;
1763 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
drhe2188f02018-05-07 11:37:34 +00001764 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
drh4b5345c2018-04-24 13:07:40 +00001765 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
drhe2ca99c2018-05-02 00:33:43 +00001766 eqp_render_level(p, pRow->iEqpId);
drh4b5345c2018-04-24 13:07:40 +00001767 p->sGraph.zPrefix[n] = 0;
1768 }
1769 }
1770}
1771
1772/*
1773** Display and reset the EXPLAIN QUERY PLAN data
1774*/
1775static void eqp_render(ShellState *p){
1776 EQPGraphRow *pRow = p->sGraph.pRow;
1777 if( pRow ){
1778 if( pRow->zText[0]=='-' ){
1779 if( pRow->pNext==0 ){
1780 eqp_reset(p);
1781 return;
1782 }
1783 utf8_printf(p->out, "%s\n", pRow->zText+3);
1784 p->sGraph.pRow = pRow->pNext;
1785 sqlite3_free(pRow);
1786 }else{
1787 utf8_printf(p->out, "QUERY PLAN\n");
1788 }
1789 p->sGraph.zPrefix[0] = 0;
1790 eqp_render_level(p, 0);
1791 eqp_reset(p);
1792 }
1793}
drh11be81d2018-01-06 15:46:20 +00001794
drh569b1d92019-02-05 20:51:41 +00001795#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh11be81d2018-01-06 15:46:20 +00001796/*
drh3f83f592019-02-04 14:53:18 +00001797** Progress handler callback.
1798*/
1799static int progress_handler(void *pClientData) {
1800 ShellState *p = (ShellState*)pClientData;
1801 p->nProgress++;
1802 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1803 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
drhfc4eeef2019-02-05 19:48:46 +00001804 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
1805 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
drh3f83f592019-02-04 14:53:18 +00001806 return 1;
1807 }
drhfc4eeef2019-02-05 19:48:46 +00001808 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
drh3f83f592019-02-04 14:53:18 +00001809 raw_printf(p->out, "Progress %u\n", p->nProgress);
1810 }
1811 return 0;
1812}
drh569b1d92019-02-05 20:51:41 +00001813#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00001814
1815/*
drh2ce15c32017-07-11 13:34:40 +00001816** This is the callback routine that the shell
1817** invokes for each row of a query result.
1818*/
1819static int shell_callback(
1820 void *pArg,
1821 int nArg, /* Number of result columns */
1822 char **azArg, /* Text of each result column */
1823 char **azCol, /* Column names */
1824 int *aiType /* Column types */
1825){
1826 int i;
1827 ShellState *p = (ShellState*)pArg;
1828
drhb3c45232017-08-28 14:33:27 +00001829 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001830 switch( p->cMode ){
1831 case MODE_Line: {
1832 int w = 5;
1833 if( azArg==0 ) break;
1834 for(i=0; i<nArg; i++){
1835 int len = strlen30(azCol[i] ? azCol[i] : "");
1836 if( len>w ) w = len;
1837 }
1838 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1839 for(i=0; i<nArg; i++){
1840 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1841 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1842 }
1843 break;
1844 }
1845 case MODE_Explain:
1846 case MODE_Column: {
1847 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1848 const int *colWidth;
1849 int showHdr;
1850 char *rowSep;
1851 if( p->cMode==MODE_Column ){
1852 colWidth = p->colWidth;
1853 showHdr = p->showHeader;
1854 rowSep = p->rowSeparator;
1855 }else{
1856 colWidth = aExplainWidths;
1857 showHdr = 1;
1858 rowSep = SEP_Row;
1859 }
1860 if( p->cnt++==0 ){
1861 for(i=0; i<nArg; i++){
1862 int w, n;
1863 if( i<ArraySize(p->colWidth) ){
1864 w = colWidth[i];
1865 }else{
1866 w = 0;
1867 }
1868 if( w==0 ){
1869 w = strlenChar(azCol[i] ? azCol[i] : "");
1870 if( w<10 ) w = 10;
1871 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1872 if( w<n ) w = n;
1873 }
1874 if( i<ArraySize(p->actualWidth) ){
1875 p->actualWidth[i] = w;
1876 }
1877 if( showHdr ){
1878 utf8_width_print(p->out, w, azCol[i]);
1879 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1880 }
1881 }
1882 if( showHdr ){
1883 for(i=0; i<nArg; i++){
1884 int w;
1885 if( i<ArraySize(p->actualWidth) ){
1886 w = p->actualWidth[i];
1887 if( w<0 ) w = -w;
1888 }else{
1889 w = 10;
1890 }
1891 utf8_printf(p->out,"%-*.*s%s",w,w,
1892 "----------------------------------------------------------"
1893 "----------------------------------------------------------",
1894 i==nArg-1 ? rowSep : " ");
1895 }
1896 }
1897 }
1898 if( azArg==0 ) break;
1899 for(i=0; i<nArg; i++){
1900 int w;
1901 if( i<ArraySize(p->actualWidth) ){
1902 w = p->actualWidth[i];
1903 }else{
1904 w = 10;
1905 }
1906 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1907 w = strlenChar(azArg[i]);
1908 }
1909 if( i==1 && p->aiIndent && p->pStmt ){
1910 if( p->iIndent<p->nIndent ){
1911 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1912 }
1913 p->iIndent++;
1914 }
1915 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1916 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1917 }
1918 break;
1919 }
1920 case MODE_Semi: { /* .schema and .fullschema output */
1921 printSchemaLine(p->out, azArg[0], ";\n");
1922 break;
1923 }
1924 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1925 char *z;
1926 int j;
1927 int nParen = 0;
1928 char cEnd = 0;
1929 char c;
1930 int nLine = 0;
1931 assert( nArg==1 );
1932 if( azArg[0]==0 ) break;
1933 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1934 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1935 ){
1936 utf8_printf(p->out, "%s;\n", azArg[0]);
1937 break;
1938 }
1939 z = sqlite3_mprintf("%s", azArg[0]);
1940 j = 0;
1941 for(i=0; IsSpace(z[i]); i++){}
1942 for(; (c = z[i])!=0; i++){
1943 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001944 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001945 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1946 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1947 j--;
1948 }
1949 z[j++] = c;
1950 }
1951 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1952 z[j] = 0;
1953 if( strlen30(z)>=79 ){
drh11be81d2018-01-06 15:46:20 +00001954 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001955 if( c==cEnd ){
1956 cEnd = 0;
1957 }else if( c=='"' || c=='\'' || c=='`' ){
1958 cEnd = c;
1959 }else if( c=='[' ){
1960 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001961 }else if( c=='-' && z[i+1]=='-' ){
1962 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001963 }else if( c=='(' ){
1964 nParen++;
1965 }else if( c==')' ){
1966 nParen--;
1967 if( nLine>0 && nParen==0 && j>0 ){
1968 printSchemaLineN(p->out, z, j, "\n");
1969 j = 0;
1970 }
1971 }
1972 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001973 if( nParen==1 && cEnd==0
1974 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1975 ){
drh2ce15c32017-07-11 13:34:40 +00001976 if( c=='\n' ) j--;
1977 printSchemaLineN(p->out, z, j, "\n ");
1978 j = 0;
1979 nLine++;
1980 while( IsSpace(z[i+1]) ){ i++; }
1981 }
1982 }
1983 z[j] = 0;
1984 }
1985 printSchemaLine(p->out, z, ";\n");
1986 sqlite3_free(z);
1987 break;
1988 }
1989 case MODE_List: {
1990 if( p->cnt++==0 && p->showHeader ){
1991 for(i=0; i<nArg; i++){
1992 utf8_printf(p->out,"%s%s",azCol[i],
1993 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1994 }
1995 }
1996 if( azArg==0 ) break;
1997 for(i=0; i<nArg; i++){
1998 char *z = azArg[i];
1999 if( z==0 ) z = p->nullValue;
2000 utf8_printf(p->out, "%s", z);
2001 if( i<nArg-1 ){
2002 utf8_printf(p->out, "%s", p->colSeparator);
2003 }else{
2004 utf8_printf(p->out, "%s", p->rowSeparator);
2005 }
2006 }
2007 break;
2008 }
2009 case MODE_Html: {
2010 if( p->cnt++==0 && p->showHeader ){
2011 raw_printf(p->out,"<TR>");
2012 for(i=0; i<nArg; i++){
2013 raw_printf(p->out,"<TH>");
2014 output_html_string(p->out, azCol[i]);
2015 raw_printf(p->out,"</TH>\n");
2016 }
2017 raw_printf(p->out,"</TR>\n");
2018 }
2019 if( azArg==0 ) break;
2020 raw_printf(p->out,"<TR>");
2021 for(i=0; i<nArg; i++){
2022 raw_printf(p->out,"<TD>");
2023 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2024 raw_printf(p->out,"</TD>\n");
2025 }
2026 raw_printf(p->out,"</TR>\n");
2027 break;
2028 }
2029 case MODE_Tcl: {
2030 if( p->cnt++==0 && p->showHeader ){
2031 for(i=0; i<nArg; i++){
2032 output_c_string(p->out,azCol[i] ? azCol[i] : "");
2033 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2034 }
2035 utf8_printf(p->out, "%s", p->rowSeparator);
2036 }
2037 if( azArg==0 ) break;
2038 for(i=0; i<nArg; i++){
2039 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2040 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2041 }
2042 utf8_printf(p->out, "%s", p->rowSeparator);
2043 break;
2044 }
2045 case MODE_Csv: {
2046 setBinaryMode(p->out, 1);
2047 if( p->cnt++==0 && p->showHeader ){
2048 for(i=0; i<nArg; i++){
2049 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2050 }
2051 utf8_printf(p->out, "%s", p->rowSeparator);
2052 }
2053 if( nArg>0 ){
2054 for(i=0; i<nArg; i++){
2055 output_csv(p, azArg[i], i<nArg-1);
2056 }
2057 utf8_printf(p->out, "%s", p->rowSeparator);
2058 }
2059 setTextMode(p->out, 1);
2060 break;
2061 }
2062 case MODE_Insert: {
2063 if( azArg==0 ) break;
2064 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2065 if( p->showHeader ){
2066 raw_printf(p->out,"(");
2067 for(i=0; i<nArg; i++){
2068 if( i>0 ) raw_printf(p->out, ",");
2069 if( quoteChar(azCol[i]) ){
2070 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2071 utf8_printf(p->out, "%s", z);
2072 sqlite3_free(z);
2073 }else{
2074 raw_printf(p->out, "%s", azCol[i]);
2075 }
2076 }
2077 raw_printf(p->out,")");
2078 }
2079 p->cnt++;
2080 for(i=0; i<nArg; i++){
2081 raw_printf(p->out, i>0 ? "," : " VALUES(");
2082 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2083 utf8_printf(p->out,"NULL");
2084 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2085 if( ShellHasFlag(p, SHFLG_Newlines) ){
2086 output_quoted_string(p->out, azArg[i]);
2087 }else{
2088 output_quoted_escaped_string(p->out, azArg[i]);
2089 }
2090 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2091 utf8_printf(p->out,"%s", azArg[i]);
2092 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2093 char z[50];
2094 double r = sqlite3_column_double(p->pStmt, i);
drh2f1f8802018-06-13 17:19:20 +00002095 sqlite3_uint64 ur;
2096 memcpy(&ur,&r,sizeof(r));
2097 if( ur==0x7ff0000000000000LL ){
2098 raw_printf(p->out, "1e999");
2099 }else if( ur==0xfff0000000000000LL ){
2100 raw_printf(p->out, "-1e999");
2101 }else{
2102 sqlite3_snprintf(50,z,"%!.20g", r);
2103 raw_printf(p->out, "%s", z);
2104 }
drh2ce15c32017-07-11 13:34:40 +00002105 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2106 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2107 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2108 output_hex_blob(p->out, pBlob, nBlob);
2109 }else if( isNumber(azArg[i], 0) ){
2110 utf8_printf(p->out,"%s", azArg[i]);
2111 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2112 output_quoted_string(p->out, azArg[i]);
2113 }else{
2114 output_quoted_escaped_string(p->out, azArg[i]);
2115 }
2116 }
2117 raw_printf(p->out,");\n");
2118 break;
2119 }
2120 case MODE_Quote: {
2121 if( azArg==0 ) break;
2122 if( p->cnt==0 && p->showHeader ){
2123 for(i=0; i<nArg; i++){
2124 if( i>0 ) raw_printf(p->out, ",");
2125 output_quoted_string(p->out, azCol[i]);
2126 }
2127 raw_printf(p->out,"\n");
2128 }
2129 p->cnt++;
2130 for(i=0; i<nArg; i++){
2131 if( i>0 ) raw_printf(p->out, ",");
2132 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2133 utf8_printf(p->out,"NULL");
2134 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2135 output_quoted_string(p->out, azArg[i]);
2136 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2137 utf8_printf(p->out,"%s", azArg[i]);
2138 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2139 char z[50];
2140 double r = sqlite3_column_double(p->pStmt, i);
2141 sqlite3_snprintf(50,z,"%!.20g", r);
2142 raw_printf(p->out, "%s", z);
2143 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2144 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2145 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2146 output_hex_blob(p->out, pBlob, nBlob);
2147 }else if( isNumber(azArg[i], 0) ){
2148 utf8_printf(p->out,"%s", azArg[i]);
2149 }else{
2150 output_quoted_string(p->out, azArg[i]);
2151 }
2152 }
2153 raw_printf(p->out,"\n");
2154 break;
2155 }
2156 case MODE_Ascii: {
2157 if( p->cnt++==0 && p->showHeader ){
2158 for(i=0; i<nArg; i++){
2159 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2160 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2161 }
2162 utf8_printf(p->out, "%s", p->rowSeparator);
2163 }
2164 if( azArg==0 ) break;
2165 for(i=0; i<nArg; i++){
2166 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2167 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2168 }
2169 utf8_printf(p->out, "%s", p->rowSeparator);
2170 break;
2171 }
drh4b5345c2018-04-24 13:07:40 +00002172 case MODE_EQP: {
drhe2ca99c2018-05-02 00:33:43 +00002173 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
drh4b5345c2018-04-24 13:07:40 +00002174 break;
2175 }
drh2ce15c32017-07-11 13:34:40 +00002176 }
2177 return 0;
2178}
2179
2180/*
2181** This is the callback routine that the SQLite library
2182** invokes for each row of a query result.
2183*/
2184static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2185 /* since we don't have type info, call the shell_callback with a NULL value */
2186 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2187}
2188
2189/*
2190** This is the callback routine from sqlite3_exec() that appends all
2191** output onto the end of a ShellText object.
2192*/
2193static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2194 ShellText *p = (ShellText*)pArg;
2195 int i;
2196 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00002197 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002198 if( p->n ) appendText(p, "|", 0);
2199 for(i=0; i<nArg; i++){
2200 if( i ) appendText(p, ",", 0);
2201 if( azArg[i] ) appendText(p, azArg[i], 0);
2202 }
2203 return 0;
2204}
2205
2206/*
2207** Generate an appropriate SELFTEST table in the main database.
2208*/
2209static void createSelftestTable(ShellState *p){
2210 char *zErrMsg = 0;
2211 sqlite3_exec(p->db,
2212 "SAVEPOINT selftest_init;\n"
2213 "CREATE TABLE IF NOT EXISTS selftest(\n"
2214 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2215 " op TEXT,\n" /* Operator: memo run */
2216 " cmd TEXT,\n" /* Command text */
2217 " ans TEXT\n" /* Desired answer */
2218 ");"
2219 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2220 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2221 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2222 " 'memo','Tests generated by --init');\n"
2223 "INSERT INTO [_shell$self]\n"
2224 " SELECT 'run',\n"
2225 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2226 "FROM sqlite_master ORDER BY 2'',224))',\n"
2227 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2228 "FROM sqlite_master ORDER BY 2',224));\n"
2229 "INSERT INTO [_shell$self]\n"
2230 " SELECT 'run',"
2231 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2232 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2233 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2234 " FROM (\n"
2235 " SELECT name FROM sqlite_master\n"
2236 " WHERE type='table'\n"
2237 " AND name<>'selftest'\n"
2238 " AND coalesce(rootpage,0)>0\n"
2239 " )\n"
2240 " ORDER BY name;\n"
2241 "INSERT INTO [_shell$self]\n"
2242 " VALUES('run','PRAGMA integrity_check','ok');\n"
2243 "INSERT INTO selftest(tno,op,cmd,ans)"
2244 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2245 "DROP TABLE [_shell$self];"
2246 ,0,0,&zErrMsg);
2247 if( zErrMsg ){
2248 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2249 sqlite3_free(zErrMsg);
2250 }
2251 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2252}
2253
2254
2255/*
2256** Set the destination table field of the ShellState structure to
2257** the name of the table given. Escape any quote characters in the
2258** table name.
2259*/
2260static void set_table_name(ShellState *p, const char *zName){
2261 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00002262 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00002263 char *z;
2264
2265 if( p->zDestTable ){
2266 free(p->zDestTable);
2267 p->zDestTable = 0;
2268 }
2269 if( zName==0 ) return;
2270 cQuote = quoteChar(zName);
2271 n = strlen30(zName);
2272 if( cQuote ) n += n+2;
2273 z = p->zDestTable = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00002274 if( z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002275 n = 0;
2276 if( cQuote ) z[n++] = cQuote;
2277 for(i=0; zName[i]; i++){
2278 z[n++] = zName[i];
2279 if( zName[i]==cQuote ) z[n++] = cQuote;
2280 }
2281 if( cQuote ) z[n++] = cQuote;
2282 z[n] = 0;
2283}
2284
2285
2286/*
2287** Execute a query statement that will generate SQL output. Print
2288** the result columns, comma-separated, on a line and then add a
2289** semicolon terminator to the end of that line.
2290**
2291** If the number of columns is 1 and that column contains text "--"
2292** then write the semicolon on a separate line. That way, if a
2293** "--" comment occurs at the end of the statement, the comment
2294** won't consume the semicolon terminator.
2295*/
2296static int run_table_dump_query(
2297 ShellState *p, /* Query context */
2298 const char *zSelect, /* SELECT statement to extract content */
2299 const char *zFirstRow /* Print before first row, if not NULL */
2300){
2301 sqlite3_stmt *pSelect;
2302 int rc;
2303 int nResult;
2304 int i;
2305 const char *z;
2306 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2307 if( rc!=SQLITE_OK || !pSelect ){
2308 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2309 sqlite3_errmsg(p->db));
2310 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2311 return rc;
2312 }
2313 rc = sqlite3_step(pSelect);
2314 nResult = sqlite3_column_count(pSelect);
2315 while( rc==SQLITE_ROW ){
2316 if( zFirstRow ){
2317 utf8_printf(p->out, "%s", zFirstRow);
2318 zFirstRow = 0;
2319 }
2320 z = (const char*)sqlite3_column_text(pSelect, 0);
2321 utf8_printf(p->out, "%s", z);
2322 for(i=1; i<nResult; i++){
2323 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2324 }
2325 if( z==0 ) z = "";
2326 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2327 if( z[0] ){
2328 raw_printf(p->out, "\n;\n");
2329 }else{
2330 raw_printf(p->out, ";\n");
2331 }
2332 rc = sqlite3_step(pSelect);
2333 }
2334 rc = sqlite3_finalize(pSelect);
2335 if( rc!=SQLITE_OK ){
2336 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2337 sqlite3_errmsg(p->db));
2338 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2339 }
2340 return rc;
2341}
2342
2343/*
2344** Allocate space and save off current error string.
2345*/
2346static char *save_err_msg(
2347 sqlite3 *db /* Database to query */
2348){
2349 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2350 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2351 if( zErrMsg ){
2352 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2353 }
2354 return zErrMsg;
2355}
2356
2357#ifdef __linux__
2358/*
2359** Attempt to display I/O stats on Linux using /proc/PID/io
2360*/
2361static void displayLinuxIoStats(FILE *out){
2362 FILE *in;
2363 char z[200];
2364 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2365 in = fopen(z, "rb");
2366 if( in==0 ) return;
2367 while( fgets(z, sizeof(z), in)!=0 ){
2368 static const struct {
2369 const char *zPattern;
2370 const char *zDesc;
2371 } aTrans[] = {
2372 { "rchar: ", "Bytes received by read():" },
2373 { "wchar: ", "Bytes sent to write():" },
2374 { "syscr: ", "Read() system calls:" },
2375 { "syscw: ", "Write() system calls:" },
2376 { "read_bytes: ", "Bytes read from storage:" },
2377 { "write_bytes: ", "Bytes written to storage:" },
2378 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2379 };
2380 int i;
2381 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00002382 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00002383 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2384 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2385 break;
2386 }
2387 }
2388 }
2389 fclose(in);
2390}
2391#endif
2392
2393/*
2394** Display a single line of status using 64-bit values.
2395*/
2396static void displayStatLine(
2397 ShellState *p, /* The shell context */
2398 char *zLabel, /* Label for this one line */
2399 char *zFormat, /* Format for the result */
2400 int iStatusCtrl, /* Which status to display */
2401 int bReset /* True to reset the stats */
2402){
2403 sqlite3_int64 iCur = -1;
2404 sqlite3_int64 iHiwtr = -1;
2405 int i, nPercent;
2406 char zLine[200];
2407 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2408 for(i=0, nPercent=0; zFormat[i]; i++){
2409 if( zFormat[i]=='%' ) nPercent++;
2410 }
2411 if( nPercent>1 ){
2412 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2413 }else{
2414 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2415 }
2416 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2417}
2418
2419/*
2420** Display memory stats.
2421*/
2422static int display_stats(
2423 sqlite3 *db, /* Database to query */
2424 ShellState *pArg, /* Pointer to ShellState */
2425 int bReset /* True to reset the stats */
2426){
2427 int iCur;
2428 int iHiwtr;
drh393344f2018-03-09 16:37:05 +00002429 FILE *out;
2430 if( pArg==0 || pArg->out==0 ) return 0;
2431 out = pArg->out;
drh2ce15c32017-07-11 13:34:40 +00002432
drh393344f2018-03-09 16:37:05 +00002433 if( pArg->pStmt && (pArg->statsOn & 2) ){
2434 int nCol, i, x;
2435 sqlite3_stmt *pStmt = pArg->pStmt;
2436 char z[100];
2437 nCol = sqlite3_column_count(pStmt);
2438 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2439 for(i=0; i<nCol; i++){
2440 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2441 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002442#ifndef SQLITE_OMIT_DECLTYPE
drh393344f2018-03-09 16:37:05 +00002443 sqlite3_snprintf(30, z+x, "declared type:");
2444 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
drh929cce82018-03-17 16:26:36 +00002445#endif
2446#ifdef SQLITE_ENABLE_COLUMN_METADATA
drh393344f2018-03-09 16:37:05 +00002447 sqlite3_snprintf(30, z+x, "database name:");
2448 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2449 sqlite3_snprintf(30, z+x, "table name:");
2450 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2451 sqlite3_snprintf(30, z+x, "origin name:");
2452 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002453#endif
drh2ce15c32017-07-11 13:34:40 +00002454 }
drh929cce82018-03-17 16:26:36 +00002455 }
drh2ce15c32017-07-11 13:34:40 +00002456
drh393344f2018-03-09 16:37:05 +00002457 displayStatLine(pArg, "Memory Used:",
2458 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2459 displayStatLine(pArg, "Number of Outstanding Allocations:",
2460 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2461 if( pArg->shellFlgs & SHFLG_Pagecache ){
2462 displayStatLine(pArg, "Number of Pcache Pages Used:",
2463 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2464 }
2465 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2466 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2467 displayStatLine(pArg, "Largest Allocation:",
2468 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2469 displayStatLine(pArg, "Largest Pcache Allocation:",
2470 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2471#ifdef YYTRACKMAXSTACKDEPTH
2472 displayStatLine(pArg, "Deepest Parser Stack:",
2473 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2474#endif
2475
2476 if( db ){
drh2ce15c32017-07-11 13:34:40 +00002477 if( pArg->shellFlgs & SHFLG_Lookaside ){
2478 iHiwtr = iCur = -1;
2479 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2480 &iCur, &iHiwtr, bReset);
2481 raw_printf(pArg->out,
2482 "Lookaside Slots Used: %d (max %d)\n",
2483 iCur, iHiwtr);
2484 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2485 &iCur, &iHiwtr, bReset);
2486 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2487 iHiwtr);
2488 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2489 &iCur, &iHiwtr, bReset);
2490 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2491 iHiwtr);
2492 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2493 &iCur, &iHiwtr, bReset);
2494 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2495 iHiwtr);
2496 }
2497 iHiwtr = iCur = -1;
2498 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2499 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2500 iCur);
2501 iHiwtr = iCur = -1;
2502 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2503 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2504 iHiwtr = iCur = -1;
2505 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2506 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2507 iHiwtr = iCur = -1;
2508 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2509 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2510 iHiwtr = iCur = -1;
drhffc78a42018-03-14 14:53:50 +00002511 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2512 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2513 iHiwtr = iCur = -1;
drh2ce15c32017-07-11 13:34:40 +00002514 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2515 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2516 iCur);
2517 iHiwtr = iCur = -1;
2518 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2519 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2520 iCur);
2521 }
2522
drh393344f2018-03-09 16:37:05 +00002523 if( pArg->pStmt ){
drh2ce15c32017-07-11 13:34:40 +00002524 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2525 bReset);
2526 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2527 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2528 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2529 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2530 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2531 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2532 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
drh393344f2018-03-09 16:37:05 +00002533 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
2534 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2535 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2536 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2537 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2538 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
drh2ce15c32017-07-11 13:34:40 +00002539 }
2540
2541#ifdef __linux__
2542 displayLinuxIoStats(pArg->out);
2543#endif
2544
2545 /* Do not remove this machine readable comment: extra-stats-output-here */
2546
2547 return 0;
2548}
2549
2550/*
2551** Display scan stats.
2552*/
2553static void display_scanstats(
2554 sqlite3 *db, /* Database to query */
2555 ShellState *pArg /* Pointer to ShellState */
2556){
2557#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2558 UNUSED_PARAMETER(db);
2559 UNUSED_PARAMETER(pArg);
2560#else
2561 int i, k, n, mx;
2562 raw_printf(pArg->out, "-------- scanstats --------\n");
2563 mx = 0;
2564 for(k=0; k<=mx; k++){
2565 double rEstLoop = 1.0;
2566 for(i=n=0; 1; i++){
2567 sqlite3_stmt *p = pArg->pStmt;
2568 sqlite3_int64 nLoop, nVisit;
2569 double rEst;
2570 int iSid;
2571 const char *zExplain;
2572 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2573 break;
2574 }
2575 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2576 if( iSid>mx ) mx = iSid;
2577 if( iSid!=k ) continue;
2578 if( n==0 ){
2579 rEstLoop = (double)nLoop;
2580 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2581 }
2582 n++;
2583 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2584 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2585 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2586 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2587 rEstLoop *= rEst;
2588 raw_printf(pArg->out,
2589 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2590 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2591 );
2592 }
2593 }
2594 raw_printf(pArg->out, "---------------------------\n");
2595#endif
2596}
2597
2598/*
2599** Parameter azArray points to a zero-terminated array of strings. zStr
2600** points to a single nul-terminated string. Return non-zero if zStr
2601** is equal, according to strcmp(), to any of the strings in the array.
2602** Otherwise, return zero.
2603*/
2604static int str_in_array(const char *zStr, const char **azArray){
2605 int i;
2606 for(i=0; azArray[i]; i++){
2607 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2608 }
2609 return 0;
2610}
2611
2612/*
2613** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2614** and populate the ShellState.aiIndent[] array with the number of
2615** spaces each opcode should be indented before it is output.
2616**
2617** The indenting rules are:
2618**
2619** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2620** all opcodes that occur between the p2 jump destination and the opcode
2621** itself by 2 spaces.
2622**
2623** * For each "Goto", if the jump destination is earlier in the program
2624** and ends on one of:
2625** Yield SeekGt SeekLt RowSetRead Rewind
2626** or if the P1 parameter is one instead of zero,
2627** then indent all opcodes between the earlier instruction
2628** and "Goto" by 2 spaces.
2629*/
2630static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2631 const char *zSql; /* The text of the SQL statement */
2632 const char *z; /* Used to check if this is an EXPLAIN */
2633 int *abYield = 0; /* True if op is an OP_Yield */
2634 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2635 int iOp; /* Index of operation in p->aiIndent[] */
2636
drhf1949b62018-06-07 17:32:59 +00002637 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
drh2ce15c32017-07-11 13:34:40 +00002638 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2639 "Rewind", 0 };
2640 const char *azGoto[] = { "Goto", 0 };
2641
2642 /* Try to figure out if this is really an EXPLAIN statement. If this
2643 ** cannot be verified, return early. */
2644 if( sqlite3_column_count(pSql)!=8 ){
2645 p->cMode = p->mode;
2646 return;
2647 }
2648 zSql = sqlite3_sql(pSql);
2649 if( zSql==0 ) return;
2650 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2651 if( sqlite3_strnicmp(z, "explain", 7) ){
2652 p->cMode = p->mode;
2653 return;
2654 }
2655
2656 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2657 int i;
2658 int iAddr = sqlite3_column_int(pSql, 0);
2659 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2660
2661 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2662 ** p2 is an instruction address, set variable p2op to the index of that
2663 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2664 ** the current instruction is part of a sub-program generated by an
2665 ** SQL trigger or foreign key. */
2666 int p2 = sqlite3_column_int(pSql, 3);
2667 int p2op = (p2 + (iOp-iAddr));
2668
2669 /* Grow the p->aiIndent array as required */
2670 if( iOp>=nAlloc ){
2671 if( iOp==0 ){
2672 /* Do further verfication that this is explain output. Abort if
2673 ** it is not */
2674 static const char *explainCols[] = {
2675 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2676 int jj;
2677 for(jj=0; jj<ArraySize(explainCols); jj++){
2678 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2679 p->cMode = p->mode;
2680 sqlite3_reset(pSql);
2681 return;
2682 }
2683 }
2684 }
2685 nAlloc += 100;
2686 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002687 if( p->aiIndent==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002688 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002689 if( abYield==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002690 }
2691 abYield[iOp] = str_in_array(zOp, azYield);
2692 p->aiIndent[iOp] = 0;
2693 p->nIndent = iOp+1;
2694
2695 if( str_in_array(zOp, azNext) ){
2696 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2697 }
2698 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2699 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2700 ){
2701 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2702 }
2703 }
2704
2705 p->iIndent = 0;
2706 sqlite3_free(abYield);
2707 sqlite3_reset(pSql);
2708}
2709
2710/*
2711** Free the array allocated by explain_data_prepare().
2712*/
2713static void explain_data_delete(ShellState *p){
2714 sqlite3_free(p->aiIndent);
2715 p->aiIndent = 0;
2716 p->nIndent = 0;
2717 p->iIndent = 0;
2718}
2719
2720/*
2721** Disable and restore .wheretrace and .selecttrace settings.
2722*/
2723#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2724extern int sqlite3SelectTrace;
2725static int savedSelectTrace;
2726#endif
2727#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2728extern int sqlite3WhereTrace;
2729static int savedWhereTrace;
2730#endif
2731static void disable_debug_trace_modes(void){
2732#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2733 savedSelectTrace = sqlite3SelectTrace;
2734 sqlite3SelectTrace = 0;
2735#endif
2736#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2737 savedWhereTrace = sqlite3WhereTrace;
2738 sqlite3WhereTrace = 0;
2739#endif
2740}
2741static void restore_debug_trace_modes(void){
2742#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2743 sqlite3SelectTrace = savedSelectTrace;
2744#endif
2745#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2746 sqlite3WhereTrace = savedWhereTrace;
2747#endif
2748}
2749
2750/*
2751** Run a prepared statement
2752*/
2753static void exec_prepared_stmt(
2754 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002755 sqlite3_stmt *pStmt /* Statment to run */
drh2ce15c32017-07-11 13:34:40 +00002756){
2757 int rc;
2758
2759 /* perform the first step. this will tell us if we
2760 ** have a result set or not and how wide it is.
2761 */
2762 rc = sqlite3_step(pStmt);
2763 /* if we have a result set... */
2764 if( SQLITE_ROW == rc ){
drha10b9992018-03-09 15:24:33 +00002765 /* allocate space for col name ptr, value ptr, and type */
2766 int nCol = sqlite3_column_count(pStmt);
2767 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2768 if( !pData ){
2769 rc = SQLITE_NOMEM;
drh2ce15c32017-07-11 13:34:40 +00002770 }else{
drha10b9992018-03-09 15:24:33 +00002771 char **azCols = (char **)pData; /* Names of result columns */
2772 char **azVals = &azCols[nCol]; /* Results */
2773 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2774 int i, x;
2775 assert(sizeof(int) <= sizeof(char *));
2776 /* save off ptrs to column names */
2777 for(i=0; i<nCol; i++){
2778 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2779 }
drh2ce15c32017-07-11 13:34:40 +00002780 do{
drha10b9992018-03-09 15:24:33 +00002781 /* extract the data and data types */
2782 for(i=0; i<nCol; i++){
2783 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2784 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2785 azVals[i] = "";
2786 }else{
2787 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2788 }
2789 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2790 rc = SQLITE_NOMEM;
2791 break; /* from for */
2792 }
2793 } /* end for */
2794
2795 /* if data and types extracted successfully... */
2796 if( SQLITE_ROW == rc ){
2797 /* call the supplied callback with the result row data */
2798 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2799 rc = SQLITE_ABORT;
2800 }else{
2801 rc = sqlite3_step(pStmt);
2802 }
2803 }
2804 } while( SQLITE_ROW == rc );
2805 sqlite3_free(pData);
drh2ce15c32017-07-11 13:34:40 +00002806 }
2807 }
2808}
2809
dan6b046be2018-01-09 15:25:55 +00002810#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002811/*
dan43efc182017-12-19 17:42:13 +00002812** This function is called to process SQL if the previous shell command
2813** was ".expert". It passes the SQL in the second argument directly to
2814** the sqlite3expert object.
2815**
2816** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2817** code. In this case, (*pzErr) may be set to point to a buffer containing
2818** an English language error message. It is the responsibility of the
2819** caller to eventually free this buffer using sqlite3_free().
2820*/
2821static int expertHandleSQL(
2822 ShellState *pState,
2823 const char *zSql,
2824 char **pzErr
2825){
2826 assert( pState->expert.pExpert );
2827 assert( pzErr==0 || *pzErr==0 );
2828 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2829}
2830
2831/*
2832** This function is called either to silently clean up the object
2833** created by the ".expert" command (if bCancel==1), or to generate a
2834** report from it and then clean it up (if bCancel==0).
2835**
2836** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2837** code. In this case, (*pzErr) may be set to point to a buffer containing
2838** an English language error message. It is the responsibility of the
2839** caller to eventually free this buffer using sqlite3_free().
2840*/
2841static int expertFinish(
2842 ShellState *pState,
2843 int bCancel,
2844 char **pzErr
2845){
2846 int rc = SQLITE_OK;
2847 sqlite3expert *p = pState->expert.pExpert;
2848 assert( p );
2849 assert( bCancel || pzErr==0 || *pzErr==0 );
2850 if( bCancel==0 ){
2851 FILE *out = pState->out;
2852 int bVerbose = pState->expert.bVerbose;
2853
2854 rc = sqlite3_expert_analyze(p, pzErr);
2855 if( rc==SQLITE_OK ){
2856 int nQuery = sqlite3_expert_count(p);
2857 int i;
2858
2859 if( bVerbose ){
2860 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2861 raw_printf(out, "-- Candidates -----------------------------\n");
2862 raw_printf(out, "%s\n", zCand);
2863 }
2864 for(i=0; i<nQuery; i++){
2865 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2866 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2867 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2868 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2869 if( bVerbose ){
2870 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2871 raw_printf(out, "%s\n\n", zSql);
2872 }
2873 raw_printf(out, "%s\n", zIdx);
2874 raw_printf(out, "%s\n", zEQP);
2875 }
2876 }
2877 }
2878 sqlite3_expert_destroy(p);
2879 pState->expert.pExpert = 0;
2880 return rc;
2881}
2882
dan6b046be2018-01-09 15:25:55 +00002883/*
2884** Implementation of ".expert" dot command.
2885*/
2886static int expertDotCommand(
2887 ShellState *pState, /* Current shell tool state */
2888 char **azArg, /* Array of arguments passed to dot command */
2889 int nArg /* Number of entries in azArg[] */
2890){
2891 int rc = SQLITE_OK;
2892 char *zErr = 0;
2893 int i;
2894 int iSample = 0;
2895
2896 assert( pState->expert.pExpert==0 );
2897 memset(&pState->expert, 0, sizeof(ExpertInfo));
2898
2899 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2900 char *z = azArg[i];
2901 int n;
2902 if( z[0]=='-' && z[1]=='-' ) z++;
2903 n = strlen30(z);
2904 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2905 pState->expert.bVerbose = 1;
2906 }
2907 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2908 if( i==(nArg-1) ){
2909 raw_printf(stderr, "option requires an argument: %s\n", z);
2910 rc = SQLITE_ERROR;
2911 }else{
2912 iSample = (int)integerValue(azArg[++i]);
2913 if( iSample<0 || iSample>100 ){
2914 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2915 rc = SQLITE_ERROR;
2916 }
2917 }
2918 }
2919 else{
2920 raw_printf(stderr, "unknown option: %s\n", z);
2921 rc = SQLITE_ERROR;
2922 }
2923 }
2924
2925 if( rc==SQLITE_OK ){
2926 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2927 if( pState->expert.pExpert==0 ){
2928 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2929 rc = SQLITE_ERROR;
2930 }else{
2931 sqlite3_expert_config(
2932 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2933 );
2934 }
2935 }
2936
2937 return rc;
2938}
2939#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00002940
2941/*
drh2ce15c32017-07-11 13:34:40 +00002942** Execute a statement or set of statements. Print
2943** any result rows/columns depending on the current mode
2944** set via the supplied callback.
2945**
2946** This is very similar to SQLite's built-in sqlite3_exec()
2947** function except it takes a slightly different callback
2948** and callback data argument.
2949*/
2950static int shell_exec(
drh2ce15c32017-07-11 13:34:40 +00002951 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002952 const char *zSql, /* SQL to be evaluated */
drh2ce15c32017-07-11 13:34:40 +00002953 char **pzErrMsg /* Error msg written here */
2954){
2955 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2956 int rc = SQLITE_OK; /* Return Code */
2957 int rc2;
2958 const char *zLeftover; /* Tail of unprocessed SQL */
drha10b9992018-03-09 15:24:33 +00002959 sqlite3 *db = pArg->db;
drh2ce15c32017-07-11 13:34:40 +00002960
2961 if( pzErrMsg ){
2962 *pzErrMsg = NULL;
2963 }
2964
dan6b046be2018-01-09 15:25:55 +00002965#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00002966 if( pArg->expert.pExpert ){
2967 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2968 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2969 }
dan6b046be2018-01-09 15:25:55 +00002970#endif
dan43efc182017-12-19 17:42:13 +00002971
drh2ce15c32017-07-11 13:34:40 +00002972 while( zSql[0] && (SQLITE_OK == rc) ){
2973 static const char *zStmtSql;
2974 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2975 if( SQLITE_OK != rc ){
2976 if( pzErrMsg ){
2977 *pzErrMsg = save_err_msg(db);
2978 }
2979 }else{
2980 if( !pStmt ){
2981 /* this happens for a comment or white-space */
2982 zSql = zLeftover;
2983 while( IsSpace(zSql[0]) ) zSql++;
2984 continue;
2985 }
2986 zStmtSql = sqlite3_sql(pStmt);
2987 if( zStmtSql==0 ) zStmtSql = "";
2988 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2989
2990 /* save off the prepared statment handle and reset row count */
2991 if( pArg ){
2992 pArg->pStmt = pStmt;
2993 pArg->cnt = 0;
2994 }
2995
2996 /* echo the sql statement if echo on */
2997 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2998 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2999 }
3000
3001 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
3002 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
3003 sqlite3_stmt *pExplain;
3004 char *zEQP;
drhada70452017-12-21 21:02:27 +00003005 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00003006 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00003007 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3008 if( pArg->autoEQP>=AUTOEQP_trigger ){
3009 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3010 }
drh2ce15c32017-07-11 13:34:40 +00003011 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3012 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3013 if( rc==SQLITE_OK ){
3014 while( sqlite3_step(pExplain)==SQLITE_ROW ){
drh4b5345c2018-04-24 13:07:40 +00003015 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
drhe2ca99c2018-05-02 00:33:43 +00003016 int iEqpId = sqlite3_column_int(pExplain, 0);
3017 int iParentId = sqlite3_column_int(pExplain, 1);
drh4b5345c2018-04-24 13:07:40 +00003018 if( zEQPLine[0]=='-' ) eqp_render(pArg);
drhe2ca99c2018-05-02 00:33:43 +00003019 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
drh2ce15c32017-07-11 13:34:40 +00003020 }
drh4b5345c2018-04-24 13:07:40 +00003021 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003022 }
3023 sqlite3_finalize(pExplain);
3024 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00003025 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00003026 /* Also do an EXPLAIN for ".eqp full" mode */
3027 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3028 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3029 if( rc==SQLITE_OK ){
3030 pArg->cMode = MODE_Explain;
3031 explain_data_prepare(pArg, pExplain);
drha10b9992018-03-09 15:24:33 +00003032 exec_prepared_stmt(pArg, pExplain);
drh2ce15c32017-07-11 13:34:40 +00003033 explain_data_delete(pArg);
3034 }
3035 sqlite3_finalize(pExplain);
3036 sqlite3_free(zEQP);
3037 }
drh51efe092018-03-20 12:04:38 +00003038 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3039 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3040 /* Reprepare pStmt before reactiving trace modes */
3041 sqlite3_finalize(pStmt);
3042 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
drh3c49eaf2018-06-07 15:23:43 +00003043 if( pArg ) pArg->pStmt = pStmt;
drh51efe092018-03-20 12:04:38 +00003044 }
drh2ce15c32017-07-11 13:34:40 +00003045 restore_debug_trace_modes();
3046 }
3047
3048 if( pArg ){
3049 pArg->cMode = pArg->mode;
drh4b5345c2018-04-24 13:07:40 +00003050 if( pArg->autoExplain ){
3051 if( sqlite3_column_count(pStmt)==8
3052 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
3053 ){
3054 pArg->cMode = MODE_Explain;
3055 }
3056 if( sqlite3_column_count(pStmt)==4
3057 && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql,0)==0 ){
3058 pArg->cMode = MODE_EQP;
3059 }
drh2ce15c32017-07-11 13:34:40 +00003060 }
3061
3062 /* If the shell is currently in ".explain" mode, gather the extra
3063 ** data required to add indents to the output.*/
3064 if( pArg->cMode==MODE_Explain ){
3065 explain_data_prepare(pArg, pStmt);
3066 }
3067 }
3068
drha10b9992018-03-09 15:24:33 +00003069 exec_prepared_stmt(pArg, pStmt);
drh2ce15c32017-07-11 13:34:40 +00003070 explain_data_delete(pArg);
drh4b5345c2018-04-24 13:07:40 +00003071 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003072
3073 /* print usage stats if stats on */
3074 if( pArg && pArg->statsOn ){
3075 display_stats(db, pArg, 0);
3076 }
3077
3078 /* print loop-counters if required */
3079 if( pArg && pArg->scanstatsOn ){
3080 display_scanstats(db, pArg);
3081 }
3082
3083 /* Finalize the statement just executed. If this fails, save a
3084 ** copy of the error message. Otherwise, set zSql to point to the
3085 ** next statement to execute. */
3086 rc2 = sqlite3_finalize(pStmt);
3087 if( rc!=SQLITE_NOMEM ) rc = rc2;
3088 if( rc==SQLITE_OK ){
3089 zSql = zLeftover;
3090 while( IsSpace(zSql[0]) ) zSql++;
3091 }else if( pzErrMsg ){
3092 *pzErrMsg = save_err_msg(db);
3093 }
3094
3095 /* clear saved stmt handle */
3096 if( pArg ){
3097 pArg->pStmt = NULL;
3098 }
3099 }
3100 } /* end while */
3101
3102 return rc;
3103}
3104
3105/*
3106** Release memory previously allocated by tableColumnList().
3107*/
3108static void freeColumnList(char **azCol){
3109 int i;
3110 for(i=1; azCol[i]; i++){
3111 sqlite3_free(azCol[i]);
3112 }
3113 /* azCol[0] is a static string */
3114 sqlite3_free(azCol);
3115}
3116
3117/*
3118** Return a list of pointers to strings which are the names of all
3119** columns in table zTab. The memory to hold the names is dynamically
3120** allocated and must be released by the caller using a subsequent call
3121** to freeColumnList().
3122**
3123** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3124** value that needs to be preserved, then azCol[0] is filled in with the
3125** name of the rowid column.
3126**
3127** The first regular column in the table is azCol[1]. The list is terminated
3128** by an entry with azCol[i]==0.
3129*/
3130static char **tableColumnList(ShellState *p, const char *zTab){
3131 char **azCol = 0;
3132 sqlite3_stmt *pStmt;
3133 char *zSql;
3134 int nCol = 0;
3135 int nAlloc = 0;
3136 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3137 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3138 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3139 int rc;
3140
3141 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3142 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3143 sqlite3_free(zSql);
3144 if( rc ) return 0;
3145 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3146 if( nCol>=nAlloc-2 ){
3147 nAlloc = nAlloc*2 + nCol + 10;
3148 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
drh4b5345c2018-04-24 13:07:40 +00003149 if( azCol==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00003150 }
3151 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3152 if( sqlite3_column_int(pStmt, 5) ){
3153 nPK++;
3154 if( nPK==1
3155 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3156 "INTEGER")==0
3157 ){
3158 isIPK = 1;
3159 }else{
3160 isIPK = 0;
3161 }
3162 }
3163 }
3164 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00003165 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003166 azCol[0] = 0;
3167 azCol[nCol+1] = 0;
3168
3169 /* The decision of whether or not a rowid really needs to be preserved
3170 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3171 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3172 ** rowids on tables where the rowid is inaccessible because there are other
3173 ** columns in the table named "rowid", "_rowid_", and "oid".
3174 */
3175 if( preserveRowid && isIPK ){
3176 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3177 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3178 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3179 ** ROWID aliases. To distinguish these cases, check to see if
3180 ** there is a "pk" entry in "PRAGMA index_list". There will be
3181 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3182 */
3183 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3184 " WHERE origin='pk'", zTab);
3185 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3186 sqlite3_free(zSql);
3187 if( rc ){
3188 freeColumnList(azCol);
3189 return 0;
3190 }
3191 rc = sqlite3_step(pStmt);
3192 sqlite3_finalize(pStmt);
3193 preserveRowid = rc==SQLITE_ROW;
3194 }
3195 if( preserveRowid ){
3196 /* Only preserve the rowid if we can find a name to use for the
3197 ** rowid */
3198 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3199 int i, j;
3200 for(j=0; j<3; j++){
3201 for(i=1; i<=nCol; i++){
3202 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3203 }
3204 if( i>nCol ){
3205 /* At this point, we know that azRowid[j] is not the name of any
3206 ** ordinary column in the table. Verify that azRowid[j] is a valid
3207 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3208 ** tables will fail this last check */
3209 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3210 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3211 break;
3212 }
3213 }
3214 }
3215 return azCol;
3216}
3217
3218/*
3219** Toggle the reverse_unordered_selects setting.
3220*/
3221static void toggleSelectOrder(sqlite3 *db){
3222 sqlite3_stmt *pStmt = 0;
3223 int iSetting = 0;
3224 char zStmt[100];
3225 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3226 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3227 iSetting = sqlite3_column_int(pStmt, 0);
3228 }
3229 sqlite3_finalize(pStmt);
3230 sqlite3_snprintf(sizeof(zStmt), zStmt,
3231 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3232 sqlite3_exec(db, zStmt, 0, 0, 0);
3233}
3234
3235/*
3236** This is a different callback routine used for dumping the database.
3237** Each row received by this callback consists of a table name,
3238** the table type ("index" or "table") and SQL to create the table.
3239** This routine should print text sufficient to recreate the table.
3240*/
3241static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3242 int rc;
3243 const char *zTable;
3244 const char *zType;
3245 const char *zSql;
3246 ShellState *p = (ShellState *)pArg;
3247
3248 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00003249 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003250 zTable = azArg[0];
3251 zType = azArg[1];
3252 zSql = azArg[2];
3253
3254 if( strcmp(zTable, "sqlite_sequence")==0 ){
3255 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3256 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3257 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3258 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3259 return 0;
3260 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3261 char *zIns;
3262 if( !p->writableSchema ){
3263 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3264 p->writableSchema = 1;
3265 }
3266 zIns = sqlite3_mprintf(
3267 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3268 "VALUES('table','%q','%q',0,'%q');",
3269 zTable, zTable, zSql);
3270 utf8_printf(p->out, "%s\n", zIns);
3271 sqlite3_free(zIns);
3272 return 0;
3273 }else{
3274 printSchemaLine(p->out, zSql, ";\n");
3275 }
3276
3277 if( strcmp(zType, "table")==0 ){
3278 ShellText sSelect;
3279 ShellText sTable;
3280 char **azCol;
3281 int i;
3282 char *savedDestTable;
3283 int savedMode;
3284
3285 azCol = tableColumnList(p, zTable);
3286 if( azCol==0 ){
3287 p->nErr++;
3288 return 0;
3289 }
3290
3291 /* Always quote the table name, even if it appears to be pure ascii,
3292 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3293 initText(&sTable);
3294 appendText(&sTable, zTable, quoteChar(zTable));
3295 /* If preserving the rowid, add a column list after the table name.
3296 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3297 ** instead of the usual "INSERT INTO tab VALUES(...)".
3298 */
3299 if( azCol[0] ){
3300 appendText(&sTable, "(", 0);
3301 appendText(&sTable, azCol[0], 0);
3302 for(i=1; azCol[i]; i++){
3303 appendText(&sTable, ",", 0);
3304 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3305 }
3306 appendText(&sTable, ")", 0);
3307 }
3308
3309 /* Build an appropriate SELECT statement */
3310 initText(&sSelect);
3311 appendText(&sSelect, "SELECT ", 0);
3312 if( azCol[0] ){
3313 appendText(&sSelect, azCol[0], 0);
3314 appendText(&sSelect, ",", 0);
3315 }
3316 for(i=1; azCol[i]; i++){
3317 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3318 if( azCol[i+1] ){
3319 appendText(&sSelect, ",", 0);
3320 }
3321 }
3322 freeColumnList(azCol);
3323 appendText(&sSelect, " FROM ", 0);
3324 appendText(&sSelect, zTable, quoteChar(zTable));
3325
3326 savedDestTable = p->zDestTable;
3327 savedMode = p->mode;
3328 p->zDestTable = sTable.z;
3329 p->mode = p->cMode = MODE_Insert;
drha10b9992018-03-09 15:24:33 +00003330 rc = shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003331 if( (rc&0xff)==SQLITE_CORRUPT ){
3332 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3333 toggleSelectOrder(p->db);
drha10b9992018-03-09 15:24:33 +00003334 shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003335 toggleSelectOrder(p->db);
3336 }
3337 p->zDestTable = savedDestTable;
3338 p->mode = savedMode;
3339 freeText(&sTable);
3340 freeText(&sSelect);
3341 if( rc ) p->nErr++;
3342 }
3343 return 0;
3344}
3345
3346/*
3347** Run zQuery. Use dump_callback() as the callback routine so that
3348** the contents of the query are output as SQL statements.
3349**
3350** If we get a SQLITE_CORRUPT error, rerun the query after appending
3351** "ORDER BY rowid DESC" to the end.
3352*/
3353static int run_schema_dump_query(
3354 ShellState *p,
3355 const char *zQuery
3356){
3357 int rc;
3358 char *zErr = 0;
3359 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3360 if( rc==SQLITE_CORRUPT ){
3361 char *zQ2;
3362 int len = strlen30(zQuery);
3363 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3364 if( zErr ){
3365 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3366 sqlite3_free(zErr);
3367 zErr = 0;
3368 }
3369 zQ2 = malloc( len+100 );
3370 if( zQ2==0 ) return rc;
3371 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3372 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3373 if( rc ){
3374 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3375 }else{
3376 rc = SQLITE_CORRUPT;
3377 }
3378 sqlite3_free(zErr);
3379 free(zQ2);
3380 }
3381 return rc;
3382}
3383
3384/*
drh98aa2ab2018-09-26 16:53:51 +00003385** Text of help messages.
3386**
3387** The help text for each individual command begins with a line that starts
3388** with ".". Subsequent lines are supplimental information.
3389**
3390** There must be two or more spaces between the end of the command and the
3391** start of the description of what that command does.
drh2ce15c32017-07-11 13:34:40 +00003392*/
drh98aa2ab2018-09-26 16:53:51 +00003393static const char *(azHelp[]) = {
drhe37c0e12018-01-06 19:19:50 +00003394#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drh98aa2ab2018-09-26 16:53:51 +00003395 ".archive ... Manage SQL archives",
3396 " Each command must have exactly one of the following options:",
3397 " -c, --create Create a new archive",
3398 " -u, --update Update or add files to an existing archive",
3399 " -t, --list List contents of archive",
3400 " -x, --extract Extract files from archive",
3401 " Optional arguments:",
3402 " -v, --verbose Print each filename as it is processed",
3403 " -f FILE, --file FILE Operate on archive FILE (default is current db)",
3404 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS",
3405 " -C DIR, --directory DIR Change to directory DIR to read/extract files",
3406 " -n, --dryrun Show the SQL that would have occurred",
3407 " Examples:",
3408 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar",
3409 " .ar -tf archive.sar # List members of archive.sar",
3410 " .ar -xvf archive.sar # Verbosely extract files from archive.sar",
3411 " See also:",
3412 " http://sqlite.org/cli.html#sqlar_archive_support",
drhe37c0e12018-01-06 19:19:50 +00003413#endif
drh2ce15c32017-07-11 13:34:40 +00003414#ifndef SQLITE_OMIT_AUTHORIZATION
drh98aa2ab2018-09-26 16:53:51 +00003415 ".auth ON|OFF Show authorizer callbacks",
drh2ce15c32017-07-11 13:34:40 +00003416#endif
drh98aa2ab2018-09-26 16:53:51 +00003417 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3418 " --append Use the appendvfs",
drha50bffb2018-12-08 01:09:14 +00003419 " --async Write to FILE without a journal and without fsync()",
drh98aa2ab2018-09-26 16:53:51 +00003420 ".bail on|off Stop after hitting an error. Default OFF",
3421 ".binary on|off Turn binary output on or off. Default OFF",
3422 ".cd DIRECTORY Change the working directory to DIRECTORY",
3423 ".changes on|off Show number of rows changed by SQL",
3424 ".check GLOB Fail if output since .testcase does not match",
3425 ".clone NEWDB Clone data into NEWDB from the existing database",
3426 ".databases List names and files of attached databases",
3427 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3428 ".dbinfo ?DB? Show status information about the database",
drheb7f2a02018-09-26 18:02:32 +00003429 ".dump ?TABLE? ... Render all database content as SQL",
3430 " Options:",
3431 " --preserve-rowids Include ROWID values in the output",
3432 " --newlines Allow unescaped newline characters in output",
3433 " TABLE is LIKE pattern for the tables to dump",
drh98aa2ab2018-09-26 16:53:51 +00003434 ".echo on|off Turn command echo on or off",
drhb4e50392019-01-26 15:40:04 +00003435 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
3436 " Other Modes:",
3437#ifdef SQLITE_DEBUG
3438 " test Show raw EXPLAIN QUERY PLAN output",
3439 " trace Like \"full\" but also enable \"PRAGMA vdbe_trace\"",
3440#endif
3441 " trigger Like \"full\" but also show trigger bytecode",
drh98aa2ab2018-09-26 16:53:51 +00003442 ".excel Display the output of next command in a spreadsheet",
drheb7f2a02018-09-26 18:02:32 +00003443 ".exit ?CODE? Exit this program with return-code CODE",
drh98aa2ab2018-09-26 16:53:51 +00003444 ".expert EXPERIMENTAL. Suggest indexes for specified queries",
drh2ce15c32017-07-11 13:34:40 +00003445/* Because explain mode comes on automatically now, the ".explain" mode
3446** is removed from the help screen. It is still supported for legacy, however */
drh98aa2ab2018-09-26 16:53:51 +00003447/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/
3448 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3449 ".headers on|off Turn display of headers on or off",
3450 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3451 ".import FILE TABLE Import data from FILE into TABLE",
drh2ce15c32017-07-11 13:34:40 +00003452#ifndef SQLITE_OMIT_TEST_CONTROL
drh98aa2ab2018-09-26 16:53:51 +00003453 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
drh2ce15c32017-07-11 13:34:40 +00003454#endif
drh98aa2ab2018-09-26 16:53:51 +00003455 ".indexes ?TABLE? Show names of indexes",
3456 " If TABLE is specified, only show indexes for",
3457 " tables matching TABLE using the LIKE operator.",
drh2ce15c32017-07-11 13:34:40 +00003458#ifdef SQLITE_ENABLE_IOTRACE
drh98aa2ab2018-09-26 16:53:51 +00003459 ".iotrace FILE Enable I/O diagnostic logging to FILE",
drh2ce15c32017-07-11 13:34:40 +00003460#endif
drh98aa2ab2018-09-26 16:53:51 +00003461 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3462 ".lint OPTIONS Report potential schema issues.",
3463 " Options:",
3464 " fkey-indexes Find missing foreign key indexes",
drh2ce15c32017-07-11 13:34:40 +00003465#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh98aa2ab2018-09-26 16:53:51 +00003466 ".load FILE ?ENTRY? Load an extension library",
drh2ce15c32017-07-11 13:34:40 +00003467#endif
drh98aa2ab2018-09-26 16:53:51 +00003468 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3469 ".mode MODE ?TABLE? Set output mode",
3470 " MODE is one of:",
3471 " ascii Columns/rows delimited by 0x1F and 0x1E",
3472 " csv Comma-separated values",
3473 " column Left-aligned columns. (See .width)",
3474 " html HTML <table> code",
3475 " insert SQL insert statements for TABLE",
3476 " line One value per line",
3477 " list Values delimited by \"|\"",
3478 " quote Escape answers as for SQL",
3479 " tabs Tab-separated values",
3480 " tcl TCL list elements",
3481 ".nullvalue STRING Use STRING in place of NULL values",
3482 ".once (-e|-x|FILE) Output for the next SQL command only to FILE",
3483 " If FILE begins with '|' then open as a pipe",
3484 " Other options:",
3485 " -e Invoke system text editor",
3486 " -x Open in a spreadsheet",
3487 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3488 " Options:",
drh60f34ae2018-10-30 13:19:49 +00003489 " --append Use appendvfs to append database to the end of FILE",
drha751f392018-10-30 15:31:22 +00003490#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00003491 " --deserialize Load into memory useing sqlite3_deserialize()",
drh33746482018-12-13 15:06:26 +00003492 " --hexdb Load the output of \"dbtotxt\" as an in-memory database",
drh6ca64482019-01-22 16:06:20 +00003493 " --maxsize N Maximum size for --hexdb or --deserialized database",
drha751f392018-10-30 15:31:22 +00003494#endif
drh60f34ae2018-10-30 13:19:49 +00003495 " --new Initialize FILE to an empty database",
3496 " --readonly Open FILE readonly",
3497 " --zip FILE is a ZIP archive",
drh98aa2ab2018-09-26 16:53:51 +00003498 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
3499 " If FILE begins with '|' then open it as a pipe.",
3500 ".print STRING... Print literal STRING",
drh569b1d92019-02-05 20:51:41 +00003501#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00003502 ".progress N Invoke progress handler after every N opcodes",
3503 " --limit N Interrupt after N progress callbacks",
3504 " --once Do no more than one progress interrupt",
3505 " --quiet|-q No output except at interrupts",
3506 " --reset Reset the count for each input and interrupt",
drh569b1d92019-02-05 20:51:41 +00003507#endif
drh98aa2ab2018-09-26 16:53:51 +00003508 ".prompt MAIN CONTINUE Replace the standard prompts",
3509 ".quit Exit this program",
3510 ".read FILE Read input from FILE",
3511 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
3512 ".save FILE Write in-memory database into FILE",
3513 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
3514 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
3515 " Options:",
3516 " --indent Try to pretty-print the schema",
drheb7f2a02018-09-26 18:02:32 +00003517 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
3518 " Options:",
3519 " --init Create a new SELFTEST table",
3520 " -v Verbose output",
drh98aa2ab2018-09-26 16:53:51 +00003521 ".separator COL ?ROW? Change the column and row separators",
drh2ce15c32017-07-11 13:34:40 +00003522#if defined(SQLITE_ENABLE_SESSION)
drheb7f2a02018-09-26 18:02:32 +00003523 ".session ?NAME? CMD ... Create or control sessions",
3524 " Subcommands:",
3525 " attach TABLE Attach TABLE",
3526 " changeset FILE Write a changeset into FILE",
3527 " close Close one session",
3528 " enable ?BOOLEAN? Set or query the enable bit",
3529 " filter GLOB... Reject tables matching GLOBs",
3530 " indirect ?BOOLEAN? Mark or query the indirect status",
3531 " isempty Query whether the session is empty",
3532 " list List currently open session names",
3533 " open DB NAME Open a new session on DB",
3534 " patchset FILE Write a patchset into FILE",
3535 " If ?NAME? is omitted, the first defined session is used.",
drh2ce15c32017-07-11 13:34:40 +00003536#endif
drheb7f2a02018-09-26 18:02:32 +00003537 ".sha3sum ... Compute a SHA3 hash of database content",
3538 " Options:",
3539 " --schema Also hash the sqlite_master table",
3540 " --sha3-224 Use the sha3-224 algorithm",
3541 " --sha3-256 Use the sha3-256 algorithm. This is the default.",
3542 " --sha3-384 Use the sha3-384 algorithm",
3543 " --sha3-512 Use the sha3-512 algorithm",
3544 " Any other argument is a LIKE pattern for tables to hash",
drh04a28c32018-01-31 01:38:44 +00003545#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003546 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003547#endif
drh98aa2ab2018-09-26 16:53:51 +00003548 ".show Show the current values for various settings",
3549 ".stats ?on|off? Show stats or turn stats on or off",
drh04a28c32018-01-31 01:38:44 +00003550#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003551 ".system CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003552#endif
drh98aa2ab2018-09-26 16:53:51 +00003553 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
3554 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
3555 ".timeout MS Try opening locked tables for MS milliseconds",
3556 ".timer on|off Turn SQL timer on or off",
drh707821f2018-12-05 13:39:06 +00003557#ifndef SQLITE_OMIT_TRACE
3558 ".trace ?OPTIONS? Output each SQL statement as it is run",
3559 " FILE Send output to FILE",
3560 " stdout Send output to stdout",
3561 " stderr Send output to stderr",
3562 " off Disable tracing",
3563 " --expanded Expand query parameters",
3564#ifdef SQLITE_ENABLE_NORMALIZE
3565 " --normalized Normal the SQL statements",
3566#endif
3567 " --plain Show SQL as it is input",
3568 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
3569 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
3570 " --row Trace each row (SQLITE_TRACE_ROW)",
3571 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
3572#endif /* SQLITE_OMIT_TRACE */
drh98aa2ab2018-09-26 16:53:51 +00003573 ".vfsinfo ?AUX? Information about the top-level VFS",
3574 ".vfslist List all available VFSes",
3575 ".vfsname ?AUX? Print the name of the VFS stack",
3576 ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
3577 " Negative values right-justify",
3578};
3579
3580/*
3581** Output help text.
3582**
3583** zPattern describes the set of commands for which help text is provided.
3584** If zPattern is NULL, then show all commands, but only give a one-line
3585** description of each.
3586**
3587** Return the number of matches.
3588*/
3589static int showHelp(FILE *out, const char *zPattern){
drhe93f8262018-10-11 16:53:37 +00003590 int i = 0;
3591 int j = 0;
drh98aa2ab2018-09-26 16:53:51 +00003592 int n = 0;
3593 char *zPat;
drh488cddf2018-10-06 14:38:17 +00003594 if( zPattern==0
3595 || zPattern[0]=='0'
3596 || strcmp(zPattern,"-a")==0
3597 || strcmp(zPattern,"-all")==0
3598 ){
drh98aa2ab2018-09-26 16:53:51 +00003599 /* Show all commands, but only one line per command */
drh488cddf2018-10-06 14:38:17 +00003600 if( zPattern==0 ) zPattern = "";
drh98aa2ab2018-09-26 16:53:51 +00003601 for(i=0; i<ArraySize(azHelp); i++){
drh488cddf2018-10-06 14:38:17 +00003602 if( azHelp[i][0]=='.' || zPattern[0] ){
drh98aa2ab2018-09-26 16:53:51 +00003603 utf8_printf(out, "%s\n", azHelp[i]);
3604 n++;
3605 }
3606 }
3607 }else{
3608 /* Look for commands that for which zPattern is an exact prefix */
3609 zPat = sqlite3_mprintf(".%s*", zPattern);
3610 for(i=0; i<ArraySize(azHelp); i++){
3611 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3612 utf8_printf(out, "%s\n", azHelp[i]);
drheb7f2a02018-09-26 18:02:32 +00003613 j = i+1;
drh98aa2ab2018-09-26 16:53:51 +00003614 n++;
3615 }
3616 }
3617 sqlite3_free(zPat);
drheb7f2a02018-09-26 18:02:32 +00003618 if( n ){
3619 if( n==1 ){
3620 /* when zPattern is a prefix of exactly one command, then include the
3621 ** details of that command, which should begin at offset j */
3622 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3623 utf8_printf(out, "%s\n", azHelp[j]);
3624 j++;
3625 }
3626 }
3627 return n;
3628 }
3629 /* Look for commands that contain zPattern anywhere. Show the complete
3630 ** text of all commands that match. */
drh98aa2ab2018-09-26 16:53:51 +00003631 zPat = sqlite3_mprintf("%%%s%%", zPattern);
3632 for(i=0; i<ArraySize(azHelp); i++){
3633 if( azHelp[i][0]=='.' ) j = i;
3634 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3635 utf8_printf(out, "%s\n", azHelp[j]);
3636 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3637 j++;
3638 utf8_printf(out, "%s\n", azHelp[j]);
3639 }
3640 i = j;
3641 n++;
3642 }
3643 }
3644 sqlite3_free(zPat);
3645 }
3646 return n;
3647}
drh2ce15c32017-07-11 13:34:40 +00003648
drh2ce15c32017-07-11 13:34:40 +00003649/* Forward reference */
drh60379d42018-12-13 18:30:01 +00003650static int process_input(ShellState *p);
drh2ce15c32017-07-11 13:34:40 +00003651
3652/*
3653** Read the content of file zName into memory obtained from sqlite3_malloc64()
3654** and return a pointer to the buffer. The caller is responsible for freeing
3655** the memory.
3656**
3657** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3658** read.
3659**
3660** For convenience, a nul-terminator byte is always appended to the data read
3661** from the file before the buffer is returned. This byte is not included in
3662** the final value of (*pnByte), if applicable.
3663**
3664** NULL is returned if any error is encountered. The final value of *pnByte
3665** is undefined in this case.
3666*/
3667static char *readFile(const char *zName, int *pnByte){
3668 FILE *in = fopen(zName, "rb");
3669 long nIn;
3670 size_t nRead;
3671 char *pBuf;
3672 if( in==0 ) return 0;
3673 fseek(in, 0, SEEK_END);
3674 nIn = ftell(in);
3675 rewind(in);
3676 pBuf = sqlite3_malloc64( nIn+1 );
drh1dbb1472018-10-11 10:37:24 +00003677 if( pBuf==0 ){ fclose(in); return 0; }
drh2ce15c32017-07-11 13:34:40 +00003678 nRead = fread(pBuf, nIn, 1, in);
3679 fclose(in);
3680 if( nRead!=1 ){
3681 sqlite3_free(pBuf);
3682 return 0;
3683 }
3684 pBuf[nIn] = 0;
3685 if( pnByte ) *pnByte = nIn;
3686 return pBuf;
3687}
3688
3689#if defined(SQLITE_ENABLE_SESSION)
3690/*
3691** Close a single OpenSession object and release all of its associated
3692** resources.
3693*/
3694static void session_close(OpenSession *pSession){
3695 int i;
3696 sqlite3session_delete(pSession->p);
3697 sqlite3_free(pSession->zName);
3698 for(i=0; i<pSession->nFilter; i++){
3699 sqlite3_free(pSession->azFilter[i]);
3700 }
3701 sqlite3_free(pSession->azFilter);
3702 memset(pSession, 0, sizeof(OpenSession));
3703}
3704#endif
3705
3706/*
3707** Close all OpenSession objects and release all associated resources.
3708*/
3709#if defined(SQLITE_ENABLE_SESSION)
3710static void session_close_all(ShellState *p){
3711 int i;
3712 for(i=0; i<p->nSession; i++){
3713 session_close(&p->aSession[i]);
3714 }
3715 p->nSession = 0;
3716}
3717#else
3718# define session_close_all(X)
3719#endif
3720
3721/*
3722** Implementation of the xFilter function for an open session. Omit
3723** any tables named by ".session filter" but let all other table through.
3724*/
3725#if defined(SQLITE_ENABLE_SESSION)
3726static int session_filter(void *pCtx, const char *zTab){
3727 OpenSession *pSession = (OpenSession*)pCtx;
3728 int i;
3729 for(i=0; i<pSession->nFilter; i++){
3730 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3731 }
3732 return 1;
3733}
3734#endif
3735
3736/*
drh1fa6d9f2018-01-06 21:46:01 +00003737** Try to deduce the type of file for zName based on its content. Return
3738** one of the SHELL_OPEN_* constants.
drh1bf208c2018-03-09 21:54:01 +00003739**
3740** If the file does not exist or is empty but its name looks like a ZIP
3741** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3742** Otherwise, assume an ordinary database regardless of the filename if
3743** the type cannot be determined from content.
drh1fa6d9f2018-01-06 21:46:01 +00003744*/
drhfc97c1c2018-05-14 00:41:12 +00003745int deduceDatabaseType(const char *zName, int dfltZip){
drh1fa6d9f2018-01-06 21:46:01 +00003746 FILE *f = fopen(zName, "rb");
3747 size_t n;
3748 int rc = SHELL_OPEN_UNSPEC;
3749 char zBuf[100];
drh1bf208c2018-03-09 21:54:01 +00003750 if( f==0 ){
drhbe4ccb22018-05-17 20:04:24 +00003751 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3752 return SHELL_OPEN_ZIPFILE;
3753 }else{
3754 return SHELL_OPEN_NORMAL;
3755 }
drh1bf208c2018-03-09 21:54:01 +00003756 }
drh2b3c4af2018-10-30 14:36:21 +00003757 n = fread(zBuf, 16, 1, f);
3758 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
3759 fclose(f);
3760 return SHELL_OPEN_NORMAL;
3761 }
drh1fa6d9f2018-01-06 21:46:01 +00003762 fseek(f, -25, SEEK_END);
3763 n = fread(zBuf, 25, 1, f);
3764 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3765 rc = SHELL_OPEN_APPENDVFS;
3766 }else{
3767 fseek(f, -22, SEEK_END);
3768 n = fread(zBuf, 22, 1, f);
3769 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3770 && zBuf[3]==0x06 ){
3771 rc = SHELL_OPEN_ZIPFILE;
drh1bf208c2018-03-09 21:54:01 +00003772 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
mistachkina3926f42018-05-14 12:23:04 +00003773 rc = SHELL_OPEN_ZIPFILE;
drh1fa6d9f2018-01-06 21:46:01 +00003774 }
3775 }
3776 fclose(f);
3777 return rc;
3778}
3779
drh33746482018-12-13 15:06:26 +00003780#ifdef SQLITE_ENABLE_DESERIALIZE
3781/*
3782** Reconstruct an in-memory database using the output from the "dbtotxt"
3783** program. Read content from the file in p->zDbFilename. If p->zDbFilename
3784** is 0, then read from standard input.
3785*/
3786static unsigned char *readHexDb(ShellState *p, int *pnData){
3787 unsigned char *a = 0;
drh2c8ee022018-12-13 18:59:30 +00003788 int nLine;
drh33746482018-12-13 15:06:26 +00003789 int n = 0;
3790 int pgsz = 0;
3791 int iOffset = 0;
3792 int j, k;
3793 int rc;
3794 FILE *in;
3795 unsigned char x[16];
drh2c8ee022018-12-13 18:59:30 +00003796 char zLine[1000];
drh33746482018-12-13 15:06:26 +00003797 if( p->zDbFilename ){
3798 in = fopen(p->zDbFilename, "r");
3799 if( in==0 ){
3800 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
3801 return 0;
3802 }
drh2c8ee022018-12-13 18:59:30 +00003803 nLine = 0;
drh33746482018-12-13 15:06:26 +00003804 }else{
drh60379d42018-12-13 18:30:01 +00003805 in = p->in;
drh2c8ee022018-12-13 18:59:30 +00003806 nLine = p->lineno;
drh33746482018-12-13 15:06:26 +00003807 }
3808 *pnData = 0;
drh2c8ee022018-12-13 18:59:30 +00003809 nLine++;
drh33746482018-12-13 15:06:26 +00003810 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
3811 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
3812 if( rc!=2 ) goto readHexDb_error;
3813 if( n<=0 ) goto readHexDb_error;
3814 a = sqlite3_malloc( n );
3815 if( a==0 ){
3816 utf8_printf(stderr, "Out of memory!\n");
3817 goto readHexDb_error;
3818 }
3819 memset(a, 0, n);
3820 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
3821 utf8_printf(stderr, "invalid pagesize\n");
3822 goto readHexDb_error;
3823 }
drh2c8ee022018-12-13 18:59:30 +00003824 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
drh33746482018-12-13 15:06:26 +00003825 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
3826 if( rc==2 ){
3827 iOffset = k;
3828 continue;
3829 }
3830 if( strncmp(zLine, "| end ", 6)==0 ){
3831 break;
3832 }
3833 rc = sscanf(zLine,"| %d: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx"
3834 " %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx",
3835 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
3836 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
3837 if( rc==17 ){
3838 k = iOffset+j;
drhf354e772018-12-13 22:58:52 +00003839 if( k+16<=n ){
3840 memcpy(a+k, x, 16);
drh33746482018-12-13 15:06:26 +00003841 }
drh33746482018-12-13 15:06:26 +00003842 }
3843 }
3844 *pnData = n;
drh2c8ee022018-12-13 18:59:30 +00003845 if( in!=p->in ){
3846 fclose(in);
3847 }else{
3848 p->lineno = nLine;
3849 }
drh33746482018-12-13 15:06:26 +00003850 return a;
3851
3852readHexDb_error:
3853 if( in!=stdin ){
3854 fclose(in);
3855 }else{
drh60379d42018-12-13 18:30:01 +00003856 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
drh2c8ee022018-12-13 18:59:30 +00003857 nLine++;
drh33746482018-12-13 15:06:26 +00003858 if(strncmp(zLine, "| end ", 6)==0 ) break;
3859 }
drh2c8ee022018-12-13 18:59:30 +00003860 p->lineno = nLine;
drh33746482018-12-13 15:06:26 +00003861 }
3862 sqlite3_free(a);
3863 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
3864 return 0;
3865}
3866#endif /* SQLITE_ENABLE_DESERIALIZE */
3867
drhbe4ccb22018-05-17 20:04:24 +00003868/* Flags for open_db().
3869**
3870** The default behavior of open_db() is to exit(1) if the database fails to
3871** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
3872** but still returns without calling exit.
3873**
3874** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
3875** ZIP archive if the file does not exist or is empty and its name matches
3876** the *.zip pattern.
3877*/
3878#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
3879#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
3880
drh1fa6d9f2018-01-06 21:46:01 +00003881/*
drh2ce15c32017-07-11 13:34:40 +00003882** Make sure the database is open. If it is not, then open it. If
3883** the database fails to open, print an error message and exit.
3884*/
drhbe4ccb22018-05-17 20:04:24 +00003885static void open_db(ShellState *p, int openFlags){
drh2ce15c32017-07-11 13:34:40 +00003886 if( p->db==0 ){
drhf2072d12018-05-11 15:10:11 +00003887 if( p->openMode==SHELL_OPEN_UNSPEC ){
3888 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
3889 p->openMode = SHELL_OPEN_NORMAL;
drhbe4ccb22018-05-17 20:04:24 +00003890 }else{
3891 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
3892 (openFlags & OPEN_DB_ZIPFILE)!=0);
drhf2072d12018-05-11 15:10:11 +00003893 }
drh1fa6d9f2018-01-06 21:46:01 +00003894 }
3895 switch( p->openMode ){
3896 case SHELL_OPEN_APPENDVFS: {
3897 sqlite3_open_v2(p->zDbFilename, &p->db,
3898 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
3899 break;
3900 }
drh33746482018-12-13 15:06:26 +00003901 case SHELL_OPEN_HEXDB:
drh60f34ae2018-10-30 13:19:49 +00003902 case SHELL_OPEN_DESERIALIZE: {
3903 sqlite3_open(0, &p->db);
3904 break;
3905 }
drh1fa6d9f2018-01-06 21:46:01 +00003906 case SHELL_OPEN_ZIPFILE: {
3907 sqlite3_open(":memory:", &p->db);
3908 break;
3909 }
drhee269a62018-02-14 23:27:43 +00003910 case SHELL_OPEN_READONLY: {
3911 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
3912 break;
3913 }
drh1fa6d9f2018-01-06 21:46:01 +00003914 case SHELL_OPEN_UNSPEC:
3915 case SHELL_OPEN_NORMAL: {
3916 sqlite3_open(p->zDbFilename, &p->db);
3917 break;
3918 }
3919 }
drh2ce15c32017-07-11 13:34:40 +00003920 globalDb = p->db;
3921 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3922 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3923 p->zDbFilename, sqlite3_errmsg(p->db));
drhf25cc4f2019-01-04 14:29:21 +00003924 if( openFlags & OPEN_DB_KEEPALIVE ){
3925 sqlite3_open(":memory:", &p->db);
3926 return;
3927 }
drh2ce15c32017-07-11 13:34:40 +00003928 exit(1);
3929 }
3930#ifndef SQLITE_OMIT_LOAD_EXTENSION
3931 sqlite3_enable_load_extension(p->db, 1);
3932#endif
3933 sqlite3_fileio_init(p->db, 0, 0);
3934 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00003935 sqlite3_completion_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003936#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00003937 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00003938 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003939#endif
drhceba7922018-01-01 21:28:25 +00003940 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00003941 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00003942 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3943 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00003944 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
3945 shellPutsFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00003946#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00003947 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
3948 editFunc, 0, 0);
3949 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
3950 editFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00003951#endif
drh1fa6d9f2018-01-06 21:46:01 +00003952 if( p->openMode==SHELL_OPEN_ZIPFILE ){
3953 char *zSql = sqlite3_mprintf(
3954 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
3955 sqlite3_exec(p->db, zSql, 0, 0, 0);
3956 sqlite3_free(zSql);
drha751f392018-10-30 15:31:22 +00003957 }
3958#ifdef SQLITE_ENABLE_DESERIALIZE
drh33746482018-12-13 15:06:26 +00003959 else
3960 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
mistachkin99490932018-12-17 22:19:57 +00003961 int rc;
drh60f34ae2018-10-30 13:19:49 +00003962 int nData = 0;
drh33746482018-12-13 15:06:26 +00003963 unsigned char *aData;
3964 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
3965 aData = (unsigned char*)readFile(p->zDbFilename, &nData);
3966 }else{
3967 aData = readHexDb(p, &nData);
3968 if( aData==0 ){
3969 utf8_printf(stderr, "Error in hexdb input\n");
3970 return;
3971 }
3972 }
mistachkin99490932018-12-17 22:19:57 +00003973 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
drh60f34ae2018-10-30 13:19:49 +00003974 SQLITE_DESERIALIZE_RESIZEABLE |
3975 SQLITE_DESERIALIZE_FREEONCLOSE);
3976 if( rc ){
3977 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
3978 }
drh6ca64482019-01-22 16:06:20 +00003979 if( p->szMax>0 ){
3980 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
3981 }
drh1fa6d9f2018-01-06 21:46:01 +00003982 }
drha751f392018-10-30 15:31:22 +00003983#endif
drh2ce15c32017-07-11 13:34:40 +00003984 }
3985}
3986
drh9e804032018-05-18 17:11:50 +00003987/*
3988** Attempt to close the databaes connection. Report errors.
3989*/
3990void close_db(sqlite3 *db){
3991 int rc = sqlite3_close(db);
3992 if( rc ){
3993 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
3994 rc, sqlite3_errmsg(db));
3995 }
3996}
3997
drh56eb09b2017-07-11 13:59:07 +00003998#if HAVE_READLINE || HAVE_EDITLINE
3999/*
4000** Readline completion callbacks
4001*/
4002static char *readline_completion_generator(const char *text, int state){
4003 static sqlite3_stmt *pStmt = 0;
4004 char *zRet;
4005 if( state==0 ){
4006 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00004007 sqlite3_finalize(pStmt);
4008 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4009 " FROM completion(%Q) ORDER BY 1", text);
4010 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4011 sqlite3_free(zSql);
4012 }
4013 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00004014 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00004015 }else{
4016 sqlite3_finalize(pStmt);
4017 pStmt = 0;
4018 zRet = 0;
4019 }
4020 return zRet;
4021}
4022static char **readline_completion(const char *zText, int iStart, int iEnd){
4023 rl_attempted_completion_over = 1;
4024 return rl_completion_matches(zText, readline_completion_generator);
4025}
4026
4027#elif HAVE_LINENOISE
4028/*
4029** Linenoise completion callback
4030*/
4031static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00004032 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00004033 int i, iStart;
4034 sqlite3_stmt *pStmt = 0;
4035 char *zSql;
4036 char zBuf[1000];
4037
4038 if( nLine>sizeof(zBuf)-30 ) return;
drh1615c372018-05-12 23:56:22 +00004039 if( zLine[0]=='.' || zLine[0]=='#') return;
drh56eb09b2017-07-11 13:59:07 +00004040 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4041 if( i==nLine-1 ) return;
4042 iStart = i+1;
4043 memcpy(zBuf, zLine, iStart);
4044 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4045 " FROM completion(%Q,%Q) ORDER BY 1",
4046 &zLine[iStart], zLine);
4047 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4048 sqlite3_free(zSql);
4049 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4050 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4051 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4052 int nCompletion = sqlite3_column_bytes(pStmt, 0);
4053 if( iStart+nCompletion < sizeof(zBuf)-1 ){
4054 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4055 linenoiseAddCompletion(lc, zBuf);
4056 }
4057 }
4058 sqlite3_finalize(pStmt);
4059}
4060#endif
4061
drh2ce15c32017-07-11 13:34:40 +00004062/*
4063** Do C-language style dequoting.
4064**
4065** \a -> alarm
4066** \b -> backspace
4067** \t -> tab
4068** \n -> newline
4069** \v -> vertical tab
4070** \f -> form feed
4071** \r -> carriage return
4072** \s -> space
4073** \" -> "
4074** \' -> '
4075** \\ -> backslash
4076** \NNN -> ascii character NNN in octal
4077*/
4078static void resolve_backslashes(char *z){
4079 int i, j;
4080 char c;
4081 while( *z && *z!='\\' ) z++;
4082 for(i=j=0; (c = z[i])!=0; i++, j++){
4083 if( c=='\\' && z[i+1]!=0 ){
4084 c = z[++i];
4085 if( c=='a' ){
4086 c = '\a';
4087 }else if( c=='b' ){
4088 c = '\b';
4089 }else if( c=='t' ){
4090 c = '\t';
4091 }else if( c=='n' ){
4092 c = '\n';
4093 }else if( c=='v' ){
4094 c = '\v';
4095 }else if( c=='f' ){
4096 c = '\f';
4097 }else if( c=='r' ){
4098 c = '\r';
4099 }else if( c=='"' ){
4100 c = '"';
4101 }else if( c=='\'' ){
4102 c = '\'';
4103 }else if( c=='\\' ){
4104 c = '\\';
4105 }else if( c>='0' && c<='7' ){
4106 c -= '0';
4107 if( z[i+1]>='0' && z[i+1]<='7' ){
4108 i++;
4109 c = (c<<3) + z[i] - '0';
4110 if( z[i+1]>='0' && z[i+1]<='7' ){
4111 i++;
4112 c = (c<<3) + z[i] - '0';
4113 }
4114 }
4115 }
4116 }
4117 z[j] = c;
4118 }
4119 if( j<i ) z[j] = 0;
4120}
4121
4122/*
drh2ce15c32017-07-11 13:34:40 +00004123** Interpret zArg as either an integer or a boolean value. Return 1 or 0
4124** for TRUE and FALSE. Return the integer value if appropriate.
4125*/
4126static int booleanValue(const char *zArg){
4127 int i;
4128 if( zArg[0]=='0' && zArg[1]=='x' ){
4129 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4130 }else{
4131 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4132 }
4133 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4134 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4135 return 1;
4136 }
4137 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4138 return 0;
4139 }
4140 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4141 zArg);
4142 return 0;
4143}
4144
4145/*
4146** Set or clear a shell flag according to a boolean value.
4147*/
4148static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4149 if( booleanValue(zArg) ){
4150 ShellSetFlag(p, mFlag);
4151 }else{
4152 ShellClearFlag(p, mFlag);
4153 }
4154}
4155
4156/*
4157** Close an output file, assuming it is not stderr or stdout
4158*/
4159static void output_file_close(FILE *f){
4160 if( f && f!=stdout && f!=stderr ) fclose(f);
4161}
4162
4163/*
4164** Try to open an output file. The names "stdout" and "stderr" are
4165** recognized and do the right thing. NULL is returned if the output
4166** filename is "off".
4167*/
drha92a01a2018-01-10 22:15:37 +00004168static FILE *output_file_open(const char *zFile, int bTextMode){
drh2ce15c32017-07-11 13:34:40 +00004169 FILE *f;
4170 if( strcmp(zFile,"stdout")==0 ){
4171 f = stdout;
4172 }else if( strcmp(zFile, "stderr")==0 ){
4173 f = stderr;
4174 }else if( strcmp(zFile, "off")==0 ){
4175 f = 0;
4176 }else{
drha92a01a2018-01-10 22:15:37 +00004177 f = fopen(zFile, bTextMode ? "w" : "wb");
drh2ce15c32017-07-11 13:34:40 +00004178 if( f==0 ){
4179 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4180 }
4181 }
4182 return f;
4183}
4184
drh707821f2018-12-05 13:39:06 +00004185#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00004186/*
4187** A routine for handling output from sqlite3_trace().
4188*/
4189static int sql_trace_callback(
drh707821f2018-12-05 13:39:06 +00004190 unsigned mType, /* The trace type */
4191 void *pArg, /* The ShellState pointer */
4192 void *pP, /* Usually a pointer to sqlite_stmt */
4193 void *pX /* Auxiliary output */
drh2ce15c32017-07-11 13:34:40 +00004194){
drh707821f2018-12-05 13:39:06 +00004195 ShellState *p = (ShellState*)pArg;
4196 sqlite3_stmt *pStmt;
4197 const char *zSql;
4198 int nSql;
4199 if( p->traceOut==0 ) return 0;
4200 if( mType==SQLITE_TRACE_CLOSE ){
4201 utf8_printf(p->traceOut, "-- closing database connection\n");
4202 return 0;
4203 }
4204 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4205 zSql = (const char*)pX;
4206 }else{
4207 pStmt = (sqlite3_stmt*)pP;
4208 switch( p->eTraceType ){
4209 case SHELL_TRACE_EXPANDED: {
4210 zSql = sqlite3_expanded_sql(pStmt);
4211 break;
4212 }
4213#ifdef SQLITE_ENABLE_NORMALIZE
4214 case SHELL_TRACE_NORMALIZED: {
4215 zSql = sqlite3_normalized_sql(pStmt);
4216 break;
4217 }
4218#endif
4219 default: {
4220 zSql = sqlite3_sql(pStmt);
4221 break;
4222 }
4223 }
4224 }
4225 if( zSql==0 ) return 0;
4226 nSql = strlen30(zSql);
4227 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4228 switch( mType ){
4229 case SQLITE_TRACE_ROW:
4230 case SQLITE_TRACE_STMT: {
4231 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4232 break;
4233 }
4234 case SQLITE_TRACE_PROFILE: {
4235 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4236 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4237 break;
4238 }
drh2ce15c32017-07-11 13:34:40 +00004239 }
4240 return 0;
4241}
4242#endif
drh2ce15c32017-07-11 13:34:40 +00004243
4244/*
4245** A no-op routine that runs with the ".breakpoint" doc-command. This is
4246** a useful spot to set a debugger breakpoint.
4247*/
4248static void test_breakpoint(void){
4249 static int nCall = 0;
4250 nCall++;
4251}
4252
4253/*
4254** An object used to read a CSV and other files for import.
4255*/
4256typedef struct ImportCtx ImportCtx;
4257struct ImportCtx {
4258 const char *zFile; /* Name of the input file */
4259 FILE *in; /* Read the CSV text from this input stream */
4260 char *z; /* Accumulated text for a field */
4261 int n; /* Number of bytes in z */
4262 int nAlloc; /* Space allocated for z[] */
4263 int nLine; /* Current line number */
4264 int bNotFirst; /* True if one or more bytes already read */
4265 int cTerm; /* Character that terminated the most recent field */
4266 int cColSep; /* The column separator character. (Usually ",") */
4267 int cRowSep; /* The row separator character. (Usually "\n") */
4268};
4269
4270/* Append a single byte to z[] */
4271static void import_append_char(ImportCtx *p, int c){
4272 if( p->n+1>=p->nAlloc ){
4273 p->nAlloc += p->nAlloc + 100;
4274 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drh4b5345c2018-04-24 13:07:40 +00004275 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004276 }
4277 p->z[p->n++] = (char)c;
4278}
4279
4280/* Read a single field of CSV text. Compatible with rfc4180 and extended
4281** with the option of having a separator other than ",".
4282**
4283** + Input comes from p->in.
4284** + Store results in p->z of length p->n. Space to hold p->z comes
4285** from sqlite3_malloc64().
4286** + Use p->cSep as the column separator. The default is ",".
4287** + Use p->rSep as the row separator. The default is "\n".
4288** + Keep track of the line number in p->nLine.
4289** + Store the character that terminates the field in p->cTerm. Store
4290** EOF on end-of-file.
4291** + Report syntax errors on stderr
4292*/
4293static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4294 int c;
4295 int cSep = p->cColSep;
4296 int rSep = p->cRowSep;
4297 p->n = 0;
4298 c = fgetc(p->in);
4299 if( c==EOF || seenInterrupt ){
4300 p->cTerm = EOF;
4301 return 0;
4302 }
4303 if( c=='"' ){
4304 int pc, ppc;
4305 int startLine = p->nLine;
4306 int cQuote = c;
4307 pc = ppc = 0;
4308 while( 1 ){
4309 c = fgetc(p->in);
4310 if( c==rSep ) p->nLine++;
4311 if( c==cQuote ){
4312 if( pc==cQuote ){
4313 pc = 0;
4314 continue;
4315 }
4316 }
4317 if( (c==cSep && pc==cQuote)
4318 || (c==rSep && pc==cQuote)
4319 || (c==rSep && pc=='\r' && ppc==cQuote)
4320 || (c==EOF && pc==cQuote)
4321 ){
4322 do{ p->n--; }while( p->z[p->n]!=cQuote );
4323 p->cTerm = c;
4324 break;
4325 }
4326 if( pc==cQuote && c!='\r' ){
4327 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4328 p->zFile, p->nLine, cQuote);
4329 }
4330 if( c==EOF ){
4331 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4332 p->zFile, startLine, cQuote);
4333 p->cTerm = c;
4334 break;
4335 }
4336 import_append_char(p, c);
4337 ppc = pc;
4338 pc = c;
4339 }
4340 }else{
4341 /* If this is the first field being parsed and it begins with the
4342 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4343 if( (c&0xff)==0xef && p->bNotFirst==0 ){
4344 import_append_char(p, c);
4345 c = fgetc(p->in);
4346 if( (c&0xff)==0xbb ){
4347 import_append_char(p, c);
4348 c = fgetc(p->in);
4349 if( (c&0xff)==0xbf ){
4350 p->bNotFirst = 1;
4351 p->n = 0;
4352 return csv_read_one_field(p);
4353 }
4354 }
4355 }
4356 while( c!=EOF && c!=cSep && c!=rSep ){
4357 import_append_char(p, c);
4358 c = fgetc(p->in);
4359 }
4360 if( c==rSep ){
4361 p->nLine++;
4362 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4363 }
4364 p->cTerm = c;
4365 }
4366 if( p->z ) p->z[p->n] = 0;
4367 p->bNotFirst = 1;
4368 return p->z;
4369}
4370
4371/* Read a single field of ASCII delimited text.
4372**
4373** + Input comes from p->in.
4374** + Store results in p->z of length p->n. Space to hold p->z comes
4375** from sqlite3_malloc64().
4376** + Use p->cSep as the column separator. The default is "\x1F".
4377** + Use p->rSep as the row separator. The default is "\x1E".
4378** + Keep track of the row number in p->nLine.
4379** + Store the character that terminates the field in p->cTerm. Store
4380** EOF on end-of-file.
4381** + Report syntax errors on stderr
4382*/
4383static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4384 int c;
4385 int cSep = p->cColSep;
4386 int rSep = p->cRowSep;
4387 p->n = 0;
4388 c = fgetc(p->in);
4389 if( c==EOF || seenInterrupt ){
4390 p->cTerm = EOF;
4391 return 0;
4392 }
4393 while( c!=EOF && c!=cSep && c!=rSep ){
4394 import_append_char(p, c);
4395 c = fgetc(p->in);
4396 }
4397 if( c==rSep ){
4398 p->nLine++;
4399 }
4400 p->cTerm = c;
4401 if( p->z ) p->z[p->n] = 0;
4402 return p->z;
4403}
4404
4405/*
4406** Try to transfer data for table zTable. If an error is seen while
4407** moving forward, try to go backwards. The backwards movement won't
4408** work for WITHOUT ROWID tables.
4409*/
4410static void tryToCloneData(
4411 ShellState *p,
4412 sqlite3 *newDb,
4413 const char *zTable
4414){
4415 sqlite3_stmt *pQuery = 0;
4416 sqlite3_stmt *pInsert = 0;
4417 char *zQuery = 0;
4418 char *zInsert = 0;
4419 int rc;
4420 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00004421 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00004422 int k = 0;
4423 int cnt = 0;
4424 const int spinRate = 10000;
4425
4426 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4427 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4428 if( rc ){
4429 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4430 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4431 zQuery);
4432 goto end_data_xfer;
4433 }
4434 n = sqlite3_column_count(pQuery);
4435 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh4b5345c2018-04-24 13:07:40 +00004436 if( zInsert==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004437 sqlite3_snprintf(200+nTable,zInsert,
4438 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00004439 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00004440 for(j=1; j<n; j++){
4441 memcpy(zInsert+i, ",?", 2);
4442 i += 2;
4443 }
4444 memcpy(zInsert+i, ");", 3);
4445 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4446 if( rc ){
4447 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4448 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4449 zQuery);
4450 goto end_data_xfer;
4451 }
4452 for(k=0; k<2; k++){
4453 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4454 for(i=0; i<n; i++){
4455 switch( sqlite3_column_type(pQuery, i) ){
4456 case SQLITE_NULL: {
4457 sqlite3_bind_null(pInsert, i+1);
4458 break;
4459 }
4460 case SQLITE_INTEGER: {
4461 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4462 break;
4463 }
4464 case SQLITE_FLOAT: {
4465 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4466 break;
4467 }
4468 case SQLITE_TEXT: {
4469 sqlite3_bind_text(pInsert, i+1,
4470 (const char*)sqlite3_column_text(pQuery,i),
4471 -1, SQLITE_STATIC);
4472 break;
4473 }
4474 case SQLITE_BLOB: {
4475 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4476 sqlite3_column_bytes(pQuery,i),
4477 SQLITE_STATIC);
4478 break;
4479 }
4480 }
4481 } /* End for */
4482 rc = sqlite3_step(pInsert);
4483 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4484 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4485 sqlite3_errmsg(newDb));
4486 }
4487 sqlite3_reset(pInsert);
4488 cnt++;
4489 if( (cnt%spinRate)==0 ){
4490 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4491 fflush(stdout);
4492 }
4493 } /* End while */
4494 if( rc==SQLITE_DONE ) break;
4495 sqlite3_finalize(pQuery);
4496 sqlite3_free(zQuery);
4497 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4498 zTable);
4499 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4500 if( rc ){
4501 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4502 break;
4503 }
4504 } /* End for(k=0...) */
4505
4506end_data_xfer:
4507 sqlite3_finalize(pQuery);
4508 sqlite3_finalize(pInsert);
4509 sqlite3_free(zQuery);
4510 sqlite3_free(zInsert);
4511}
4512
4513
4514/*
4515** Try to transfer all rows of the schema that match zWhere. For
4516** each row, invoke xForEach() on the object defined by that row.
4517** If an error is encountered while moving forward through the
4518** sqlite_master table, try again moving backwards.
4519*/
4520static void tryToCloneSchema(
4521 ShellState *p,
4522 sqlite3 *newDb,
4523 const char *zWhere,
4524 void (*xForEach)(ShellState*,sqlite3*,const char*)
4525){
4526 sqlite3_stmt *pQuery = 0;
4527 char *zQuery = 0;
4528 int rc;
4529 const unsigned char *zName;
4530 const unsigned char *zSql;
4531 char *zErrMsg = 0;
4532
4533 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4534 " WHERE %s", zWhere);
4535 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4536 if( rc ){
4537 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4538 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4539 zQuery);
4540 goto end_schema_xfer;
4541 }
4542 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4543 zName = sqlite3_column_text(pQuery, 0);
4544 zSql = sqlite3_column_text(pQuery, 1);
4545 printf("%s... ", zName); fflush(stdout);
4546 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4547 if( zErrMsg ){
4548 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4549 sqlite3_free(zErrMsg);
4550 zErrMsg = 0;
4551 }
4552 if( xForEach ){
4553 xForEach(p, newDb, (const char*)zName);
4554 }
4555 printf("done\n");
4556 }
4557 if( rc!=SQLITE_DONE ){
4558 sqlite3_finalize(pQuery);
4559 sqlite3_free(zQuery);
4560 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4561 " WHERE %s ORDER BY rowid DESC", zWhere);
4562 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4563 if( rc ){
4564 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4565 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4566 zQuery);
4567 goto end_schema_xfer;
4568 }
4569 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4570 zName = sqlite3_column_text(pQuery, 0);
4571 zSql = sqlite3_column_text(pQuery, 1);
4572 printf("%s... ", zName); fflush(stdout);
4573 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4574 if( zErrMsg ){
4575 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4576 sqlite3_free(zErrMsg);
4577 zErrMsg = 0;
4578 }
4579 if( xForEach ){
4580 xForEach(p, newDb, (const char*)zName);
4581 }
4582 printf("done\n");
4583 }
4584 }
4585end_schema_xfer:
4586 sqlite3_finalize(pQuery);
4587 sqlite3_free(zQuery);
4588}
4589
4590/*
4591** Open a new database file named "zNewDb". Try to recover as much information
4592** as possible out of the main database (which might be corrupt) and write it
4593** into zNewDb.
4594*/
4595static void tryToClone(ShellState *p, const char *zNewDb){
4596 int rc;
4597 sqlite3 *newDb = 0;
4598 if( access(zNewDb,0)==0 ){
4599 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4600 return;
4601 }
4602 rc = sqlite3_open(zNewDb, &newDb);
4603 if( rc ){
4604 utf8_printf(stderr, "Cannot create output database: %s\n",
4605 sqlite3_errmsg(newDb));
4606 }else{
4607 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4608 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4609 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4610 tryToCloneSchema(p, newDb, "type!='table'", 0);
4611 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4612 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4613 }
drh9e804032018-05-18 17:11:50 +00004614 close_db(newDb);
drh2ce15c32017-07-11 13:34:40 +00004615}
4616
4617/*
drh13c20932018-01-10 21:41:55 +00004618** Change the output file back to stdout.
4619**
4620** If the p->doXdgOpen flag is set, that means the output was being
4621** redirected to a temporary file named by p->zTempFile. In that case,
4622** launch start/open/xdg-open on that temporary file.
drh2ce15c32017-07-11 13:34:40 +00004623*/
4624static void output_reset(ShellState *p){
4625 if( p->outfile[0]=='|' ){
4626#ifndef SQLITE_OMIT_POPEN
4627 pclose(p->out);
4628#endif
4629 }else{
4630 output_file_close(p->out);
drh04a28c32018-01-31 01:38:44 +00004631#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00004632 if( p->doXdgOpen ){
4633 const char *zXdgOpenCmd =
4634#if defined(_WIN32)
4635 "start";
4636#elif defined(__APPLE__)
4637 "open";
4638#else
4639 "xdg-open";
4640#endif
4641 char *zCmd;
4642 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
drha92a01a2018-01-10 22:15:37 +00004643 if( system(zCmd) ){
4644 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4645 }
drh13c20932018-01-10 21:41:55 +00004646 sqlite3_free(zCmd);
drh3c484e82018-01-10 22:27:21 +00004647 outputModePop(p);
drh13c20932018-01-10 21:41:55 +00004648 p->doXdgOpen = 0;
4649 }
drh04a28c32018-01-31 01:38:44 +00004650#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00004651 }
4652 p->outfile[0] = 0;
4653 p->out = stdout;
4654}
4655
4656/*
4657** Run an SQL command and return the single integer result.
4658*/
4659static int db_int(ShellState *p, const char *zSql){
4660 sqlite3_stmt *pStmt;
4661 int res = 0;
4662 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4663 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4664 res = sqlite3_column_int(pStmt,0);
4665 }
4666 sqlite3_finalize(pStmt);
4667 return res;
4668}
4669
4670/*
4671** Convert a 2-byte or 4-byte big-endian integer into a native integer
4672*/
4673static unsigned int get2byteInt(unsigned char *a){
4674 return (a[0]<<8) + a[1];
4675}
4676static unsigned int get4byteInt(unsigned char *a){
4677 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4678}
4679
4680/*
4681** Implementation of the ".info" command.
4682**
4683** Return 1 on error, 2 to exit, and 0 otherwise.
4684*/
4685static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4686 static const struct { const char *zName; int ofst; } aField[] = {
4687 { "file change counter:", 24 },
4688 { "database page count:", 28 },
4689 { "freelist page count:", 36 },
4690 { "schema cookie:", 40 },
4691 { "schema format:", 44 },
4692 { "default cache size:", 48 },
4693 { "autovacuum top root:", 52 },
4694 { "incremental vacuum:", 64 },
4695 { "text encoding:", 56 },
4696 { "user version:", 60 },
4697 { "application id:", 68 },
4698 { "software version:", 96 },
4699 };
4700 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4701 { "number of tables:",
4702 "SELECT count(*) FROM %s WHERE type='table'" },
4703 { "number of indexes:",
4704 "SELECT count(*) FROM %s WHERE type='index'" },
4705 { "number of triggers:",
4706 "SELECT count(*) FROM %s WHERE type='trigger'" },
4707 { "number of views:",
4708 "SELECT count(*) FROM %s WHERE type='view'" },
4709 { "schema size:",
4710 "SELECT total(length(sql)) FROM %s" },
4711 };
drh2ce15c32017-07-11 13:34:40 +00004712 int i;
drhea99a312018-07-18 19:09:07 +00004713 unsigned iDataVersion;
drh2ce15c32017-07-11 13:34:40 +00004714 char *zSchemaTab;
4715 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004716 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004717 unsigned char aHdr[100];
4718 open_db(p, 0);
4719 if( p->db==0 ) return 1;
drh512e6c32017-10-11 17:51:08 +00004720 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4721 -1, &pStmt, 0);
4722 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4723 if( sqlite3_step(pStmt)==SQLITE_ROW
4724 && sqlite3_column_bytes(pStmt,0)>100
4725 ){
4726 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4727 sqlite3_finalize(pStmt);
4728 }else{
drh2ce15c32017-07-11 13:34:40 +00004729 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004730 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004731 return 1;
4732 }
4733 i = get2byteInt(aHdr+16);
4734 if( i==1 ) i = 65536;
4735 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4736 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4737 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4738 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4739 for(i=0; i<ArraySize(aField); i++){
4740 int ofst = aField[i].ofst;
4741 unsigned int val = get4byteInt(aHdr + ofst);
4742 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4743 switch( ofst ){
4744 case 56: {
4745 if( val==1 ) raw_printf(p->out, " (utf8)");
4746 if( val==2 ) raw_printf(p->out, " (utf16le)");
4747 if( val==3 ) raw_printf(p->out, " (utf16be)");
4748 }
4749 }
4750 raw_printf(p->out, "\n");
4751 }
4752 if( zDb==0 ){
4753 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4754 }else if( strcmp(zDb,"temp")==0 ){
4755 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4756 }else{
4757 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4758 }
4759 for(i=0; i<ArraySize(aQuery); i++){
4760 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4761 int val = db_int(p, zSql);
4762 sqlite3_free(zSql);
4763 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4764 }
4765 sqlite3_free(zSchemaTab);
drhea99a312018-07-18 19:09:07 +00004766 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
4767 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
drh2ce15c32017-07-11 13:34:40 +00004768 return 0;
4769}
4770
4771/*
4772** Print the current sqlite3_errmsg() value to stderr and return 1.
4773*/
4774static int shellDatabaseError(sqlite3 *db){
4775 const char *zErr = sqlite3_errmsg(db);
4776 utf8_printf(stderr, "Error: %s\n", zErr);
4777 return 1;
4778}
4779
4780/*
drh2ce15c32017-07-11 13:34:40 +00004781** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4782** if they match and FALSE (0) if they do not match.
4783**
4784** Globbing rules:
4785**
4786** '*' Matches any sequence of zero or more characters.
4787**
4788** '?' Matches exactly one character.
4789**
4790** [...] Matches one character from the enclosed list of
4791** characters.
4792**
4793** [^...] Matches one character not in the enclosed list.
4794**
4795** '#' Matches any sequence of one or more digits with an
4796** optional + or - sign in front
4797**
4798** ' ' Any span of whitespace matches any other span of
4799** whitespace.
4800**
4801** Extra whitespace at the end of z[] is ignored.
4802*/
4803static int testcase_glob(const char *zGlob, const char *z){
4804 int c, c2;
4805 int invert;
4806 int seen;
4807
4808 while( (c = (*(zGlob++)))!=0 ){
4809 if( IsSpace(c) ){
4810 if( !IsSpace(*z) ) return 0;
4811 while( IsSpace(*zGlob) ) zGlob++;
4812 while( IsSpace(*z) ) z++;
4813 }else if( c=='*' ){
4814 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4815 if( c=='?' && (*(z++))==0 ) return 0;
4816 }
4817 if( c==0 ){
4818 return 1;
4819 }else if( c=='[' ){
4820 while( *z && testcase_glob(zGlob-1,z)==0 ){
4821 z++;
4822 }
4823 return (*z)!=0;
4824 }
4825 while( (c2 = (*(z++)))!=0 ){
4826 while( c2!=c ){
4827 c2 = *(z++);
4828 if( c2==0 ) return 0;
4829 }
4830 if( testcase_glob(zGlob,z) ) return 1;
4831 }
4832 return 0;
4833 }else if( c=='?' ){
4834 if( (*(z++))==0 ) return 0;
4835 }else if( c=='[' ){
4836 int prior_c = 0;
4837 seen = 0;
4838 invert = 0;
4839 c = *(z++);
4840 if( c==0 ) return 0;
4841 c2 = *(zGlob++);
4842 if( c2=='^' ){
4843 invert = 1;
4844 c2 = *(zGlob++);
4845 }
4846 if( c2==']' ){
4847 if( c==']' ) seen = 1;
4848 c2 = *(zGlob++);
4849 }
4850 while( c2 && c2!=']' ){
4851 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4852 c2 = *(zGlob++);
4853 if( c>=prior_c && c<=c2 ) seen = 1;
4854 prior_c = 0;
4855 }else{
4856 if( c==c2 ){
4857 seen = 1;
4858 }
4859 prior_c = c2;
4860 }
4861 c2 = *(zGlob++);
4862 }
4863 if( c2==0 || (seen ^ invert)==0 ) return 0;
4864 }else if( c=='#' ){
4865 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4866 if( !IsDigit(z[0]) ) return 0;
4867 z++;
4868 while( IsDigit(z[0]) ){ z++; }
4869 }else{
4870 if( c!=(*(z++)) ) return 0;
4871 }
4872 }
4873 while( IsSpace(*z) ){ z++; }
4874 return *z==0;
4875}
4876
4877
4878/*
4879** Compare the string as a command-line option with either one or two
4880** initial "-" characters.
4881*/
4882static int optionMatch(const char *zStr, const char *zOpt){
4883 if( zStr[0]!='-' ) return 0;
4884 zStr++;
4885 if( zStr[0]=='-' ) zStr++;
4886 return strcmp(zStr, zOpt)==0;
4887}
4888
4889/*
4890** Delete a file.
4891*/
4892int shellDeleteFile(const char *zFilename){
4893 int rc;
4894#ifdef _WIN32
4895 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4896 rc = _wunlink(z);
4897 sqlite3_free(z);
4898#else
4899 rc = unlink(zFilename);
4900#endif
4901 return rc;
4902}
4903
drh13c20932018-01-10 21:41:55 +00004904/*
4905** Try to delete the temporary file (if there is one) and free the
4906** memory used to hold the name of the temp file.
4907*/
4908static void clearTempFile(ShellState *p){
4909 if( p->zTempFile==0 ) return;
drh536c3452018-01-11 00:38:39 +00004910 if( p->doXdgOpen ) return;
drh13c20932018-01-10 21:41:55 +00004911 if( shellDeleteFile(p->zTempFile) ) return;
4912 sqlite3_free(p->zTempFile);
4913 p->zTempFile = 0;
4914}
4915
4916/*
4917** Create a new temp file name with the given suffix.
4918*/
4919static void newTempFile(ShellState *p, const char *zSuffix){
4920 clearTempFile(p);
4921 sqlite3_free(p->zTempFile);
4922 p->zTempFile = 0;
drh7f3bf8a2018-01-10 21:50:08 +00004923 if( p->db ){
4924 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
4925 }
drh13c20932018-01-10 21:41:55 +00004926 if( p->zTempFile==0 ){
4927 sqlite3_uint64 r;
4928 sqlite3_randomness(sizeof(r), &r);
4929 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
4930 }else{
4931 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
4932 }
4933 if( p->zTempFile==0 ){
4934 raw_printf(stderr, "out of memory\n");
4935 exit(1);
4936 }
4937}
4938
drh2ce15c32017-07-11 13:34:40 +00004939
4940/*
4941** The implementation of SQL scalar function fkey_collate_clause(), used
4942** by the ".lint fkey-indexes" command. This scalar function is always
4943** called with four arguments - the parent table name, the parent column name,
4944** the child table name and the child column name.
4945**
4946** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4947**
4948** If either of the named tables or columns do not exist, this function
4949** returns an empty string. An empty string is also returned if both tables
4950** and columns exist but have the same default collation sequence. Or,
4951** if both exist but the default collation sequences are different, this
4952** function returns the string " COLLATE <parent-collation>", where
4953** <parent-collation> is the default collation sequence of the parent column.
4954*/
4955static void shellFkeyCollateClause(
4956 sqlite3_context *pCtx,
4957 int nVal,
4958 sqlite3_value **apVal
4959){
4960 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4961 const char *zParent;
4962 const char *zParentCol;
4963 const char *zParentSeq;
4964 const char *zChild;
4965 const char *zChildCol;
4966 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4967 int rc;
4968
4969 assert( nVal==4 );
4970 zParent = (const char*)sqlite3_value_text(apVal[0]);
4971 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4972 zChild = (const char*)sqlite3_value_text(apVal[2]);
4973 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4974
4975 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4976 rc = sqlite3_table_column_metadata(
4977 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4978 );
4979 if( rc==SQLITE_OK ){
4980 rc = sqlite3_table_column_metadata(
4981 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4982 );
4983 }
4984
4985 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4986 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4987 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4988 sqlite3_free(z);
4989 }
4990}
4991
4992
4993/*
4994** The implementation of dot-command ".lint fkey-indexes".
4995*/
4996static int lintFkeyIndexes(
4997 ShellState *pState, /* Current shell tool state */
4998 char **azArg, /* Array of arguments passed to dot command */
4999 int nArg /* Number of entries in azArg[] */
5000){
5001 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
5002 FILE *out = pState->out; /* Stream to write non-error output to */
5003 int bVerbose = 0; /* If -verbose is present */
5004 int bGroupByParent = 0; /* If -groupbyparent is present */
5005 int i; /* To iterate through azArg[] */
5006 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
5007 int rc; /* Return code */
5008 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
5009
5010 /*
5011 ** This SELECT statement returns one row for each foreign key constraint
5012 ** in the schema of the main database. The column values are:
5013 **
5014 ** 0. The text of an SQL statement similar to:
5015 **
danf9679312017-12-01 18:40:18 +00005016 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00005017 **
danf9679312017-12-01 18:40:18 +00005018 ** This SELECT is similar to the one that the foreign keys implementation
5019 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00005020 ** be used to optimize this query, then it can also be used by the FK
5021 ** implementation to optimize DELETE or UPDATE statements on the parent
5022 ** table.
5023 **
5024 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5025 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5026 ** contains an index that can be used to optimize the query.
5027 **
5028 ** 2. Human readable text that describes the child table and columns. e.g.
5029 **
5030 ** "child_table(child_key1, child_key2)"
5031 **
5032 ** 3. Human readable text that describes the parent table and columns. e.g.
5033 **
5034 ** "parent_table(parent_key1, parent_key2)"
5035 **
5036 ** 4. A full CREATE INDEX statement for an index that could be used to
5037 ** optimize DELETE or UPDATE statements on the parent table. e.g.
5038 **
5039 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
5040 **
5041 ** 5. The name of the parent table.
5042 **
5043 ** These six values are used by the C logic below to generate the report.
5044 */
5045 const char *zSql =
5046 "SELECT "
danf9679312017-12-01 18:40:18 +00005047 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00005048 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5049 " || fkey_collate_clause("
5050 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5051 ", "
5052 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
5053 " || group_concat('*=?', ' AND ') || ')'"
5054 ", "
5055 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
5056 ", "
5057 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5058 ", "
5059 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5060 " || ' ON ' || quote(s.name) || '('"
5061 " || group_concat(quote(f.[from]) ||"
5062 " fkey_collate_clause("
5063 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5064 " || ');'"
5065 ", "
5066 " f.[table] "
5067 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
5068 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5069 "GROUP BY s.name, f.id "
5070 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5071 ;
5072 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
5073
5074 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00005075 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00005076 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5077 bVerbose = 1;
5078 }
5079 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5080 bGroupByParent = 1;
5081 zIndent = " ";
5082 }
5083 else{
5084 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5085 azArg[0], azArg[1]
5086 );
5087 return SQLITE_ERROR;
5088 }
5089 }
5090
5091 /* Register the fkey_collate_clause() SQL function */
5092 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5093 0, shellFkeyCollateClause, 0, 0
5094 );
5095
5096
5097 if( rc==SQLITE_OK ){
5098 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5099 }
5100 if( rc==SQLITE_OK ){
5101 sqlite3_bind_int(pSql, 1, bGroupByParent);
5102 }
5103
5104 if( rc==SQLITE_OK ){
5105 int rc2;
5106 char *zPrev = 0;
5107 while( SQLITE_ROW==sqlite3_step(pSql) ){
5108 int res = -1;
5109 sqlite3_stmt *pExplain = 0;
5110 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5111 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5112 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5113 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5114 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5115 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5116
5117 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5118 if( rc!=SQLITE_OK ) break;
5119 if( SQLITE_ROW==sqlite3_step(pExplain) ){
5120 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5121 res = (
5122 0==sqlite3_strglob(zGlob, zPlan)
5123 || 0==sqlite3_strglob(zGlobIPK, zPlan)
5124 );
5125 }
5126 rc = sqlite3_finalize(pExplain);
5127 if( rc!=SQLITE_OK ) break;
5128
5129 if( res<0 ){
5130 raw_printf(stderr, "Error: internal error");
5131 break;
5132 }else{
5133 if( bGroupByParent
5134 && (bVerbose || res==0)
5135 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5136 ){
5137 raw_printf(out, "-- Parent table %s\n", zParent);
5138 sqlite3_free(zPrev);
5139 zPrev = sqlite3_mprintf("%s", zParent);
5140 }
5141
5142 if( res==0 ){
5143 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5144 }else if( bVerbose ){
5145 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5146 zIndent, zFrom, zTarget
5147 );
5148 }
5149 }
5150 }
5151 sqlite3_free(zPrev);
5152
5153 if( rc!=SQLITE_OK ){
5154 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5155 }
5156
5157 rc2 = sqlite3_finalize(pSql);
5158 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5159 rc = rc2;
5160 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5161 }
5162 }else{
5163 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5164 }
5165
5166 return rc;
5167}
5168
5169/*
5170** Implementation of ".lint" dot command.
5171*/
5172static int lintDotCommand(
5173 ShellState *pState, /* Current shell tool state */
5174 char **azArg, /* Array of arguments passed to dot command */
5175 int nArg /* Number of entries in azArg[] */
5176){
5177 int n;
drhaf2770f2018-01-05 14:55:43 +00005178 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00005179 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5180 return lintFkeyIndexes(pState, azArg, nArg);
5181
5182 usage:
5183 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5184 raw_printf(stderr, "Where sub-commands are:\n");
5185 raw_printf(stderr, " fkey-indexes\n");
5186 return SQLITE_ERROR;
5187}
5188
drhe37c0e12018-01-06 19:19:50 +00005189#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5190/*********************************************************************************
5191** The ".archive" or ".ar" command.
5192*/
danfd0245d2017-12-07 15:44:29 +00005193static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00005194 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00005195 int *pRc,
5196 const char *zSql,
5197 sqlite3_stmt **ppStmt
5198){
5199 *ppStmt = 0;
5200 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00005201 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00005202 if( rc!=SQLITE_OK ){
5203 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00005204 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00005205 );
5206 *pRc = rc;
5207 }
5208 }
5209}
5210
danac15e2d2017-12-14 19:15:07 +00005211static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00005212 sqlite3 *db,
5213 int *pRc,
danac15e2d2017-12-14 19:15:07 +00005214 sqlite3_stmt **ppStmt,
5215 const char *zFmt,
5216 ...
dan3f67ddf2017-12-13 20:04:53 +00005217){
danac15e2d2017-12-14 19:15:07 +00005218 *ppStmt = 0;
5219 if( *pRc==SQLITE_OK ){
5220 va_list ap;
5221 char *z;
5222 va_start(ap, zFmt);
5223 z = sqlite3_vmprintf(zFmt, ap);
drh1dbb1472018-10-11 10:37:24 +00005224 va_end(ap);
dan3f67ddf2017-12-13 20:04:53 +00005225 if( z==0 ){
5226 *pRc = SQLITE_NOMEM;
5227 }else{
5228 shellPrepare(db, pRc, z, ppStmt);
5229 sqlite3_free(z);
5230 }
dan3f67ddf2017-12-13 20:04:53 +00005231 }
5232}
5233
danfd0245d2017-12-07 15:44:29 +00005234static void shellFinalize(
5235 int *pRc,
5236 sqlite3_stmt *pStmt
5237){
dan25c12182017-12-07 21:03:33 +00005238 if( pStmt ){
5239 sqlite3 *db = sqlite3_db_handle(pStmt);
5240 int rc = sqlite3_finalize(pStmt);
5241 if( *pRc==SQLITE_OK ){
5242 if( rc!=SQLITE_OK ){
5243 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5244 }
5245 *pRc = rc;
5246 }
5247 }
danfd0245d2017-12-07 15:44:29 +00005248}
5249
5250static void shellReset(
5251 int *pRc,
5252 sqlite3_stmt *pStmt
5253){
5254 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00005255 if( *pRc==SQLITE_OK ){
5256 if( rc!=SQLITE_OK ){
5257 sqlite3 *db = sqlite3_db_handle(pStmt);
5258 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5259 }
5260 *pRc = rc;
5261 }
danfd0245d2017-12-07 15:44:29 +00005262}
drhe37c0e12018-01-06 19:19:50 +00005263/*
dan88be0202017-12-09 17:58:02 +00005264** Structure representing a single ".ar" command.
5265*/
5266typedef struct ArCommand ArCommand;
5267struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00005268 u8 eCmd; /* An AR_CMD_* value */
5269 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00005270 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00005271 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00005272 u8 bAppend; /* True if --append */
drhd0f9cdc2018-05-17 14:09:06 +00005273 u8 fromCmdLine; /* Run from -A instead of .archive */
drhb376b3d2018-01-10 13:11:51 +00005274 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00005275 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00005276 const char *zFile; /* --file argument, or NULL */
5277 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00005278 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00005279 ShellState *p; /* Shell state */
5280 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00005281};
5282
5283/*
5284** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5285*/
dan0d0547f2017-12-14 15:40:42 +00005286static int arUsage(FILE *f){
drh98aa2ab2018-09-26 16:53:51 +00005287 showHelp(f,"archive");
dan0d0547f2017-12-14 15:40:42 +00005288 return SQLITE_ERROR;
5289}
5290
5291/*
5292** Print an error message for the .ar command to stderr and return
5293** SQLITE_ERROR.
5294*/
drhd0f9cdc2018-05-17 14:09:06 +00005295static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
dan0d0547f2017-12-14 15:40:42 +00005296 va_list ap;
5297 char *z;
5298 va_start(ap, zFmt);
5299 z = sqlite3_vmprintf(zFmt, ap);
5300 va_end(ap);
drhd0f9cdc2018-05-17 14:09:06 +00005301 utf8_printf(stderr, "Error: %s\n", z);
5302 if( pAr->fromCmdLine ){
5303 utf8_printf(stderr, "Use \"-A\" for more help\n");
5304 }else{
5305 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5306 }
dan0d0547f2017-12-14 15:40:42 +00005307 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00005308 return SQLITE_ERROR;
5309}
5310
5311/*
5312** Values for ArCommand.eCmd.
5313*/
dand4b56e52017-12-12 20:04:59 +00005314#define AR_CMD_CREATE 1
5315#define AR_CMD_EXTRACT 2
5316#define AR_CMD_LIST 3
5317#define AR_CMD_UPDATE 4
dan0d0547f2017-12-14 15:40:42 +00005318#define AR_CMD_HELP 5
dand4b56e52017-12-12 20:04:59 +00005319
5320/*
5321** Other (non-command) switches.
5322*/
drhb376b3d2018-01-10 13:11:51 +00005323#define AR_SWITCH_VERBOSE 6
5324#define AR_SWITCH_FILE 7
5325#define AR_SWITCH_DIRECTORY 8
drha5676c42018-01-10 15:17:34 +00005326#define AR_SWITCH_APPEND 9
drhb376b3d2018-01-10 13:11:51 +00005327#define AR_SWITCH_DRYRUN 10
dand4b56e52017-12-12 20:04:59 +00005328
5329static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5330 switch( eSwitch ){
5331 case AR_CMD_CREATE:
5332 case AR_CMD_EXTRACT:
5333 case AR_CMD_LIST:
5334 case AR_CMD_UPDATE:
dan0d0547f2017-12-14 15:40:42 +00005335 case AR_CMD_HELP:
5336 if( pAr->eCmd ){
drhd0f9cdc2018-05-17 14:09:06 +00005337 return arErrorMsg(pAr, "multiple command options");
dan0d0547f2017-12-14 15:40:42 +00005338 }
dand4b56e52017-12-12 20:04:59 +00005339 pAr->eCmd = eSwitch;
5340 break;
5341
drhb376b3d2018-01-10 13:11:51 +00005342 case AR_SWITCH_DRYRUN:
5343 pAr->bDryRun = 1;
5344 break;
dand4b56e52017-12-12 20:04:59 +00005345 case AR_SWITCH_VERBOSE:
5346 pAr->bVerbose = 1;
5347 break;
drha5676c42018-01-10 15:17:34 +00005348 case AR_SWITCH_APPEND:
5349 pAr->bAppend = 1;
drhca7733b2018-01-10 18:09:20 +00005350 /* Fall thru into --file */
dand4b56e52017-12-12 20:04:59 +00005351 case AR_SWITCH_FILE:
5352 pAr->zFile = zArg;
5353 break;
5354 case AR_SWITCH_DIRECTORY:
5355 pAr->zDir = zArg;
5356 break;
5357 }
5358
5359 return SQLITE_OK;
5360}
dan88be0202017-12-09 17:58:02 +00005361
5362/*
5363** Parse the command line for an ".ar" command. The results are written into
5364** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5365** successfully, otherwise an error message is written to stderr and
5366** SQLITE_ERROR returned.
5367*/
5368static int arParseCommand(
5369 char **azArg, /* Array of arguments passed to dot command */
5370 int nArg, /* Number of entries in azArg[] */
5371 ArCommand *pAr /* Populate this object */
5372){
dand4b56e52017-12-12 20:04:59 +00005373 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00005374 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00005375 char cShort;
5376 u8 eSwitch;
5377 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00005378 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00005379 { "create", 'c', AR_CMD_CREATE, 0 },
5380 { "extract", 'x', AR_CMD_EXTRACT, 0 },
5381 { "list", 't', AR_CMD_LIST, 0 },
5382 { "update", 'u', AR_CMD_UPDATE, 0 },
5383 { "help", 'h', AR_CMD_HELP, 0 },
5384 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
5385 { "file", 'f', AR_SWITCH_FILE, 1 },
drhca7733b2018-01-10 18:09:20 +00005386 { "append", 'a', AR_SWITCH_APPEND, 1 },
drhb376b3d2018-01-10 13:11:51 +00005387 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drhb376b3d2018-01-10 13:11:51 +00005388 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00005389 };
5390 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5391 struct ArSwitch *pEnd = &aSwitch[nSwitch];
5392
dan88be0202017-12-09 17:58:02 +00005393 if( nArg<=1 ){
drh98aa2ab2018-09-26 16:53:51 +00005394 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
dan0d0547f2017-12-14 15:40:42 +00005395 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00005396 }else{
5397 char *z = azArg[1];
dan88be0202017-12-09 17:58:02 +00005398 if( z[0]!='-' ){
5399 /* Traditional style [tar] invocation */
5400 int i;
5401 int iArg = 2;
5402 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00005403 const char *zArg = 0;
5404 struct ArSwitch *pOpt;
5405 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5406 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00005407 }
dan0d0547f2017-12-14 15:40:42 +00005408 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005409 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005410 }
dand4b56e52017-12-12 20:04:59 +00005411 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005412 if( iArg>=nArg ){
drhd0f9cdc2018-05-17 14:09:06 +00005413 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005414 }
dand4b56e52017-12-12 20:04:59 +00005415 zArg = azArg[iArg++];
5416 }
5417 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00005418 }
dan88be0202017-12-09 17:58:02 +00005419 pAr->nArg = nArg-iArg;
5420 if( pAr->nArg>0 ){
5421 pAr->azArg = &azArg[iArg];
5422 }
dand4b56e52017-12-12 20:04:59 +00005423 }else{
5424 /* Non-traditional invocation */
5425 int iArg;
5426 for(iArg=1; iArg<nArg; iArg++){
5427 int n;
5428 z = azArg[iArg];
5429 if( z[0]!='-' ){
5430 /* All remaining command line words are command arguments. */
5431 pAr->azArg = &azArg[iArg];
5432 pAr->nArg = nArg-iArg;
5433 break;
5434 }
drhaf2770f2018-01-05 14:55:43 +00005435 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00005436
5437 if( z[1]!='-' ){
5438 int i;
5439 /* One or more short options */
5440 for(i=1; i<n; i++){
5441 const char *zArg = 0;
5442 struct ArSwitch *pOpt;
5443 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5444 if( z[i]==pOpt->cShort ) break;
5445 }
dan0d0547f2017-12-14 15:40:42 +00005446 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005447 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005448 }
dand4b56e52017-12-12 20:04:59 +00005449 if( pOpt->bArg ){
5450 if( i<(n-1) ){
5451 zArg = &z[i+1];
5452 i = n;
5453 }else{
dan0d0547f2017-12-14 15:40:42 +00005454 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005455 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005456 }
dand4b56e52017-12-12 20:04:59 +00005457 zArg = azArg[++iArg];
5458 }
5459 }
5460 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5461 }
5462 }else if( z[2]=='\0' ){
5463 /* A -- option, indicating that all remaining command line words
5464 ** are command arguments. */
5465 pAr->azArg = &azArg[iArg+1];
5466 pAr->nArg = nArg-iArg-1;
5467 break;
5468 }else{
5469 /* A long option */
5470 const char *zArg = 0; /* Argument for option, if any */
5471 struct ArSwitch *pMatch = 0; /* Matching option */
5472 struct ArSwitch *pOpt; /* Iterator */
5473 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5474 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00005475 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00005476 if( pMatch ){
drhd0f9cdc2018-05-17 14:09:06 +00005477 return arErrorMsg(pAr, "ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00005478 }else{
5479 pMatch = pOpt;
5480 }
5481 }
5482 }
5483
5484 if( pMatch==0 ){
drhd0f9cdc2018-05-17 14:09:06 +00005485 return arErrorMsg(pAr, "unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00005486 }
5487 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005488 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005489 return arErrorMsg(pAr, "option requires an argument: %s", z);
dan0d0547f2017-12-14 15:40:42 +00005490 }
dand4b56e52017-12-12 20:04:59 +00005491 zArg = azArg[++iArg];
5492 }
5493 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5494 }
5495 }
dan88be0202017-12-09 17:58:02 +00005496 }
5497 }
5498
5499 return SQLITE_OK;
5500}
5501
5502/*
dan3f67ddf2017-12-13 20:04:53 +00005503** This function assumes that all arguments within the ArCommand.azArg[]
5504** array refer to archive members, as for the --extract or --list commands.
5505** It checks that each of them are present. If any specified file is not
5506** present in the archive, an error is printed to stderr and an error
5507** code returned. Otherwise, if all specified arguments are present in
5508** the archive, SQLITE_OK is returned.
5509**
5510** This function strips any trailing '/' characters from each argument.
5511** This is consistent with the way the [tar] command seems to work on
5512** Linux.
5513*/
drhb376b3d2018-01-10 13:11:51 +00005514static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00005515 int rc = SQLITE_OK;
5516 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00005517 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00005518 sqlite3_stmt *pTest = 0;
5519
drhb376b3d2018-01-10 13:11:51 +00005520 shellPreparePrintf(pAr->db, &rc, &pTest,
5521 "SELECT name FROM %s WHERE name=$name",
5522 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00005523 );
drhb376b3d2018-01-10 13:11:51 +00005524 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00005525 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5526 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00005527 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00005528 int bOk = 0;
5529 while( n>0 && z[n-1]=='/' ) n--;
5530 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00005531 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00005532 if( SQLITE_ROW==sqlite3_step(pTest) ){
5533 bOk = 1;
5534 }
5535 shellReset(&rc, pTest);
5536 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00005537 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00005538 rc = SQLITE_ERROR;
5539 }
5540 }
5541 shellFinalize(&rc, pTest);
5542 }
dan3f67ddf2017-12-13 20:04:53 +00005543 return rc;
5544}
5545
5546/*
5547** Format a WHERE clause that can be used against the "sqlar" table to
5548** identify all archive members that match the command arguments held
5549** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5550** The caller is responsible for eventually calling sqlite3_free() on
5551** any non-NULL (*pzWhere) value.
5552*/
5553static void arWhereClause(
5554 int *pRc,
5555 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00005556 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00005557){
5558 char *zWhere = 0;
5559 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00005560 if( pAr->nArg==0 ){
5561 zWhere = sqlite3_mprintf("1");
5562 }else{
5563 int i;
5564 const char *zSep = "";
5565 for(i=0; i<pAr->nArg; i++){
5566 const char *z = pAr->azArg[i];
5567 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00005568 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5569 zWhere, zSep, z, strlen30(z)+1, z
5570 );
danac15e2d2017-12-14 19:15:07 +00005571 if( zWhere==0 ){
5572 *pRc = SQLITE_NOMEM;
5573 break;
5574 }
5575 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00005576 }
dan3f67ddf2017-12-13 20:04:53 +00005577 }
5578 }
5579 *pzWhere = zWhere;
5580}
5581
5582/*
dan88be0202017-12-09 17:58:02 +00005583** Implementation of .ar "lisT" command.
5584*/
drhb376b3d2018-01-10 13:11:51 +00005585static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00005586 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00005587 const char *azCols[] = {
5588 "name",
drh410cad92018-01-10 17:19:16 +00005589 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00005590 };
dan5a78b812017-12-27 18:54:11 +00005591
dan3f67ddf2017-12-13 20:04:53 +00005592 char *zWhere = 0;
5593 sqlite3_stmt *pSql = 0;
5594 int rc;
5595
drhb376b3d2018-01-10 13:11:51 +00005596 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005597 arWhereClause(&rc, pAr, &zWhere);
5598
drhb376b3d2018-01-10 13:11:51 +00005599 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5600 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00005601 if( pAr->bDryRun ){
5602 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5603 }else{
5604 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5605 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00005606 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5607 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00005608 sqlite3_column_int(pSql, 1),
5609 sqlite3_column_text(pSql, 2),
5610 sqlite3_column_text(pSql, 3)
5611 );
5612 }else{
5613 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5614 }
danb5090e42017-12-27 21:13:21 +00005615 }
dan3f67ddf2017-12-13 20:04:53 +00005616 }
dan5a78b812017-12-27 18:54:11 +00005617 shellFinalize(&rc, pSql);
drhd0f9cdc2018-05-17 14:09:06 +00005618 sqlite3_free(zWhere);
dan3f67ddf2017-12-13 20:04:53 +00005619 return rc;
dan88be0202017-12-09 17:58:02 +00005620}
5621
5622
danfd0245d2017-12-07 15:44:29 +00005623/*
5624** Implementation of .ar "eXtract" command.
5625*/
drhb376b3d2018-01-10 13:11:51 +00005626static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00005627 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00005628 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00005629 " ($dir || name),"
5630 " writefile(($dir || name), %s, mode, mtime) "
drh0cfd46a2018-06-06 01:18:01 +00005631 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5632 " AND name NOT GLOB '*..[/\\]*'";
dan5a78b812017-12-27 18:54:11 +00005633
5634 const char *azExtraArg[] = {
5635 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00005636 "data"
dan5a78b812017-12-27 18:54:11 +00005637 };
dan5a78b812017-12-27 18:54:11 +00005638
danfd0245d2017-12-07 15:44:29 +00005639 sqlite3_stmt *pSql = 0;
5640 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00005641 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00005642 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00005643 int i, j;
dan2ad09492017-12-09 18:28:22 +00005644
dan3f67ddf2017-12-13 20:04:53 +00005645 /* If arguments are specified, check that they actually exist within
5646 ** the archive before proceeding. And formulate a WHERE clause to
5647 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00005648 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005649 arWhereClause(&rc, pAr, &zWhere);
5650
5651 if( rc==SQLITE_OK ){
5652 if( pAr->zDir ){
5653 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5654 }else{
5655 zDir = sqlite3_mprintf("");
5656 }
5657 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00005658 }
danfd0245d2017-12-07 15:44:29 +00005659
drhb376b3d2018-01-10 13:11:51 +00005660 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5661 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00005662 );
5663
dan2ad09492017-12-09 18:28:22 +00005664 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005665 j = sqlite3_bind_parameter_index(pSql, "$dir");
5666 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00005667
danac15e2d2017-12-14 19:15:07 +00005668 /* Run the SELECT statement twice. The first time, writefile() is called
5669 ** for all archive members that should be extracted. The second time,
5670 ** only for the directories. This is because the timestamps for
5671 ** extracted directories must be reset after they are populated (as
5672 ** populating them changes the timestamp). */
5673 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00005674 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5675 sqlite3_bind_int(pSql, j, i);
5676 if( pAr->bDryRun ){
5677 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5678 }else{
5679 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5680 if( i==0 && pAr->bVerbose ){
5681 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5682 }
danac15e2d2017-12-14 19:15:07 +00005683 }
5684 }
5685 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005686 }
danac15e2d2017-12-14 19:15:07 +00005687 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005688 }
dan25c12182017-12-07 21:03:33 +00005689
dan2ad09492017-12-09 18:28:22 +00005690 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00005691 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00005692 return rc;
5693}
5694
drhb376b3d2018-01-10 13:11:51 +00005695/*
5696** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5697*/
5698static int arExecSql(ArCommand *pAr, const char *zSql){
5699 int rc;
5700 if( pAr->bDryRun ){
5701 utf8_printf(pAr->p->out, "%s\n", zSql);
5702 rc = SQLITE_OK;
5703 }else{
drh410cad92018-01-10 17:19:16 +00005704 char *zErr = 0;
5705 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5706 if( zErr ){
5707 utf8_printf(stdout, "ERROR: %s\n", zErr);
5708 sqlite3_free(zErr);
5709 }
drhb376b3d2018-01-10 13:11:51 +00005710 }
5711 return rc;
5712}
5713
dan1ad3f612017-12-11 20:22:02 +00005714
danfd0245d2017-12-07 15:44:29 +00005715/*
dan06741a32017-12-13 20:17:18 +00005716** Implementation of .ar "create" and "update" commands.
danfd0245d2017-12-07 15:44:29 +00005717**
5718** Create the "sqlar" table in the database if it does not already exist.
5719** Then add each file in the azFile[] array to the archive. Directories
5720** are added recursively. If argument bVerbose is non-zero, a message is
5721** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00005722**
5723** The create command is the same as update, except that it drops
5724** any existing "sqlar" table before beginning.
danfd0245d2017-12-07 15:44:29 +00005725*/
drhb376b3d2018-01-10 13:11:51 +00005726static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00005727 ArCommand *pAr, /* Command arguments and options */
drhb376b3d2018-01-10 13:11:51 +00005728 int bUpdate /* true for a --create. false for --update */
danfd0245d2017-12-07 15:44:29 +00005729){
dand4b56e52017-12-12 20:04:59 +00005730 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00005731 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5732 " name TEXT PRIMARY KEY, -- name of the file\n"
5733 " mode INT, -- access permissions\n"
5734 " mtime INT, -- last modification time\n"
5735 " sz INT, -- original file size\n"
5736 " data BLOB -- compressed content\n"
5737 ")";
dand4b56e52017-12-12 20:04:59 +00005738 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh1bf208c2018-03-09 21:54:01 +00005739 const char *zInsertFmt[2] = {
5740 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
drh634c70f2018-01-10 16:50:18 +00005741 " SELECT\n"
5742 " %s,\n"
5743 " mode,\n"
5744 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00005745 " CASE substr(lsmode(mode),1,1)\n"
5746 " WHEN '-' THEN length(data)\n"
5747 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00005748 " ELSE -1 END,\n"
drh69d2d352018-03-09 22:18:53 +00005749 " sqlar_compress(data)\n"
drh634c70f2018-01-10 16:50:18 +00005750 " FROM fsdir(%Q,%Q)\n"
drh1bf208c2018-03-09 21:54:01 +00005751 " WHERE lsmode(mode) NOT LIKE '?%%';",
5752 "REPLACE INTO %s(name,mode,mtime,data)\n"
5753 " SELECT\n"
5754 " %s,\n"
5755 " mode,\n"
5756 " mtime,\n"
5757 " data\n"
5758 " FROM fsdir(%Q,%Q)\n"
5759 " WHERE lsmode(mode) NOT LIKE '?%%';"
5760 };
danfd0245d2017-12-07 15:44:29 +00005761 int i; /* For iterating through azFile[] */
5762 int rc; /* Return code */
drh1bf208c2018-03-09 21:54:01 +00005763 const char *zTab = 0; /* SQL table into which to insert */
5764 char *zSql;
5765 char zTemp[50];
danfd0245d2017-12-07 15:44:29 +00005766
drh1bf208c2018-03-09 21:54:01 +00005767 arExecSql(pAr, "PRAGMA page_size=512");
drhb376b3d2018-01-10 13:11:51 +00005768 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00005769 if( rc!=SQLITE_OK ) return rc;
drh1bf208c2018-03-09 21:54:01 +00005770 zTemp[0] = 0;
5771 if( pAr->bZip ){
5772 /* Initialize the zipfile virtual table, if necessary */
5773 if( pAr->zFile ){
5774 sqlite3_uint64 r;
5775 sqlite3_randomness(sizeof(r),&r);
5776 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5777 zTab = zTemp;
5778 zSql = sqlite3_mprintf(
5779 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5780 zTab, pAr->zFile
5781 );
5782 rc = arExecSql(pAr, zSql);
5783 sqlite3_free(zSql);
5784 }else{
5785 zTab = "zip";
5786 }
5787 }else{
5788 /* Initialize the table for an SQLAR */
5789 zTab = "sqlar";
5790 if( bUpdate==0 ){
5791 rc = arExecSql(pAr, zDrop);
5792 if( rc!=SQLITE_OK ) goto end_ar_transaction;
5793 }
5794 rc = arExecSql(pAr, zCreate);
dan06741a32017-12-13 20:17:18 +00005795 }
dan88be0202017-12-09 17:58:02 +00005796 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
mistachkince2052b2018-03-23 00:31:53 +00005797 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
drh634c70f2018-01-10 16:50:18 +00005798 pAr->bVerbose ? "shell_putsnl(name)" : "name",
5799 pAr->azArg[i], pAr->zDir);
mistachkince2052b2018-03-23 00:31:53 +00005800 rc = arExecSql(pAr, zSql2);
5801 sqlite3_free(zSql2);
danfd0245d2017-12-07 15:44:29 +00005802 }
drh1bf208c2018-03-09 21:54:01 +00005803end_ar_transaction:
danfd0245d2017-12-07 15:44:29 +00005804 if( rc!=SQLITE_OK ){
drh2bd207f2019-01-11 17:19:59 +00005805 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00005806 }else{
drhb376b3d2018-01-10 13:11:51 +00005807 rc = arExecSql(pAr, "RELEASE ar;");
drh1bf208c2018-03-09 21:54:01 +00005808 if( pAr->bZip && pAr->zFile ){
5809 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
5810 arExecSql(pAr, zSql);
5811 sqlite3_free(zSql);
5812 }
danfd0245d2017-12-07 15:44:29 +00005813 }
danfd0245d2017-12-07 15:44:29 +00005814 return rc;
5815}
5816
5817/*
5818** Implementation of ".ar" dot command.
5819*/
5820static int arDotCommand(
5821 ShellState *pState, /* Current shell tool state */
drhd0f9cdc2018-05-17 14:09:06 +00005822 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
danfd0245d2017-12-07 15:44:29 +00005823 char **azArg, /* Array of arguments passed to dot command */
5824 int nArg /* Number of entries in azArg[] */
5825){
dan88be0202017-12-09 17:58:02 +00005826 ArCommand cmd;
5827 int rc;
drh34660642018-01-10 17:39:54 +00005828 memset(&cmd, 0, sizeof(cmd));
drhd0f9cdc2018-05-17 14:09:06 +00005829 cmd.fromCmdLine = fromCmdLine;
dan88be0202017-12-09 17:58:02 +00005830 rc = arParseCommand(azArg, nArg, &cmd);
5831 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00005832 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00005833 cmd.p = pState;
5834 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00005835 if( cmd.zFile ){
drh1bf208c2018-03-09 21:54:01 +00005836 eDbType = deduceDatabaseType(cmd.zFile, 1);
drha5676c42018-01-10 15:17:34 +00005837 }else{
5838 eDbType = pState->openMode;
5839 }
5840 if( eDbType==SHELL_OPEN_ZIPFILE ){
drh1bf208c2018-03-09 21:54:01 +00005841 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
5842 if( cmd.zFile==0 ){
5843 cmd.zSrcTable = sqlite3_mprintf("zip");
5844 }else{
5845 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
5846 }
dan5a78b812017-12-27 18:54:11 +00005847 }
drha5676c42018-01-10 15:17:34 +00005848 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00005849 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00005850 int flags;
drha5676c42018-01-10 15:17:34 +00005851 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
dand4b56e52017-12-12 20:04:59 +00005852 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
5853 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
5854 }else{
5855 flags = SQLITE_OPEN_READONLY;
5856 }
drha82c95b2018-01-10 14:00:00 +00005857 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00005858 if( cmd.bDryRun ){
5859 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
5860 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
5861 }
5862 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
5863 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00005864 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005865 utf8_printf(stderr, "cannot open file: %s (%s)\n",
5866 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00005867 );
drha5676c42018-01-10 15:17:34 +00005868 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00005869 }
drhb376b3d2018-01-10 13:11:51 +00005870 sqlite3_fileio_init(cmd.db, 0, 0);
drhb376b3d2018-01-10 13:11:51 +00005871 sqlite3_sqlar_init(cmd.db, 0, 0);
drh34660642018-01-10 17:39:54 +00005872 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
5873 shellPutsFunc, 0, 0);
5874
dand4b56e52017-12-12 20:04:59 +00005875 }
drhd0f9cdc2018-05-17 14:09:06 +00005876 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
drh634c70f2018-01-10 16:50:18 +00005877 if( cmd.eCmd!=AR_CMD_CREATE
5878 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
5879 ){
drha5676c42018-01-10 15:17:34 +00005880 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
5881 rc = SQLITE_ERROR;
5882 goto end_ar_command;
5883 }
5884 cmd.zSrcTable = sqlite3_mprintf("sqlar");
5885 }
dand4b56e52017-12-12 20:04:59 +00005886
dan88be0202017-12-09 17:58:02 +00005887 switch( cmd.eCmd ){
5888 case AR_CMD_CREATE:
drhb376b3d2018-01-10 13:11:51 +00005889 rc = arCreateOrUpdateCommand(&cmd, 0);
dan88be0202017-12-09 17:58:02 +00005890 break;
danfd0245d2017-12-07 15:44:29 +00005891
dan88be0202017-12-09 17:58:02 +00005892 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00005893 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005894 break;
5895
5896 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00005897 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005898 break;
5899
dan0d0547f2017-12-14 15:40:42 +00005900 case AR_CMD_HELP:
5901 arUsage(pState->out);
5902 break;
5903
dan88be0202017-12-09 17:58:02 +00005904 default:
5905 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb376b3d2018-01-10 13:11:51 +00005906 rc = arCreateOrUpdateCommand(&cmd, 1);
dan88be0202017-12-09 17:58:02 +00005907 break;
danfd0245d2017-12-07 15:44:29 +00005908 }
5909 }
drha5676c42018-01-10 15:17:34 +00005910end_ar_command:
5911 if( cmd.db!=pState->db ){
drh9e804032018-05-18 17:11:50 +00005912 close_db(cmd.db);
drha5676c42018-01-10 15:17:34 +00005913 }
5914 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00005915
dan88be0202017-12-09 17:58:02 +00005916 return rc;
danfd0245d2017-12-07 15:44:29 +00005917}
drhe37c0e12018-01-06 19:19:50 +00005918/* End of the ".archive" or ".ar" command logic
5919**********************************************************************************/
5920#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00005921
drh2ce15c32017-07-11 13:34:40 +00005922
5923/*
5924** If an input line begins with "." then invoke this routine to
5925** process that line.
5926**
5927** Return 1 on error, 2 to exit, and 0 otherwise.
5928*/
5929static int do_meta_command(char *zLine, ShellState *p){
5930 int h = 1;
5931 int nArg = 0;
5932 int n, c;
5933 int rc = 0;
5934 char *azArg[50];
5935
dan6b046be2018-01-09 15:25:55 +00005936#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00005937 if( p->expert.pExpert ){
5938 expertFinish(p, 1, 0);
5939 }
dan6b046be2018-01-09 15:25:55 +00005940#endif
dan43efc182017-12-19 17:42:13 +00005941
drh2ce15c32017-07-11 13:34:40 +00005942 /* Parse the input line into tokens.
5943 */
5944 while( zLine[h] && nArg<ArraySize(azArg) ){
5945 while( IsSpace(zLine[h]) ){ h++; }
5946 if( zLine[h]==0 ) break;
5947 if( zLine[h]=='\'' || zLine[h]=='"' ){
5948 int delim = zLine[h++];
5949 azArg[nArg++] = &zLine[h];
5950 while( zLine[h] && zLine[h]!=delim ){
5951 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5952 h++;
5953 }
5954 if( zLine[h]==delim ){
5955 zLine[h++] = 0;
5956 }
5957 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5958 }else{
5959 azArg[nArg++] = &zLine[h];
5960 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5961 if( zLine[h] ) zLine[h++] = 0;
5962 resolve_backslashes(azArg[nArg-1]);
5963 }
5964 }
5965
5966 /* Process the input line.
5967 */
5968 if( nArg==0 ) return 0; /* no tokens, no error */
5969 n = strlen30(azArg[0]);
5970 c = azArg[0][0];
drh13c20932018-01-10 21:41:55 +00005971 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00005972
5973#ifndef SQLITE_OMIT_AUTHORIZATION
5974 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5975 if( nArg!=2 ){
5976 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5977 rc = 1;
5978 goto meta_command_exit;
5979 }
5980 open_db(p, 0);
5981 if( booleanValue(azArg[1]) ){
5982 sqlite3_set_authorizer(p->db, shellAuth, p);
5983 }else{
5984 sqlite3_set_authorizer(p->db, 0, 0);
5985 }
5986 }else
5987#endif
5988
drhe37c0e12018-01-06 19:19:50 +00005989#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5990 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00005991 open_db(p, 0);
drhd0f9cdc2018-05-17 14:09:06 +00005992 rc = arDotCommand(p, 0, azArg, nArg);
danfd0245d2017-12-07 15:44:29 +00005993 }else
5994#endif
5995
drh2ce15c32017-07-11 13:34:40 +00005996 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5997 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5998 ){
5999 const char *zDestFile = 0;
6000 const char *zDb = 0;
6001 sqlite3 *pDest;
6002 sqlite3_backup *pBackup;
6003 int j;
drha50bffb2018-12-08 01:09:14 +00006004 int bAsync = 0;
drh69ed38a2018-05-14 00:23:08 +00006005 const char *zVfs = 0;
drh2ce15c32017-07-11 13:34:40 +00006006 for(j=1; j<nArg; j++){
6007 const char *z = azArg[j];
6008 if( z[0]=='-' ){
drh69ed38a2018-05-14 00:23:08 +00006009 if( z[1]=='-' ) z++;
6010 if( strcmp(z, "-append")==0 ){
6011 zVfs = "apndvfs";
6012 }else
drha50bffb2018-12-08 01:09:14 +00006013 if( strcmp(z, "-async")==0 ){
6014 bAsync = 1;
6015 }else
drh2ce15c32017-07-11 13:34:40 +00006016 {
6017 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
6018 return 1;
6019 }
6020 }else if( zDestFile==0 ){
6021 zDestFile = azArg[j];
6022 }else if( zDb==0 ){
6023 zDb = zDestFile;
6024 zDestFile = azArg[j];
6025 }else{
drha50bffb2018-12-08 01:09:14 +00006026 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
drh2ce15c32017-07-11 13:34:40 +00006027 return 1;
6028 }
6029 }
6030 if( zDestFile==0 ){
6031 raw_printf(stderr, "missing FILENAME argument on .backup\n");
6032 return 1;
6033 }
6034 if( zDb==0 ) zDb = "main";
drh69ed38a2018-05-14 00:23:08 +00006035 rc = sqlite3_open_v2(zDestFile, &pDest,
6036 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
drh2ce15c32017-07-11 13:34:40 +00006037 if( rc!=SQLITE_OK ){
6038 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9e804032018-05-18 17:11:50 +00006039 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006040 return 1;
6041 }
drha50bffb2018-12-08 01:09:14 +00006042 if( bAsync ){
6043 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
6044 0, 0, 0);
6045 }
drh2ce15c32017-07-11 13:34:40 +00006046 open_db(p, 0);
6047 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
6048 if( pBackup==0 ){
6049 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9e804032018-05-18 17:11:50 +00006050 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006051 return 1;
6052 }
6053 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
6054 sqlite3_backup_finish(pBackup);
6055 if( rc==SQLITE_DONE ){
6056 rc = 0;
6057 }else{
6058 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
6059 rc = 1;
6060 }
drh9e804032018-05-18 17:11:50 +00006061 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006062 }else
6063
6064 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
6065 if( nArg==2 ){
6066 bail_on_error = booleanValue(azArg[1]);
6067 }else{
6068 raw_printf(stderr, "Usage: .bail on|off\n");
6069 rc = 1;
6070 }
6071 }else
6072
6073 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
6074 if( nArg==2 ){
6075 if( booleanValue(azArg[1]) ){
6076 setBinaryMode(p->out, 1);
6077 }else{
6078 setTextMode(p->out, 1);
6079 }
6080 }else{
6081 raw_printf(stderr, "Usage: .binary on|off\n");
6082 rc = 1;
6083 }
6084 }else
6085
6086 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
6087 if( nArg==2 ){
6088#if defined(_WIN32) || defined(WIN32)
6089 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
6090 rc = !SetCurrentDirectoryW(z);
6091 sqlite3_free(z);
6092#else
6093 rc = chdir(azArg[1]);
6094#endif
6095 if( rc ){
6096 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
6097 rc = 1;
6098 }
6099 }else{
6100 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
6101 rc = 1;
6102 }
6103 }else
6104
6105 /* The undocumented ".breakpoint" command causes a call to the no-op
6106 ** routine named test_breakpoint().
6107 */
6108 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
6109 test_breakpoint();
6110 }else
6111
6112 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
6113 if( nArg==2 ){
6114 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
6115 }else{
6116 raw_printf(stderr, "Usage: .changes on|off\n");
6117 rc = 1;
6118 }
6119 }else
6120
6121 /* Cancel output redirection, if it is currently set (by .testcase)
6122 ** Then read the content of the testcase-out.txt file and compare against
6123 ** azArg[1]. If there are differences, report an error and exit.
6124 */
6125 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
6126 char *zRes = 0;
6127 output_reset(p);
6128 if( nArg!=2 ){
6129 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
6130 rc = 2;
6131 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
6132 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
6133 rc = 2;
6134 }else if( testcase_glob(azArg[1],zRes)==0 ){
6135 utf8_printf(stderr,
6136 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
6137 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00006138 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00006139 }else{
6140 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
6141 p->nCheck++;
6142 }
6143 sqlite3_free(zRes);
6144 }else
6145
6146 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
6147 if( nArg==2 ){
6148 tryToClone(p, azArg[1]);
6149 }else{
6150 raw_printf(stderr, "Usage: .clone FILENAME\n");
6151 rc = 1;
6152 }
6153 }else
6154
6155 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
6156 ShellState data;
6157 char *zErrMsg = 0;
6158 open_db(p, 0);
6159 memcpy(&data, p, sizeof(data));
6160 data.showHeader = 0;
6161 data.cMode = data.mode = MODE_List;
6162 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
6163 data.cnt = 0;
6164 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
6165 callback, &data, &zErrMsg);
6166 if( zErrMsg ){
6167 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6168 sqlite3_free(zErrMsg);
6169 rc = 1;
6170 }
6171 }else
6172
drh7df01192018-04-28 12:43:16 +00006173 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
drheb7f2a02018-09-26 18:02:32 +00006174 static const struct DbConfigChoices {
6175 const char *zName;
6176 int op;
6177 } aDbConfig[] = {
drh7df01192018-04-28 12:43:16 +00006178 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
6179 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
6180 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
6181 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
6182 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
6183 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
6184 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
6185 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
drha296cda2018-11-03 16:09:59 +00006186 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
drh7df01192018-04-28 12:43:16 +00006187 };
6188 int ii, v;
6189 open_db(p, 0);
6190 for(ii=0; ii<ArraySize(aDbConfig); ii++){
6191 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
6192 if( nArg>=3 ){
6193 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
6194 }
6195 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
6196 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
6197 if( nArg>1 ) break;
6198 }
6199 if( nArg>1 && ii==ArraySize(aDbConfig) ){
6200 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
6201 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
6202 }
6203 }else
6204
6205 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00006206 rc = shell_dbinfo_command(p, nArg, azArg);
6207 }else
6208
6209 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
6210 const char *zLike = 0;
6211 int i;
6212 int savedShowHeader = p->showHeader;
drhf213b332018-07-05 17:35:46 +00006213 int savedShellFlags = p->shellFlgs;
6214 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
drh2ce15c32017-07-11 13:34:40 +00006215 for(i=1; i<nArg; i++){
6216 if( azArg[i][0]=='-' ){
6217 const char *z = azArg[i]+1;
6218 if( z[0]=='-' ) z++;
6219 if( strcmp(z,"preserve-rowids")==0 ){
6220#ifdef SQLITE_OMIT_VIRTUALTABLE
6221 raw_printf(stderr, "The --preserve-rowids option is not compatible"
6222 " with SQLITE_OMIT_VIRTUALTABLE\n");
6223 rc = 1;
6224 goto meta_command_exit;
6225#else
6226 ShellSetFlag(p, SHFLG_PreserveRowid);
6227#endif
6228 }else
6229 if( strcmp(z,"newlines")==0 ){
6230 ShellSetFlag(p, SHFLG_Newlines);
6231 }else
6232 {
6233 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
6234 rc = 1;
6235 goto meta_command_exit;
6236 }
6237 }else if( zLike ){
6238 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
6239 "?--newlines? ?LIKE-PATTERN?\n");
6240 rc = 1;
6241 goto meta_command_exit;
6242 }else{
6243 zLike = azArg[i];
6244 }
6245 }
6246 open_db(p, 0);
6247 /* When playing back a "dump", the content might appear in an order
6248 ** which causes immediate foreign key constraints to be violated.
6249 ** So disable foreign-key constraint enforcement to prevent problems. */
6250 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
6251 raw_printf(p->out, "BEGIN TRANSACTION;\n");
6252 p->writableSchema = 0;
6253 p->showHeader = 0;
6254 /* Set writable_schema=ON since doing so forces SQLite to initialize
6255 ** as much of the schema as it can even if the sqlite_master table is
6256 ** corrupt. */
6257 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
6258 p->nErr = 0;
6259 if( zLike==0 ){
6260 run_schema_dump_query(p,
6261 "SELECT name, type, sql FROM sqlite_master "
6262 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
6263 );
6264 run_schema_dump_query(p,
6265 "SELECT name, type, sql FROM sqlite_master "
6266 "WHERE name=='sqlite_sequence'"
6267 );
6268 run_table_dump_query(p,
6269 "SELECT sql FROM sqlite_master "
6270 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
6271 );
6272 }else{
6273 char *zSql;
6274 zSql = sqlite3_mprintf(
6275 "SELECT name, type, sql FROM sqlite_master "
6276 "WHERE tbl_name LIKE %Q AND type=='table'"
6277 " AND sql NOT NULL", zLike);
6278 run_schema_dump_query(p,zSql);
6279 sqlite3_free(zSql);
6280 zSql = sqlite3_mprintf(
6281 "SELECT sql FROM sqlite_master "
6282 "WHERE sql NOT NULL"
6283 " AND type IN ('index','trigger','view')"
6284 " AND tbl_name LIKE %Q", zLike);
6285 run_table_dump_query(p, zSql, 0);
6286 sqlite3_free(zSql);
6287 }
6288 if( p->writableSchema ){
6289 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
6290 p->writableSchema = 0;
6291 }
6292 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6293 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
6294 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
6295 p->showHeader = savedShowHeader;
drhf213b332018-07-05 17:35:46 +00006296 p->shellFlgs = savedShellFlags;
drh2ce15c32017-07-11 13:34:40 +00006297 }else
6298
6299 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
6300 if( nArg==2 ){
6301 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
6302 }else{
6303 raw_printf(stderr, "Usage: .echo on|off\n");
6304 rc = 1;
6305 }
6306 }else
6307
6308 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
6309 if( nArg==2 ){
drhe2ca99c2018-05-02 00:33:43 +00006310 p->autoEQPtest = 0;
drhb4e50392019-01-26 15:40:04 +00006311 if( p->autoEQPtrace ){
6312 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
6313 p->autoEQPtrace = 0;
6314 }
drh2ce15c32017-07-11 13:34:40 +00006315 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00006316 p->autoEQP = AUTOEQP_full;
6317 }else if( strcmp(azArg[1],"trigger")==0 ){
6318 p->autoEQP = AUTOEQP_trigger;
drhb4e50392019-01-26 15:40:04 +00006319#ifdef SQLITE_DEBUG
drhe2ca99c2018-05-02 00:33:43 +00006320 }else if( strcmp(azArg[1],"test")==0 ){
6321 p->autoEQP = AUTOEQP_on;
6322 p->autoEQPtest = 1;
drhb4e50392019-01-26 15:40:04 +00006323 }else if( strcmp(azArg[1],"trace")==0 ){
6324 p->autoEQP = AUTOEQP_full;
6325 p->autoEQPtrace = 1;
6326 open_db(p, 0);
drhc07eee72019-01-27 19:50:56 +00006327 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
drhb4e50392019-01-26 15:40:04 +00006328 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
6329#endif
drh2ce15c32017-07-11 13:34:40 +00006330 }else{
mistachkinb71aa092018-01-23 00:05:18 +00006331 p->autoEQP = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00006332 }
6333 }else{
drhb4e50392019-01-26 15:40:04 +00006334 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00006335 rc = 1;
6336 }
6337 }else
6338
6339 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
6340 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
6341 rc = 2;
6342 }else
6343
6344 /* The ".explain" command is automatic now. It is largely pointless. It
6345 ** retained purely for backwards compatibility */
6346 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
6347 int val = 1;
6348 if( nArg>=2 ){
6349 if( strcmp(azArg[1],"auto")==0 ){
6350 val = 99;
6351 }else{
6352 val = booleanValue(azArg[1]);
6353 }
6354 }
6355 if( val==1 && p->mode!=MODE_Explain ){
6356 p->normalMode = p->mode;
6357 p->mode = MODE_Explain;
6358 p->autoExplain = 0;
6359 }else if( val==0 ){
6360 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6361 p->autoExplain = 0;
6362 }else if( val==99 ){
6363 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6364 p->autoExplain = 1;
6365 }
6366 }else
6367
dan6b046be2018-01-09 15:25:55 +00006368#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006369 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
6370 open_db(p, 0);
6371 expertDotCommand(p, azArg, nArg);
6372 }else
dan6b046be2018-01-09 15:25:55 +00006373#endif
dan43efc182017-12-19 17:42:13 +00006374
drh2ce15c32017-07-11 13:34:40 +00006375 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
6376 ShellState data;
6377 char *zErrMsg = 0;
6378 int doStats = 0;
6379 memcpy(&data, p, sizeof(data));
6380 data.showHeader = 0;
6381 data.cMode = data.mode = MODE_Semi;
6382 if( nArg==2 && optionMatch(azArg[1], "indent") ){
6383 data.cMode = data.mode = MODE_Pretty;
6384 nArg = 1;
6385 }
6386 if( nArg!=1 ){
6387 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
6388 rc = 1;
6389 goto meta_command_exit;
6390 }
6391 open_db(p, 0);
6392 rc = sqlite3_exec(p->db,
6393 "SELECT sql FROM"
6394 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
6395 " FROM sqlite_master UNION ALL"
6396 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
6397 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
6398 "ORDER BY rowid",
6399 callback, &data, &zErrMsg
6400 );
6401 if( rc==SQLITE_OK ){
6402 sqlite3_stmt *pStmt;
6403 rc = sqlite3_prepare_v2(p->db,
6404 "SELECT rowid FROM sqlite_master"
6405 " WHERE name GLOB 'sqlite_stat[134]'",
6406 -1, &pStmt, 0);
6407 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
6408 sqlite3_finalize(pStmt);
6409 }
6410 if( doStats==0 ){
6411 raw_printf(p->out, "/* No STAT tables available */\n");
6412 }else{
6413 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6414 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
6415 callback, &data, &zErrMsg);
6416 data.cMode = data.mode = MODE_Insert;
6417 data.zDestTable = "sqlite_stat1";
drh4c540452018-05-08 23:17:36 +00006418 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006419 data.zDestTable = "sqlite_stat3";
drh4c540452018-05-08 23:17:36 +00006420 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006421 data.zDestTable = "sqlite_stat4";
drh4c540452018-05-08 23:17:36 +00006422 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006423 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6424 }
6425 }else
6426
6427 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
6428 if( nArg==2 ){
6429 p->showHeader = booleanValue(azArg[1]);
6430 }else{
6431 raw_printf(stderr, "Usage: .headers on|off\n");
6432 rc = 1;
6433 }
6434 }else
6435
6436 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
drh98aa2ab2018-09-26 16:53:51 +00006437 if( nArg>=2 ){
drhe93f8262018-10-11 16:53:37 +00006438 n = showHelp(p->out, azArg[1]);
drh98aa2ab2018-09-26 16:53:51 +00006439 if( n==0 ){
6440 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
6441 }
6442 }else{
6443 showHelp(p->out, 0);
6444 }
drh2ce15c32017-07-11 13:34:40 +00006445 }else
6446
6447 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
6448 char *zTable; /* Insert data into this table */
6449 char *zFile; /* Name of file to extra content from */
6450 sqlite3_stmt *pStmt = NULL; /* A statement */
6451 int nCol; /* Number of columns in the table */
6452 int nByte; /* Number of bytes in an SQL string */
6453 int i, j; /* Loop counters */
6454 int needCommit; /* True to COMMIT or ROLLBACK at end */
6455 int nSep; /* Number of bytes in p->colSeparator[] */
6456 char *zSql; /* An SQL statement */
6457 ImportCtx sCtx; /* Reader context */
6458 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
6459 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
6460
6461 if( nArg!=3 ){
6462 raw_printf(stderr, "Usage: .import FILE TABLE\n");
6463 goto meta_command_exit;
6464 }
6465 zFile = azArg[1];
6466 zTable = azArg[2];
6467 seenInterrupt = 0;
6468 memset(&sCtx, 0, sizeof(sCtx));
6469 open_db(p, 0);
6470 nSep = strlen30(p->colSeparator);
6471 if( nSep==0 ){
6472 raw_printf(stderr,
6473 "Error: non-null column separator required for import\n");
6474 return 1;
6475 }
6476 if( nSep>1 ){
6477 raw_printf(stderr, "Error: multi-character column separators not allowed"
6478 " for import\n");
6479 return 1;
6480 }
6481 nSep = strlen30(p->rowSeparator);
6482 if( nSep==0 ){
6483 raw_printf(stderr, "Error: non-null row separator required for import\n");
6484 return 1;
6485 }
6486 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
6487 /* When importing CSV (only), if the row separator is set to the
6488 ** default output row separator, change it to the default input
6489 ** row separator. This avoids having to maintain different input
6490 ** and output row separators. */
6491 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6492 nSep = strlen30(p->rowSeparator);
6493 }
6494 if( nSep>1 ){
6495 raw_printf(stderr, "Error: multi-character row separators not allowed"
6496 " for import\n");
6497 return 1;
6498 }
6499 sCtx.zFile = zFile;
6500 sCtx.nLine = 1;
6501 if( sCtx.zFile[0]=='|' ){
6502#ifdef SQLITE_OMIT_POPEN
6503 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6504 return 1;
6505#else
6506 sCtx.in = popen(sCtx.zFile+1, "r");
6507 sCtx.zFile = "<pipe>";
6508 xCloser = pclose;
6509#endif
6510 }else{
6511 sCtx.in = fopen(sCtx.zFile, "rb");
6512 xCloser = fclose;
6513 }
6514 if( p->mode==MODE_Ascii ){
6515 xRead = ascii_read_one_field;
6516 }else{
6517 xRead = csv_read_one_field;
6518 }
6519 if( sCtx.in==0 ){
6520 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
6521 return 1;
6522 }
6523 sCtx.cColSep = p->colSeparator[0];
6524 sCtx.cRowSep = p->rowSeparator[0];
6525 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
6526 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00006527 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00006528 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00006529 }
6530 nByte = strlen30(zSql);
6531 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6532 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
6533 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
6534 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
6535 char cSep = '(';
6536 while( xRead(&sCtx) ){
6537 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
6538 cSep = ',';
6539 if( sCtx.cTerm!=sCtx.cColSep ) break;
6540 }
6541 if( cSep=='(' ){
6542 sqlite3_free(zCreate);
6543 sqlite3_free(sCtx.z);
6544 xCloser(sCtx.in);
6545 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
6546 return 1;
6547 }
6548 zCreate = sqlite3_mprintf("%z\n)", zCreate);
6549 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
6550 sqlite3_free(zCreate);
6551 if( rc ){
6552 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
6553 sqlite3_errmsg(p->db));
6554 sqlite3_free(sCtx.z);
6555 xCloser(sCtx.in);
6556 return 1;
6557 }
6558 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6559 }
6560 sqlite3_free(zSql);
6561 if( rc ){
6562 if (pStmt) sqlite3_finalize(pStmt);
6563 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
6564 xCloser(sCtx.in);
6565 return 1;
6566 }
6567 nCol = sqlite3_column_count(pStmt);
6568 sqlite3_finalize(pStmt);
6569 pStmt = 0;
6570 if( nCol==0 ) return 0; /* no columns, no error */
6571 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
6572 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00006573 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00006574 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00006575 }
6576 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
6577 j = strlen30(zSql);
6578 for(i=1; i<nCol; i++){
6579 zSql[j++] = ',';
6580 zSql[j++] = '?';
6581 }
6582 zSql[j++] = ')';
6583 zSql[j] = 0;
6584 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6585 sqlite3_free(zSql);
6586 if( rc ){
6587 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6588 if (pStmt) sqlite3_finalize(pStmt);
6589 xCloser(sCtx.in);
6590 return 1;
6591 }
6592 needCommit = sqlite3_get_autocommit(p->db);
6593 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
6594 do{
6595 int startLine = sCtx.nLine;
6596 for(i=0; i<nCol; i++){
6597 char *z = xRead(&sCtx);
6598 /*
6599 ** Did we reach end-of-file before finding any columns?
6600 ** If so, stop instead of NULL filling the remaining columns.
6601 */
6602 if( z==0 && i==0 ) break;
6603 /*
6604 ** Did we reach end-of-file OR end-of-line before finding any
6605 ** columns in ASCII mode? If so, stop instead of NULL filling
6606 ** the remaining columns.
6607 */
6608 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
6609 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
6610 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
6611 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6612 "filling the rest with NULL\n",
6613 sCtx.zFile, startLine, nCol, i+1);
6614 i += 2;
6615 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
6616 }
6617 }
6618 if( sCtx.cTerm==sCtx.cColSep ){
6619 do{
6620 xRead(&sCtx);
6621 i++;
6622 }while( sCtx.cTerm==sCtx.cColSep );
6623 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6624 "extras ignored\n",
6625 sCtx.zFile, startLine, nCol, i);
6626 }
6627 if( i>=nCol ){
6628 sqlite3_step(pStmt);
6629 rc = sqlite3_reset(pStmt);
6630 if( rc!=SQLITE_OK ){
6631 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
6632 startLine, sqlite3_errmsg(p->db));
6633 }
6634 }
6635 }while( sCtx.cTerm!=EOF );
6636
6637 xCloser(sCtx.in);
6638 sqlite3_free(sCtx.z);
6639 sqlite3_finalize(pStmt);
6640 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
6641 }else
6642
6643#ifndef SQLITE_UNTESTABLE
6644 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
6645 char *zSql;
6646 char *zCollist = 0;
6647 sqlite3_stmt *pStmt;
6648 int tnum = 0;
6649 int i;
drh48d219a2018-04-23 18:38:48 +00006650 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
6651 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
6652 " .imposter off\n");
drh2ce15c32017-07-11 13:34:40 +00006653 rc = 1;
6654 goto meta_command_exit;
6655 }
6656 open_db(p, 0);
drh48d219a2018-04-23 18:38:48 +00006657 if( nArg==2 ){
6658 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
6659 goto meta_command_exit;
6660 }
drh2ce15c32017-07-11 13:34:40 +00006661 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6662 " WHERE name='%q' AND type='index'", azArg[1]);
6663 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6664 sqlite3_free(zSql);
6665 if( sqlite3_step(pStmt)==SQLITE_ROW ){
6666 tnum = sqlite3_column_int(pStmt, 0);
6667 }
6668 sqlite3_finalize(pStmt);
6669 if( tnum==0 ){
6670 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
6671 rc = 1;
6672 goto meta_command_exit;
6673 }
6674 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
6675 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6676 sqlite3_free(zSql);
6677 i = 0;
6678 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6679 char zLabel[20];
6680 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
6681 i++;
6682 if( zCol==0 ){
6683 if( sqlite3_column_int(pStmt,1)==-1 ){
6684 zCol = "_ROWID_";
6685 }else{
6686 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
6687 zCol = zLabel;
6688 }
6689 }
6690 if( zCollist==0 ){
6691 zCollist = sqlite3_mprintf("\"%w\"", zCol);
6692 }else{
6693 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
6694 }
6695 }
6696 sqlite3_finalize(pStmt);
6697 zSql = sqlite3_mprintf(
6698 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6699 azArg[2], zCollist, zCollist);
6700 sqlite3_free(zCollist);
6701 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
6702 if( rc==SQLITE_OK ){
6703 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
6704 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
6705 if( rc ){
6706 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
6707 }else{
6708 utf8_printf(stdout, "%s;\n", zSql);
6709 raw_printf(stdout,
6710 "WARNING: writing to an imposter table will corrupt the index!\n"
6711 );
6712 }
6713 }else{
6714 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
6715 rc = 1;
6716 }
6717 sqlite3_free(zSql);
6718 }else
6719#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6720
6721#ifdef SQLITE_ENABLE_IOTRACE
6722 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
6723 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
6724 if( iotrace && iotrace!=stdout ) fclose(iotrace);
6725 iotrace = 0;
6726 if( nArg<2 ){
6727 sqlite3IoTrace = 0;
6728 }else if( strcmp(azArg[1], "-")==0 ){
6729 sqlite3IoTrace = iotracePrintf;
6730 iotrace = stdout;
6731 }else{
6732 iotrace = fopen(azArg[1], "w");
6733 if( iotrace==0 ){
6734 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
6735 sqlite3IoTrace = 0;
6736 rc = 1;
6737 }else{
6738 sqlite3IoTrace = iotracePrintf;
6739 }
6740 }
6741 }else
6742#endif
6743
6744 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
6745 static const struct {
6746 const char *zLimitName; /* Name of a limit */
6747 int limitCode; /* Integer code for that limit */
6748 } aLimit[] = {
6749 { "length", SQLITE_LIMIT_LENGTH },
6750 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
6751 { "column", SQLITE_LIMIT_COLUMN },
6752 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
6753 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
6754 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
6755 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
6756 { "attached", SQLITE_LIMIT_ATTACHED },
6757 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
6758 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
6759 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
6760 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
6761 };
6762 int i, n2;
6763 open_db(p, 0);
6764 if( nArg==1 ){
6765 for(i=0; i<ArraySize(aLimit); i++){
6766 printf("%20s %d\n", aLimit[i].zLimitName,
6767 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
6768 }
6769 }else if( nArg>3 ){
6770 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
6771 rc = 1;
6772 goto meta_command_exit;
6773 }else{
6774 int iLimit = -1;
6775 n2 = strlen30(azArg[1]);
6776 for(i=0; i<ArraySize(aLimit); i++){
6777 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
6778 if( iLimit<0 ){
6779 iLimit = i;
6780 }else{
6781 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
6782 rc = 1;
6783 goto meta_command_exit;
6784 }
6785 }
6786 }
6787 if( iLimit<0 ){
6788 utf8_printf(stderr, "unknown limit: \"%s\"\n"
6789 "enter \".limits\" with no arguments for a list.\n",
6790 azArg[1]);
6791 rc = 1;
6792 goto meta_command_exit;
6793 }
6794 if( nArg==3 ){
6795 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
6796 (int)integerValue(azArg[2]));
6797 }
6798 printf("%20s %d\n", aLimit[iLimit].zLimitName,
6799 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
6800 }
6801 }else
6802
6803 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
6804 open_db(p, 0);
6805 lintDotCommand(p, azArg, nArg);
6806 }else
6807
6808#ifndef SQLITE_OMIT_LOAD_EXTENSION
6809 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
6810 const char *zFile, *zProc;
6811 char *zErrMsg = 0;
6812 if( nArg<2 ){
6813 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
6814 rc = 1;
6815 goto meta_command_exit;
6816 }
6817 zFile = azArg[1];
6818 zProc = nArg>=3 ? azArg[2] : 0;
6819 open_db(p, 0);
6820 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
6821 if( rc!=SQLITE_OK ){
6822 utf8_printf(stderr, "Error: %s\n", zErrMsg);
6823 sqlite3_free(zErrMsg);
6824 rc = 1;
6825 }
6826 }else
6827#endif
6828
6829 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
6830 if( nArg!=2 ){
6831 raw_printf(stderr, "Usage: .log FILENAME\n");
6832 rc = 1;
6833 }else{
6834 const char *zFile = azArg[1];
6835 output_file_close(p->pLog);
drha92a01a2018-01-10 22:15:37 +00006836 p->pLog = output_file_open(zFile, 0);
drh2ce15c32017-07-11 13:34:40 +00006837 }
6838 }else
6839
6840 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6841 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00006842 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00006843 int c2 = zMode[0];
6844 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
6845 p->mode = MODE_Line;
6846 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6847 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
6848 p->mode = MODE_Column;
6849 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6850 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
6851 p->mode = MODE_List;
6852 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6853 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6854 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
6855 p->mode = MODE_Html;
6856 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
6857 p->mode = MODE_Tcl;
6858 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
6859 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6860 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
6861 p->mode = MODE_Csv;
6862 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6863 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6864 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
6865 p->mode = MODE_List;
6866 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
6867 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
6868 p->mode = MODE_Insert;
6869 set_table_name(p, nArg>=3 ? azArg[2] : "table");
6870 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6871 p->mode = MODE_Quote;
6872 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6873 p->mode = MODE_Ascii;
6874 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6875 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
6876 }else if( nArg==1 ){
6877 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6878 }else{
6879 raw_printf(stderr, "Error: mode should be one of: "
6880 "ascii column csv html insert line list quote tabs tcl\n");
6881 rc = 1;
6882 }
6883 p->cMode = p->mode;
6884 }else
6885
6886 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6887 if( nArg==2 ){
6888 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6889 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
6890 }else{
6891 raw_printf(stderr, "Usage: .nullvalue STRING\n");
6892 rc = 1;
6893 }
6894 }else
6895
6896 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
6897 char *zNewFilename; /* Name of the database file to open */
6898 int iName = 1; /* Index in azArg[] of the filename */
6899 int newFlag = 0; /* True to delete file before opening */
6900 /* Close the existing database */
6901 session_close_all(p);
drh9e804032018-05-18 17:11:50 +00006902 close_db(p->db);
drh2ce15c32017-07-11 13:34:40 +00006903 p->db = 0;
6904 p->zDbFilename = 0;
6905 sqlite3_free(p->zFreeOnClose);
6906 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00006907 p->openMode = SHELL_OPEN_UNSPEC;
drh6ca64482019-01-22 16:06:20 +00006908 p->szMax = 0;
drh2ce15c32017-07-11 13:34:40 +00006909 /* Check for command-line arguments */
6910 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6911 const char *z = azArg[iName];
6912 if( optionMatch(z,"new") ){
6913 newFlag = 1;
drh3baed312018-03-08 18:14:41 +00006914#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00006915 }else if( optionMatch(z, "zip") ){
6916 p->openMode = SHELL_OPEN_ZIPFILE;
6917#endif
6918 }else if( optionMatch(z, "append") ){
6919 p->openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00006920 }else if( optionMatch(z, "readonly") ){
6921 p->openMode = SHELL_OPEN_READONLY;
drha751f392018-10-30 15:31:22 +00006922#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00006923 }else if( optionMatch(z, "deserialize") ){
6924 p->openMode = SHELL_OPEN_DESERIALIZE;
drh33746482018-12-13 15:06:26 +00006925 }else if( optionMatch(z, "hexdb") ){
6926 p->openMode = SHELL_OPEN_HEXDB;
drh6ca64482019-01-22 16:06:20 +00006927 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
6928 p->szMax = integerValue(azArg[++iName]);
drh33746482018-12-13 15:06:26 +00006929#endif /* SQLITE_ENABLE_DESERIALIZE */
drh2ce15c32017-07-11 13:34:40 +00006930 }else if( z[0]=='-' ){
6931 utf8_printf(stderr, "unknown option: %s\n", z);
6932 rc = 1;
6933 goto meta_command_exit;
6934 }
6935 }
6936 /* If a filename is specified, try to open it first */
6937 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
drh33746482018-12-13 15:06:26 +00006938 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
drh2ce15c32017-07-11 13:34:40 +00006939 if( newFlag ) shellDeleteFile(zNewFilename);
6940 p->zDbFilename = zNewFilename;
drhbe4ccb22018-05-17 20:04:24 +00006941 open_db(p, OPEN_DB_KEEPALIVE);
drh2ce15c32017-07-11 13:34:40 +00006942 if( p->db==0 ){
6943 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6944 sqlite3_free(zNewFilename);
6945 }else{
6946 p->zFreeOnClose = zNewFilename;
6947 }
6948 }
6949 if( p->db==0 ){
6950 /* As a fall-back open a TEMP database */
6951 p->zDbFilename = 0;
6952 open_db(p, 0);
6953 }
6954 }else
6955
drh13c20932018-01-10 21:41:55 +00006956 if( (c=='o'
6957 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
6958 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
drh2ce15c32017-07-11 13:34:40 +00006959 ){
6960 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
drha92a01a2018-01-10 22:15:37 +00006961 int bTxtMode = 0;
drh13c20932018-01-10 21:41:55 +00006962 if( azArg[0][0]=='e' ){
6963 /* Transform the ".excel" command into ".once -x" */
6964 nArg = 2;
6965 azArg[0] = "once";
6966 zFile = azArg[1] = "-x";
6967 n = 4;
6968 }
drh2ce15c32017-07-11 13:34:40 +00006969 if( nArg>2 ){
drh13c20932018-01-10 21:41:55 +00006970 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00006971 rc = 1;
6972 goto meta_command_exit;
6973 }
6974 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6975 if( nArg<2 ){
drh13c20932018-01-10 21:41:55 +00006976 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
drh2ce15c32017-07-11 13:34:40 +00006977 rc = 1;
6978 goto meta_command_exit;
6979 }
6980 p->outCount = 2;
6981 }else{
6982 p->outCount = 0;
6983 }
6984 output_reset(p);
drh13c20932018-01-10 21:41:55 +00006985 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
drh04a28c32018-01-31 01:38:44 +00006986#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00006987 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
drh3c484e82018-01-10 22:27:21 +00006988 p->doXdgOpen = 1;
6989 outputModePush(p);
drh13c20932018-01-10 21:41:55 +00006990 if( zFile[1]=='x' ){
6991 newTempFile(p, "csv");
6992 p->mode = MODE_Csv;
6993 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6994 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6995 }else{
6996 newTempFile(p, "txt");
drha92a01a2018-01-10 22:15:37 +00006997 bTxtMode = 1;
drh13c20932018-01-10 21:41:55 +00006998 }
6999 zFile = p->zTempFile;
7000 }
drh04a28c32018-01-31 01:38:44 +00007001#endif /* SQLITE_NOHAVE_SYSTEM */
drh2ce15c32017-07-11 13:34:40 +00007002 if( zFile[0]=='|' ){
7003#ifdef SQLITE_OMIT_POPEN
7004 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7005 rc = 1;
7006 p->out = stdout;
7007#else
7008 p->out = popen(zFile + 1, "w");
7009 if( p->out==0 ){
7010 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
7011 p->out = stdout;
7012 rc = 1;
7013 }else{
7014 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7015 }
7016#endif
7017 }else{
drha92a01a2018-01-10 22:15:37 +00007018 p->out = output_file_open(zFile, bTxtMode);
drh2ce15c32017-07-11 13:34:40 +00007019 if( p->out==0 ){
7020 if( strcmp(zFile,"off")!=0 ){
7021 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
7022 }
7023 p->out = stdout;
7024 rc = 1;
7025 } else {
7026 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7027 }
7028 }
7029 }else
7030
7031 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
7032 int i;
7033 for(i=1; i<nArg; i++){
7034 if( i>1 ) raw_printf(p->out, " ");
7035 utf8_printf(p->out, "%s", azArg[i]);
7036 }
7037 raw_printf(p->out, "\n");
7038 }else
7039
drh569b1d92019-02-05 20:51:41 +00007040#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00007041 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
7042 int i;
drhfc4eeef2019-02-05 19:48:46 +00007043 int nn = 0;
drh3f83f592019-02-04 14:53:18 +00007044 p->flgProgress = 0;
7045 p->mxProgress = 0;
7046 p->nProgress = 0;
7047 for(i=1; i<nArg; i++){
7048 const char *z = azArg[i];
7049 if( z[0]=='-' ){
7050 z++;
7051 if( z[0]=='-' ) z++;
7052 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007053 p->flgProgress |= SHELL_PROGRESS_QUIET;
drh3f83f592019-02-04 14:53:18 +00007054 continue;
7055 }
7056 if( strcmp(z,"reset")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007057 p->flgProgress |= SHELL_PROGRESS_RESET;
drh3f83f592019-02-04 14:53:18 +00007058 continue;
7059 }
7060 if( strcmp(z,"once")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007061 p->flgProgress |= SHELL_PROGRESS_ONCE;
drh3f83f592019-02-04 14:53:18 +00007062 continue;
7063 }
7064 if( strcmp(z,"limit")==0 ){
7065 if( i+1>=nArg ){
7066 utf8_printf(stderr, "Error: missing argument on --limit\n");
7067 rc = 1;
7068 goto meta_command_exit;
7069 }else{
7070 p->mxProgress = (int)integerValue(azArg[++i]);
7071 }
7072 continue;
7073 }
7074 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
7075 rc = 1;
7076 goto meta_command_exit;
7077 }else{
drhfc4eeef2019-02-05 19:48:46 +00007078 nn = (int)integerValue(z);
drh3f83f592019-02-04 14:53:18 +00007079 }
7080 }
7081 open_db(p, 0);
drhfc4eeef2019-02-05 19:48:46 +00007082 sqlite3_progress_handler(p->db, nn, progress_handler, p);
drh3f83f592019-02-04 14:53:18 +00007083 }else
drh569b1d92019-02-05 20:51:41 +00007084#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00007085
drh2ce15c32017-07-11 13:34:40 +00007086 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
7087 if( nArg >= 2) {
7088 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
7089 }
7090 if( nArg >= 3) {
7091 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
7092 }
7093 }else
7094
7095 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
7096 rc = 2;
7097 }else
7098
7099 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
drh60379d42018-12-13 18:30:01 +00007100 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00007101 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00007102 if( nArg!=2 ){
7103 raw_printf(stderr, "Usage: .read FILE\n");
7104 rc = 1;
7105 goto meta_command_exit;
7106 }
drh60379d42018-12-13 18:30:01 +00007107 p->in = fopen(azArg[1], "rb");
7108 if( p->in==0 ){
drh2ce15c32017-07-11 13:34:40 +00007109 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
7110 rc = 1;
7111 }else{
drh60379d42018-12-13 18:30:01 +00007112 rc = process_input(p);
7113 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00007114 }
drh60379d42018-12-13 18:30:01 +00007115 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00007116 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00007117 }else
7118
7119 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
7120 const char *zSrcFile;
7121 const char *zDb;
7122 sqlite3 *pSrc;
7123 sqlite3_backup *pBackup;
7124 int nTimeout = 0;
7125
7126 if( nArg==2 ){
7127 zSrcFile = azArg[1];
7128 zDb = "main";
7129 }else if( nArg==3 ){
7130 zSrcFile = azArg[2];
7131 zDb = azArg[1];
7132 }else{
7133 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
7134 rc = 1;
7135 goto meta_command_exit;
7136 }
7137 rc = sqlite3_open(zSrcFile, &pSrc);
7138 if( rc!=SQLITE_OK ){
7139 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9e804032018-05-18 17:11:50 +00007140 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00007141 return 1;
7142 }
7143 open_db(p, 0);
7144 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
7145 if( pBackup==0 ){
7146 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9e804032018-05-18 17:11:50 +00007147 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00007148 return 1;
7149 }
7150 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
7151 || rc==SQLITE_BUSY ){
7152 if( rc==SQLITE_BUSY ){
7153 if( nTimeout++ >= 3 ) break;
7154 sqlite3_sleep(100);
7155 }
7156 }
7157 sqlite3_backup_finish(pBackup);
7158 if( rc==SQLITE_DONE ){
7159 rc = 0;
7160 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
7161 raw_printf(stderr, "Error: source database is busy\n");
7162 rc = 1;
7163 }else{
7164 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7165 rc = 1;
7166 }
drh9e804032018-05-18 17:11:50 +00007167 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00007168 }else
7169
drh2ce15c32017-07-11 13:34:40 +00007170 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
7171 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00007172 p->scanstatsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007173#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
7174 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
7175#endif
7176 }else{
7177 raw_printf(stderr, "Usage: .scanstats on|off\n");
7178 rc = 1;
7179 }
7180 }else
7181
7182 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
7183 ShellText sSelect;
7184 ShellState data;
7185 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00007186 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00007187 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00007188 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00007189 int bDebug = 0;
7190 int ii;
drh2ce15c32017-07-11 13:34:40 +00007191
7192 open_db(p, 0);
7193 memcpy(&data, p, sizeof(data));
7194 data.showHeader = 0;
7195 data.cMode = data.mode = MODE_Semi;
7196 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00007197 for(ii=1; ii<nArg; ii++){
7198 if( optionMatch(azArg[ii],"indent") ){
7199 data.cMode = data.mode = MODE_Pretty;
7200 }else if( optionMatch(azArg[ii],"debug") ){
7201 bDebug = 1;
7202 }else if( zName==0 ){
7203 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00007204 }else{
drhceba7922018-01-01 21:28:25 +00007205 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
7206 rc = 1;
7207 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00007208 }
drh2ce15c32017-07-11 13:34:40 +00007209 }
drhceba7922018-01-01 21:28:25 +00007210 if( zName!=0 ){
mistachkin9d107262018-03-23 14:24:34 +00007211 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
7212 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
drh2ce15c32017-07-11 13:34:40 +00007213 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00007214 new_argv[0] = sqlite3_mprintf(
7215 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00007216 " type text,\n"
7217 " name text,\n"
7218 " tbl_name text,\n"
7219 " rootpage integer,\n"
7220 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00007221 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00007222 new_argv[1] = 0;
7223 new_colv[0] = "sql";
7224 new_colv[1] = 0;
7225 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00007226 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00007227 }
drh2ce15c32017-07-11 13:34:40 +00007228 }
7229 if( zDiv ){
7230 sqlite3_stmt *pStmt = 0;
7231 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
7232 -1, &pStmt, 0);
7233 if( rc ){
7234 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7235 sqlite3_finalize(pStmt);
7236 rc = 1;
7237 goto meta_command_exit;
7238 }
7239 appendText(&sSelect, "SELECT sql FROM", 0);
7240 iSchema = 0;
7241 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7242 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
7243 char zScNum[30];
7244 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
7245 appendText(&sSelect, zDiv, 0);
7246 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00007247 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
7248 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00007249 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00007250 }else{
drhceba7922018-01-01 21:28:25 +00007251 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00007252 }
drhceba7922018-01-01 21:28:25 +00007253 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
7254 appendText(&sSelect, zScNum, 0);
7255 appendText(&sSelect, " AS snum, ", 0);
7256 appendText(&sSelect, zDb, '\'');
7257 appendText(&sSelect, " AS sname FROM ", 0);
7258 appendText(&sSelect, zDb, '"');
7259 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00007260 }
7261 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00007262#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00007263 if( zName ){
7264 appendText(&sSelect,
7265 " UNION ALL SELECT shell_module_schema(name),"
7266 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
7267 }
drhcde7b772018-01-02 12:50:40 +00007268#endif
drh2ce15c32017-07-11 13:34:40 +00007269 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00007270 if( zName ){
7271 char *zQarg = sqlite3_mprintf("%Q", zName);
mistachkin9d107262018-03-23 14:24:34 +00007272 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
7273 strchr(zName, '[') != 0;
drhceba7922018-01-01 21:28:25 +00007274 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00007275 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
7276 }else{
7277 appendText(&sSelect, "lower(tbl_name)", 0);
7278 }
mistachkin9d107262018-03-23 14:24:34 +00007279 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00007280 appendText(&sSelect, zQarg, 0);
mistachkin9d107262018-03-23 14:24:34 +00007281 if( !bGlob ){
7282 appendText(&sSelect, " ESCAPE '\\' ", 0);
7283 }
drh2ce15c32017-07-11 13:34:40 +00007284 appendText(&sSelect, " AND ", 0);
7285 sqlite3_free(zQarg);
7286 }
7287 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
7288 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00007289 if( bDebug ){
7290 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
7291 }else{
7292 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
7293 }
drh2ce15c32017-07-11 13:34:40 +00007294 freeText(&sSelect);
7295 }
7296 if( zErrMsg ){
7297 utf8_printf(stderr,"Error: %s\n", zErrMsg);
7298 sqlite3_free(zErrMsg);
7299 rc = 1;
7300 }else if( rc != SQLITE_OK ){
7301 raw_printf(stderr,"Error: querying schema information\n");
7302 rc = 1;
7303 }else{
7304 rc = 0;
7305 }
7306 }else
7307
7308#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
7309 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
7310 sqlite3SelectTrace = (int)integerValue(azArg[1]);
7311 }else
7312#endif
7313
7314#if defined(SQLITE_ENABLE_SESSION)
7315 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
7316 OpenSession *pSession = &p->aSession[0];
7317 char **azCmd = &azArg[1];
7318 int iSes = 0;
7319 int nCmd = nArg - 1;
7320 int i;
7321 if( nArg<=1 ) goto session_syntax_error;
7322 open_db(p, 0);
7323 if( nArg>=3 ){
7324 for(iSes=0; iSes<p->nSession; iSes++){
7325 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
7326 }
7327 if( iSes<p->nSession ){
7328 pSession = &p->aSession[iSes];
7329 azCmd++;
7330 nCmd--;
7331 }else{
7332 pSession = &p->aSession[0];
7333 iSes = 0;
7334 }
7335 }
7336
7337 /* .session attach TABLE
7338 ** Invoke the sqlite3session_attach() interface to attach a particular
7339 ** table so that it is never filtered.
7340 */
7341 if( strcmp(azCmd[0],"attach")==0 ){
7342 if( nCmd!=2 ) goto session_syntax_error;
7343 if( pSession->p==0 ){
7344 session_not_open:
7345 raw_printf(stderr, "ERROR: No sessions are open\n");
7346 }else{
7347 rc = sqlite3session_attach(pSession->p, azCmd[1]);
7348 if( rc ){
7349 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
7350 rc = 0;
7351 }
7352 }
7353 }else
7354
7355 /* .session changeset FILE
7356 ** .session patchset FILE
7357 ** Write a changeset or patchset into a file. The file is overwritten.
7358 */
7359 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
7360 FILE *out = 0;
7361 if( nCmd!=2 ) goto session_syntax_error;
7362 if( pSession->p==0 ) goto session_not_open;
7363 out = fopen(azCmd[1], "wb");
7364 if( out==0 ){
7365 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
7366 }else{
7367 int szChng;
7368 void *pChng;
7369 if( azCmd[0][0]=='c' ){
7370 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
7371 }else{
7372 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
7373 }
7374 if( rc ){
7375 printf("Error: error code %d\n", rc);
7376 rc = 0;
7377 }
7378 if( pChng
7379 && fwrite(pChng, szChng, 1, out)!=1 ){
7380 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
7381 szChng);
7382 }
7383 sqlite3_free(pChng);
7384 fclose(out);
7385 }
7386 }else
7387
7388 /* .session close
7389 ** Close the identified session
7390 */
7391 if( strcmp(azCmd[0], "close")==0 ){
7392 if( nCmd!=1 ) goto session_syntax_error;
7393 if( p->nSession ){
7394 session_close(pSession);
7395 p->aSession[iSes] = p->aSession[--p->nSession];
7396 }
7397 }else
7398
7399 /* .session enable ?BOOLEAN?
7400 ** Query or set the enable flag
7401 */
7402 if( strcmp(azCmd[0], "enable")==0 ){
7403 int ii;
7404 if( nCmd>2 ) goto session_syntax_error;
7405 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7406 if( p->nSession ){
7407 ii = sqlite3session_enable(pSession->p, ii);
7408 utf8_printf(p->out, "session %s enable flag = %d\n",
7409 pSession->zName, ii);
7410 }
7411 }else
7412
7413 /* .session filter GLOB ....
7414 ** Set a list of GLOB patterns of table names to be excluded.
7415 */
7416 if( strcmp(azCmd[0], "filter")==0 ){
7417 int ii, nByte;
7418 if( nCmd<2 ) goto session_syntax_error;
7419 if( p->nSession ){
7420 for(ii=0; ii<pSession->nFilter; ii++){
7421 sqlite3_free(pSession->azFilter[ii]);
7422 }
7423 sqlite3_free(pSession->azFilter);
7424 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
7425 pSession->azFilter = sqlite3_malloc( nByte );
7426 if( pSession->azFilter==0 ){
7427 raw_printf(stderr, "Error: out or memory\n");
7428 exit(1);
7429 }
7430 for(ii=1; ii<nCmd; ii++){
7431 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
7432 }
7433 pSession->nFilter = ii-1;
7434 }
7435 }else
7436
7437 /* .session indirect ?BOOLEAN?
7438 ** Query or set the indirect flag
7439 */
7440 if( strcmp(azCmd[0], "indirect")==0 ){
7441 int ii;
7442 if( nCmd>2 ) goto session_syntax_error;
7443 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7444 if( p->nSession ){
7445 ii = sqlite3session_indirect(pSession->p, ii);
7446 utf8_printf(p->out, "session %s indirect flag = %d\n",
7447 pSession->zName, ii);
7448 }
7449 }else
7450
7451 /* .session isempty
7452 ** Determine if the session is empty
7453 */
7454 if( strcmp(azCmd[0], "isempty")==0 ){
7455 int ii;
7456 if( nCmd!=1 ) goto session_syntax_error;
7457 if( p->nSession ){
7458 ii = sqlite3session_isempty(pSession->p);
7459 utf8_printf(p->out, "session %s isempty flag = %d\n",
7460 pSession->zName, ii);
7461 }
7462 }else
7463
7464 /* .session list
7465 ** List all currently open sessions
7466 */
7467 if( strcmp(azCmd[0],"list")==0 ){
7468 for(i=0; i<p->nSession; i++){
7469 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
7470 }
7471 }else
7472
7473 /* .session open DB NAME
7474 ** Open a new session called NAME on the attached database DB.
7475 ** DB is normally "main".
7476 */
7477 if( strcmp(azCmd[0],"open")==0 ){
7478 char *zName;
7479 if( nCmd!=3 ) goto session_syntax_error;
7480 zName = azCmd[2];
7481 if( zName[0]==0 ) goto session_syntax_error;
7482 for(i=0; i<p->nSession; i++){
7483 if( strcmp(p->aSession[i].zName,zName)==0 ){
7484 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
7485 goto meta_command_exit;
7486 }
7487 }
7488 if( p->nSession>=ArraySize(p->aSession) ){
7489 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
7490 goto meta_command_exit;
7491 }
7492 pSession = &p->aSession[p->nSession];
7493 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
7494 if( rc ){
7495 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
7496 rc = 0;
7497 goto meta_command_exit;
7498 }
7499 pSession->nFilter = 0;
7500 sqlite3session_table_filter(pSession->p, session_filter, pSession);
7501 p->nSession++;
7502 pSession->zName = sqlite3_mprintf("%s", zName);
7503 }else
7504 /* If no command name matches, show a syntax error */
7505 session_syntax_error:
drheb7f2a02018-09-26 18:02:32 +00007506 showHelp(p->out, "session");
drh2ce15c32017-07-11 13:34:40 +00007507 }else
7508#endif
7509
7510#ifdef SQLITE_DEBUG
7511 /* Undocumented commands for internal testing. Subject to change
7512 ** without notice. */
7513 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
7514 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
7515 int i, v;
7516 for(i=1; i<nArg; i++){
7517 v = booleanValue(azArg[i]);
7518 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
7519 }
7520 }
7521 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
7522 int i; sqlite3_int64 v;
7523 for(i=1; i<nArg; i++){
7524 char zBuf[200];
7525 v = integerValue(azArg[i]);
7526 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
7527 utf8_printf(p->out, "%s", zBuf);
7528 }
7529 }
7530 }else
7531#endif
7532
7533 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
7534 int bIsInit = 0; /* True to initialize the SELFTEST table */
7535 int bVerbose = 0; /* Verbose output */
7536 int bSelftestExists; /* True if SELFTEST already exists */
7537 int i, k; /* Loop counters */
7538 int nTest = 0; /* Number of tests runs */
7539 int nErr = 0; /* Number of errors seen */
7540 ShellText str; /* Answer for a query */
7541 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
7542
7543 open_db(p,0);
7544 for(i=1; i<nArg; i++){
7545 const char *z = azArg[i];
7546 if( z[0]=='-' && z[1]=='-' ) z++;
7547 if( strcmp(z,"-init")==0 ){
7548 bIsInit = 1;
7549 }else
7550 if( strcmp(z,"-v")==0 ){
7551 bVerbose++;
7552 }else
7553 {
7554 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7555 azArg[i], azArg[0]);
7556 raw_printf(stderr, "Should be one of: --init -v\n");
7557 rc = 1;
7558 goto meta_command_exit;
7559 }
7560 }
7561 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
7562 != SQLITE_OK ){
7563 bSelftestExists = 0;
7564 }else{
7565 bSelftestExists = 1;
7566 }
7567 if( bIsInit ){
7568 createSelftestTable(p);
7569 bSelftestExists = 1;
7570 }
7571 initText(&str);
7572 appendText(&str, "x", 0);
7573 for(k=bSelftestExists; k>=0; k--){
7574 if( k==1 ){
7575 rc = sqlite3_prepare_v2(p->db,
7576 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
7577 -1, &pStmt, 0);
7578 }else{
7579 rc = sqlite3_prepare_v2(p->db,
7580 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
7581 " (1,'run','PRAGMA integrity_check','ok')",
7582 -1, &pStmt, 0);
7583 }
7584 if( rc ){
7585 raw_printf(stderr, "Error querying the selftest table\n");
7586 rc = 1;
7587 sqlite3_finalize(pStmt);
7588 goto meta_command_exit;
7589 }
7590 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
7591 int tno = sqlite3_column_int(pStmt, 0);
7592 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
7593 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
7594 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
7595
7596 k = 0;
7597 if( bVerbose>0 ){
7598 char *zQuote = sqlite3_mprintf("%q", zSql);
7599 printf("%d: %s %s\n", tno, zOp, zSql);
7600 sqlite3_free(zQuote);
7601 }
7602 if( strcmp(zOp,"memo")==0 ){
7603 utf8_printf(p->out, "%s\n", zSql);
7604 }else
7605 if( strcmp(zOp,"run")==0 ){
7606 char *zErrMsg = 0;
7607 str.n = 0;
7608 str.z[0] = 0;
7609 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
7610 nTest++;
7611 if( bVerbose ){
7612 utf8_printf(p->out, "Result: %s\n", str.z);
7613 }
7614 if( rc || zErrMsg ){
7615 nErr++;
7616 rc = 1;
7617 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
7618 sqlite3_free(zErrMsg);
7619 }else if( strcmp(zAns,str.z)!=0 ){
7620 nErr++;
7621 rc = 1;
7622 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
7623 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
7624 }
7625 }else
7626 {
7627 utf8_printf(stderr,
7628 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
7629 rc = 1;
7630 break;
7631 }
7632 } /* End loop over rows of content from SELFTEST */
7633 sqlite3_finalize(pStmt);
7634 } /* End loop over k */
7635 freeText(&str);
7636 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
7637 }else
7638
7639 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
7640 if( nArg<2 || nArg>3 ){
7641 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
7642 rc = 1;
7643 }
7644 if( nArg>=2 ){
7645 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
7646 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
7647 }
7648 if( nArg>=3 ){
7649 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
7650 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
7651 }
7652 }else
7653
7654 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
7655 const char *zLike = 0; /* Which table to checksum. 0 means everything */
7656 int i; /* Loop counter */
7657 int bSchema = 0; /* Also hash the schema */
7658 int bSeparate = 0; /* Hash each table separately */
7659 int iSize = 224; /* Hash algorithm to use */
7660 int bDebug = 0; /* Only show the query that would have run */
7661 sqlite3_stmt *pStmt; /* For querying tables names */
7662 char *zSql; /* SQL to be run */
7663 char *zSep; /* Separator */
7664 ShellText sSql; /* Complete SQL for the query to run the hash */
7665 ShellText sQuery; /* Set of queries used to read all content */
7666 open_db(p, 0);
7667 for(i=1; i<nArg; i++){
7668 const char *z = azArg[i];
7669 if( z[0]=='-' ){
7670 z++;
7671 if( z[0]=='-' ) z++;
7672 if( strcmp(z,"schema")==0 ){
7673 bSchema = 1;
7674 }else
7675 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
7676 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
7677 ){
7678 iSize = atoi(&z[5]);
7679 }else
7680 if( strcmp(z,"debug")==0 ){
7681 bDebug = 1;
7682 }else
7683 {
7684 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7685 azArg[i], azArg[0]);
7686 raw_printf(stderr, "Should be one of: --schema"
drh003edba2018-05-11 15:10:43 +00007687 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
drh2ce15c32017-07-11 13:34:40 +00007688 rc = 1;
7689 goto meta_command_exit;
7690 }
7691 }else if( zLike ){
7692 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7693 rc = 1;
7694 goto meta_command_exit;
7695 }else{
7696 zLike = z;
7697 bSeparate = 1;
drhcedfecf2018-03-23 12:59:10 +00007698 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
drh2ce15c32017-07-11 13:34:40 +00007699 }
7700 }
7701 if( bSchema ){
7702 zSql = "SELECT lower(name) FROM sqlite_master"
7703 " WHERE type='table' AND coalesce(rootpage,0)>1"
7704 " UNION ALL SELECT 'sqlite_master'"
7705 " ORDER BY 1 collate nocase";
7706 }else{
7707 zSql = "SELECT lower(name) FROM sqlite_master"
7708 " WHERE type='table' AND coalesce(rootpage,0)>1"
7709 " AND name NOT LIKE 'sqlite_%'"
7710 " ORDER BY 1 collate nocase";
7711 }
7712 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7713 initText(&sQuery);
7714 initText(&sSql);
7715 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
7716 zSep = "VALUES(";
7717 while( SQLITE_ROW==sqlite3_step(pStmt) ){
7718 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
7719 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
7720 if( strncmp(zTab, "sqlite_",7)!=0 ){
7721 appendText(&sQuery,"SELECT * FROM ", 0);
7722 appendText(&sQuery,zTab,'"');
7723 appendText(&sQuery," NOT INDEXED;", 0);
7724 }else if( strcmp(zTab, "sqlite_master")==0 ){
7725 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7726 " ORDER BY name;", 0);
7727 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
7728 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
7729 " ORDER BY name;", 0);
7730 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
7731 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
7732 " ORDER BY tbl,idx;", 0);
7733 }else if( strcmp(zTab, "sqlite_stat3")==0
7734 || strcmp(zTab, "sqlite_stat4")==0 ){
7735 appendText(&sQuery, "SELECT * FROM ", 0);
7736 appendText(&sQuery, zTab, 0);
7737 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
7738 }
7739 appendText(&sSql, zSep, 0);
7740 appendText(&sSql, sQuery.z, '\'');
7741 sQuery.n = 0;
7742 appendText(&sSql, ",", 0);
7743 appendText(&sSql, zTab, '\'');
7744 zSep = "),(";
7745 }
7746 sqlite3_finalize(pStmt);
7747 if( bSeparate ){
7748 zSql = sqlite3_mprintf(
7749 "%s))"
7750 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7751 " FROM [sha3sum$query]",
7752 sSql.z, iSize);
7753 }else{
7754 zSql = sqlite3_mprintf(
7755 "%s))"
7756 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7757 " FROM [sha3sum$query]",
7758 sSql.z, iSize);
7759 }
7760 freeText(&sQuery);
7761 freeText(&sSql);
7762 if( bDebug ){
7763 utf8_printf(p->out, "%s\n", zSql);
7764 }else{
drha10b9992018-03-09 15:24:33 +00007765 shell_exec(p, zSql, 0);
drh2ce15c32017-07-11 13:34:40 +00007766 }
7767 sqlite3_free(zSql);
7768 }else
7769
drh04a28c32018-01-31 01:38:44 +00007770#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00007771 if( c=='s'
7772 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
7773 ){
7774 char *zCmd;
7775 int i, x;
7776 if( nArg<2 ){
7777 raw_printf(stderr, "Usage: .system COMMAND\n");
7778 rc = 1;
7779 goto meta_command_exit;
7780 }
7781 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
7782 for(i=2; i<nArg; i++){
7783 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
7784 zCmd, azArg[i]);
7785 }
7786 x = system(zCmd);
7787 sqlite3_free(zCmd);
7788 if( x ) raw_printf(stderr, "System command returns %d\n", x);
7789 }else
drh04a28c32018-01-31 01:38:44 +00007790#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00007791
7792 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00007793 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00007794 int i;
7795 if( nArg!=1 ){
7796 raw_printf(stderr, "Usage: .show\n");
7797 rc = 1;
7798 goto meta_command_exit;
7799 }
7800 utf8_printf(p->out, "%12.12s: %s\n","echo",
7801 azBool[ShellHasFlag(p, SHFLG_Echo)]);
7802 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
7803 utf8_printf(p->out, "%12.12s: %s\n","explain",
7804 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
7805 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
7806 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
7807 utf8_printf(p->out, "%12.12s: ", "nullvalue");
7808 output_c_string(p->out, p->nullValue);
7809 raw_printf(p->out, "\n");
7810 utf8_printf(p->out,"%12.12s: %s\n","output",
7811 strlen30(p->outfile) ? p->outfile : "stdout");
7812 utf8_printf(p->out,"%12.12s: ", "colseparator");
7813 output_c_string(p->out, p->colSeparator);
7814 raw_printf(p->out, "\n");
7815 utf8_printf(p->out,"%12.12s: ", "rowseparator");
7816 output_c_string(p->out, p->rowSeparator);
7817 raw_printf(p->out, "\n");
7818 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
7819 utf8_printf(p->out, "%12.12s: ", "width");
7820 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
7821 raw_printf(p->out, "%d ", p->colWidth[i]);
7822 }
7823 raw_printf(p->out, "\n");
7824 utf8_printf(p->out, "%12.12s: %s\n", "filename",
7825 p->zDbFilename ? p->zDbFilename : "");
7826 }else
7827
7828 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
7829 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00007830 p->statsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007831 }else if( nArg==1 ){
7832 display_stats(p->db, p, 0);
7833 }else{
7834 raw_printf(stderr, "Usage: .stats ?on|off?\n");
7835 rc = 1;
7836 }
7837 }else
7838
7839 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
7840 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
7841 || strncmp(azArg[0], "indexes", n)==0) )
7842 ){
7843 sqlite3_stmt *pStmt;
7844 char **azResult;
7845 int nRow, nAlloc;
7846 int ii;
7847 ShellText s;
7848 initText(&s);
7849 open_db(p, 0);
7850 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
drh9e804032018-05-18 17:11:50 +00007851 if( rc ){
7852 sqlite3_finalize(pStmt);
7853 return shellDatabaseError(p->db);
7854 }
drh2ce15c32017-07-11 13:34:40 +00007855
7856 if( nArg>2 && c=='i' ){
7857 /* It is an historical accident that the .indexes command shows an error
7858 ** when called with the wrong number of arguments whereas the .tables
7859 ** command does not. */
7860 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
7861 rc = 1;
drh9e804032018-05-18 17:11:50 +00007862 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00007863 goto meta_command_exit;
7864 }
7865 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
7866 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
7867 if( zDbName==0 ) continue;
7868 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
7869 if( sqlite3_stricmp(zDbName, "main")==0 ){
7870 appendText(&s, "SELECT name FROM ", 0);
7871 }else{
7872 appendText(&s, "SELECT ", 0);
7873 appendText(&s, zDbName, '\'');
7874 appendText(&s, "||'.'||name FROM ", 0);
7875 }
7876 appendText(&s, zDbName, '"');
7877 appendText(&s, ".sqlite_master ", 0);
7878 if( c=='t' ){
7879 appendText(&s," WHERE type IN ('table','view')"
7880 " AND name NOT LIKE 'sqlite_%'"
7881 " AND name LIKE ?1", 0);
7882 }else{
7883 appendText(&s," WHERE type='index'"
7884 " AND tbl_name LIKE ?1", 0);
7885 }
7886 }
7887 rc = sqlite3_finalize(pStmt);
7888 appendText(&s, " ORDER BY 1", 0);
7889 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
7890 freeText(&s);
7891 if( rc ) return shellDatabaseError(p->db);
7892
7893 /* Run the SQL statement prepared by the above block. Store the results
7894 ** as an array of nul-terminated strings in azResult[]. */
7895 nRow = nAlloc = 0;
7896 azResult = 0;
7897 if( nArg>1 ){
7898 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
7899 }else{
7900 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
7901 }
7902 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7903 if( nRow>=nAlloc ){
7904 char **azNew;
7905 int n2 = nAlloc*2 + 10;
7906 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh4b5345c2018-04-24 13:07:40 +00007907 if( azNew==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007908 nAlloc = n2;
7909 azResult = azNew;
7910 }
7911 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
drh4b5345c2018-04-24 13:07:40 +00007912 if( 0==azResult[nRow] ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007913 nRow++;
7914 }
7915 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
7916 rc = shellDatabaseError(p->db);
7917 }
7918
7919 /* Pretty-print the contents of array azResult[] to the output */
7920 if( rc==0 && nRow>0 ){
7921 int len, maxlen = 0;
7922 int i, j;
7923 int nPrintCol, nPrintRow;
7924 for(i=0; i<nRow; i++){
7925 len = strlen30(azResult[i]);
7926 if( len>maxlen ) maxlen = len;
7927 }
7928 nPrintCol = 80/(maxlen+2);
7929 if( nPrintCol<1 ) nPrintCol = 1;
7930 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
7931 for(i=0; i<nPrintRow; i++){
7932 for(j=i; j<nRow; j+=nPrintRow){
7933 char *zSp = j<nPrintRow ? "" : " ";
7934 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
7935 azResult[j] ? azResult[j]:"");
7936 }
7937 raw_printf(p->out, "\n");
7938 }
7939 }
7940
7941 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
7942 sqlite3_free(azResult);
7943 }else
7944
7945 /* Begin redirecting output to the file "testcase-out.txt" */
7946 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
7947 output_reset(p);
drha92a01a2018-01-10 22:15:37 +00007948 p->out = output_file_open("testcase-out.txt", 0);
drh2ce15c32017-07-11 13:34:40 +00007949 if( p->out==0 ){
7950 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
7951 }
7952 if( nArg>=2 ){
7953 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
7954 }else{
7955 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
7956 }
7957 }else
7958
7959#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00007960 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007961 static const struct {
7962 const char *zCtrlName; /* Name of a test-control option */
7963 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00007964 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00007965 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00007966 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
7967 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
7968 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7969 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7970 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
7971 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7972 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
drheea8eb62018-11-26 18:09:15 +00007973 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" },
drhef302e82017-11-15 19:14:08 +00007974 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
7975 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
7976 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00007977#ifdef YYCOVERAGE
7978 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
7979#endif
drhef302e82017-11-15 19:14:08 +00007980 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
7981 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
7982 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
7983 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
7984 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00007985 };
7986 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00007987 int iCtrl = -1;
7988 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7989 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00007990 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00007991 const char *zCmd = 0;
7992
drh2ce15c32017-07-11 13:34:40 +00007993 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00007994 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00007995
7996 /* The argument can optionally begin with "-" or "--" */
7997 if( zCmd[0]=='-' && zCmd[1] ){
7998 zCmd++;
7999 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8000 }
8001
8002 /* --help lists all test-controls */
8003 if( strcmp(zCmd,"help")==0 ){
8004 utf8_printf(p->out, "Available test-controls:\n");
8005 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00008006 utf8_printf(p->out, " .testctrl %s %s\n",
8007 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00008008 }
8009 rc = 1;
8010 goto meta_command_exit;
8011 }
drh2ce15c32017-07-11 13:34:40 +00008012
8013 /* convert testctrl text option to value. allow any unique prefix
8014 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00008015 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00008016 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00008017 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00008018 if( testctrl<0 ){
8019 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00008020 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00008021 }else{
drh35f51a42017-11-15 17:07:22 +00008022 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
8023 "Use \".testctrl --help\" for help\n", zCmd);
8024 rc = 1;
8025 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00008026 }
8027 }
8028 }
drhef302e82017-11-15 19:14:08 +00008029 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00008030 utf8_printf(stderr,"Error: unknown test-control: %s\n"
8031 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00008032 }else{
8033 switch(testctrl){
8034
8035 /* sqlite3_test_control(int, db, int) */
8036 case SQLITE_TESTCTRL_OPTIMIZATIONS:
8037 case SQLITE_TESTCTRL_RESERVE:
8038 if( nArg==3 ){
8039 int opt = (int)strtol(azArg[2], 0, 0);
8040 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00008041 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008042 }
8043 break;
8044
8045 /* sqlite3_test_control(int) */
8046 case SQLITE_TESTCTRL_PRNG_SAVE:
8047 case SQLITE_TESTCTRL_PRNG_RESTORE:
8048 case SQLITE_TESTCTRL_PRNG_RESET:
8049 case SQLITE_TESTCTRL_BYTEORDER:
8050 if( nArg==2 ){
8051 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00008052 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00008053 }
8054 break;
8055
8056 /* sqlite3_test_control(int, uint) */
8057 case SQLITE_TESTCTRL_PENDING_BYTE:
8058 if( nArg==3 ){
8059 unsigned int opt = (unsigned int)integerValue(azArg[2]);
8060 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00008061 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008062 }
8063 break;
8064
8065 /* sqlite3_test_control(int, int) */
8066 case SQLITE_TESTCTRL_ASSERT:
8067 case SQLITE_TESTCTRL_ALWAYS:
drheea8eb62018-11-26 18:09:15 +00008068 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
drhef302e82017-11-15 19:14:08 +00008069 if( nArg==3 ){
8070 int opt = booleanValue(azArg[2]);
8071 rc2 = sqlite3_test_control(testctrl, opt);
8072 isOk = 1;
8073 }
8074 break;
8075
8076 /* sqlite3_test_control(int, int) */
8077 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00008078 case SQLITE_TESTCTRL_NEVER_CORRUPT:
8079 if( nArg==3 ){
8080 int opt = booleanValue(azArg[2]);
8081 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00008082 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008083 }
8084 break;
8085
drh2ce15c32017-07-11 13:34:40 +00008086 case SQLITE_TESTCTRL_IMPOSTER:
8087 if( nArg==5 ){
8088 rc2 = sqlite3_test_control(testctrl, p->db,
8089 azArg[2],
8090 integerValue(azArg[3]),
8091 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00008092 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008093 }
8094 break;
drh0d9de992017-12-26 18:04:23 +00008095
8096#ifdef YYCOVERAGE
8097 case SQLITE_TESTCTRL_PARSER_COVERAGE:
8098 if( nArg==2 ){
8099 sqlite3_test_control(testctrl, p->out);
8100 isOk = 3;
8101 }
8102#endif
drh2ce15c32017-07-11 13:34:40 +00008103 }
8104 }
drhef302e82017-11-15 19:14:08 +00008105 if( isOk==0 && iCtrl>=0 ){
8106 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
8107 rc = 1;
8108 }else if( isOk==1 ){
8109 raw_printf(p->out, "%d\n", rc2);
8110 }else if( isOk==2 ){
8111 raw_printf(p->out, "0x%08x\n", rc2);
8112 }
drh2ce15c32017-07-11 13:34:40 +00008113 }else
8114#endif /* !defined(SQLITE_UNTESTABLE) */
8115
8116 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
8117 open_db(p, 0);
8118 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
8119 }else
8120
8121 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
8122 if( nArg==2 ){
8123 enableTimer = booleanValue(azArg[1]);
8124 if( enableTimer && !HAS_TIMER ){
8125 raw_printf(stderr, "Error: timer not available on this system.\n");
8126 enableTimer = 0;
8127 }
8128 }else{
8129 raw_printf(stderr, "Usage: .timer on|off\n");
8130 rc = 1;
8131 }
8132 }else
8133
drh707821f2018-12-05 13:39:06 +00008134#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00008135 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh707821f2018-12-05 13:39:06 +00008136 int mType = 0;
8137 int jj;
drh2ce15c32017-07-11 13:34:40 +00008138 open_db(p, 0);
drh707821f2018-12-05 13:39:06 +00008139 for(jj=1; jj<nArg; jj++){
8140 const char *z = azArg[jj];
8141 if( z[0]=='-' ){
8142 if( optionMatch(z, "expanded") ){
8143 p->eTraceType = SHELL_TRACE_EXPANDED;
8144 }
8145#ifdef SQLITE_ENABLE_NORMALIZE
8146 else if( optionMatch(z, "normalized") ){
8147 p->eTraceType = SHELL_TRACE_NORMALIZED;
8148 }
8149#endif
8150 else if( optionMatch(z, "plain") ){
8151 p->eTraceType = SHELL_TRACE_PLAIN;
8152 }
8153 else if( optionMatch(z, "profile") ){
8154 mType |= SQLITE_TRACE_PROFILE;
8155 }
8156 else if( optionMatch(z, "row") ){
8157 mType |= SQLITE_TRACE_ROW;
8158 }
8159 else if( optionMatch(z, "stmt") ){
8160 mType |= SQLITE_TRACE_STMT;
8161 }
8162 else if( optionMatch(z, "close") ){
8163 mType |= SQLITE_TRACE_CLOSE;
8164 }
8165 else {
8166 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
8167 rc = 1;
8168 goto meta_command_exit;
8169 }
8170 }else{
8171 output_file_close(p->traceOut);
8172 p->traceOut = output_file_open(azArg[1], 0);
8173 }
drh2ce15c32017-07-11 13:34:40 +00008174 }
drh2ce15c32017-07-11 13:34:40 +00008175 if( p->traceOut==0 ){
8176 sqlite3_trace_v2(p->db, 0, 0, 0);
8177 }else{
drh707821f2018-12-05 13:39:06 +00008178 if( mType==0 ) mType = SQLITE_TRACE_STMT;
8179 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
drh2ce15c32017-07-11 13:34:40 +00008180 }
drh2ce15c32017-07-11 13:34:40 +00008181 }else
drh707821f2018-12-05 13:39:06 +00008182#endif /* !defined(SQLITE_OMIT_TRACE) */
drh2ce15c32017-07-11 13:34:40 +00008183
8184#if SQLITE_USER_AUTHENTICATION
8185 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
8186 if( nArg<2 ){
8187 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
8188 rc = 1;
8189 goto meta_command_exit;
8190 }
8191 open_db(p, 0);
8192 if( strcmp(azArg[1],"login")==0 ){
8193 if( nArg!=4 ){
8194 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
8195 rc = 1;
8196 goto meta_command_exit;
8197 }
drhaf2770f2018-01-05 14:55:43 +00008198 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00008199 if( rc ){
8200 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
8201 rc = 1;
8202 }
8203 }else if( strcmp(azArg[1],"add")==0 ){
8204 if( nArg!=5 ){
8205 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
8206 rc = 1;
8207 goto meta_command_exit;
8208 }
drhaf2770f2018-01-05 14:55:43 +00008209 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00008210 booleanValue(azArg[4]));
8211 if( rc ){
8212 raw_printf(stderr, "User-Add failed: %d\n", rc);
8213 rc = 1;
8214 }
8215 }else if( strcmp(azArg[1],"edit")==0 ){
8216 if( nArg!=5 ){
8217 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
8218 rc = 1;
8219 goto meta_command_exit;
8220 }
drhaf2770f2018-01-05 14:55:43 +00008221 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00008222 booleanValue(azArg[4]));
8223 if( rc ){
8224 raw_printf(stderr, "User-Edit failed: %d\n", rc);
8225 rc = 1;
8226 }
8227 }else if( strcmp(azArg[1],"delete")==0 ){
8228 if( nArg!=3 ){
8229 raw_printf(stderr, "Usage: .user delete USER\n");
8230 rc = 1;
8231 goto meta_command_exit;
8232 }
8233 rc = sqlite3_user_delete(p->db, azArg[2]);
8234 if( rc ){
8235 raw_printf(stderr, "User-Delete failed: %d\n", rc);
8236 rc = 1;
8237 }
8238 }else{
8239 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
8240 rc = 1;
8241 goto meta_command_exit;
8242 }
8243 }else
8244#endif /* SQLITE_USER_AUTHENTICATION */
8245
8246 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
8247 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
8248 sqlite3_libversion(), sqlite3_sourceid());
drh0ed2fd82018-01-16 20:05:27 +00008249#if SQLITE_HAVE_ZLIB
8250 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
8251#endif
8252#define CTIMEOPT_VAL_(opt) #opt
8253#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
8254#if defined(__clang__) && defined(__clang_major__)
8255 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
8256 CTIMEOPT_VAL(__clang_minor__) "."
8257 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
8258#elif defined(_MSC_VER)
8259 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
8260#elif defined(__GNUC__) && defined(__VERSION__)
8261 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
8262#endif
drh2ce15c32017-07-11 13:34:40 +00008263 }else
8264
8265 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
8266 const char *zDbName = nArg==2 ? azArg[1] : "main";
8267 sqlite3_vfs *pVfs = 0;
8268 if( p->db ){
8269 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
8270 if( pVfs ){
8271 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
8272 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
8273 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
8274 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
8275 }
8276 }
8277 }else
8278
8279 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
8280 sqlite3_vfs *pVfs;
8281 sqlite3_vfs *pCurrent = 0;
8282 if( p->db ){
8283 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
8284 }
8285 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
8286 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
8287 pVfs==pCurrent ? " <--- CURRENT" : "");
8288 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
8289 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
8290 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
8291 if( pVfs->pNext ){
8292 raw_printf(p->out, "-----------------------------------\n");
8293 }
8294 }
8295 }else
8296
8297 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
8298 const char *zDbName = nArg==2 ? azArg[1] : "main";
8299 char *zVfsName = 0;
8300 if( p->db ){
8301 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
8302 if( zVfsName ){
8303 utf8_printf(p->out, "%s\n", zVfsName);
8304 sqlite3_free(zVfsName);
8305 }
8306 }
8307 }else
8308
8309#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
8310 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
8311 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
8312 }else
8313#endif
8314
8315 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
8316 int j;
8317 assert( nArg<=ArraySize(azArg) );
8318 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
8319 p->colWidth[j-1] = (int)integerValue(azArg[j]);
8320 }
8321 }else
8322
8323 {
8324 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
8325 " \"%s\". Enter \".help\" for help\n", azArg[0]);
8326 rc = 1;
8327 }
8328
8329meta_command_exit:
8330 if( p->outCount ){
8331 p->outCount--;
8332 if( p->outCount==0 ) output_reset(p);
8333 }
8334 return rc;
8335}
8336
8337/*
8338** Return TRUE if a semicolon occurs anywhere in the first N characters
8339** of string z[].
8340*/
8341static int line_contains_semicolon(const char *z, int N){
8342 int i;
8343 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
8344 return 0;
8345}
8346
8347/*
8348** Test to see if a line consists entirely of whitespace.
8349*/
8350static int _all_whitespace(const char *z){
8351 for(; *z; z++){
8352 if( IsSpace(z[0]) ) continue;
8353 if( *z=='/' && z[1]=='*' ){
8354 z += 2;
8355 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
8356 if( *z==0 ) return 0;
8357 z++;
8358 continue;
8359 }
8360 if( *z=='-' && z[1]=='-' ){
8361 z += 2;
8362 while( *z && *z!='\n' ){ z++; }
8363 if( *z==0 ) return 1;
8364 continue;
8365 }
8366 return 0;
8367 }
8368 return 1;
8369}
8370
8371/*
8372** Return TRUE if the line typed in is an SQL command terminator other
8373** than a semi-colon. The SQL Server style "go" command is understood
8374** as is the Oracle "/".
8375*/
8376static int line_is_command_terminator(const char *zLine){
8377 while( IsSpace(zLine[0]) ){ zLine++; };
8378 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
8379 return 1; /* Oracle */
8380 }
8381 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
8382 && _all_whitespace(&zLine[2]) ){
8383 return 1; /* SQL Server */
8384 }
8385 return 0;
8386}
8387
8388/*
drh56f17742018-01-24 01:58:49 +00008389** We need a default sqlite3_complete() implementation to use in case
8390** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
8391** any arbitrary text is a complete SQL statement. This is not very
8392** user-friendly, but it does seem to work.
8393*/
8394#ifdef SQLITE_OMIT_COMPLETE
danc86b23b2018-11-16 14:36:42 +00008395#define sqlite3_complete(x) 1
drh56f17742018-01-24 01:58:49 +00008396#endif
8397
8398/*
drh2ce15c32017-07-11 13:34:40 +00008399** Return true if zSql is a complete SQL statement. Return false if it
8400** ends in the middle of a string literal or C-style comment.
8401*/
8402static int line_is_complete(char *zSql, int nSql){
8403 int rc;
8404 if( zSql==0 ) return 1;
8405 zSql[nSql] = ';';
8406 zSql[nSql+1] = 0;
8407 rc = sqlite3_complete(zSql);
8408 zSql[nSql] = 0;
8409 return rc;
8410}
8411
8412/*
drhfc29a862018-05-11 19:11:18 +00008413** Run a single line of SQL. Return the number of errors.
drh2ce15c32017-07-11 13:34:40 +00008414*/
8415static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
8416 int rc;
8417 char *zErrMsg = 0;
8418
8419 open_db(p, 0);
8420 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drhfc4eeef2019-02-05 19:48:46 +00008421 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
drh2ce15c32017-07-11 13:34:40 +00008422 BEGIN_TIMER;
drha10b9992018-03-09 15:24:33 +00008423 rc = shell_exec(p, zSql, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008424 END_TIMER;
8425 if( rc || zErrMsg ){
8426 char zPrefix[100];
8427 if( in!=0 || !stdin_is_interactive ){
8428 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
8429 "Error: near line %d:", startline);
8430 }else{
8431 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
8432 }
8433 if( zErrMsg!=0 ){
8434 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
8435 sqlite3_free(zErrMsg);
8436 zErrMsg = 0;
8437 }else{
8438 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
8439 }
8440 return 1;
8441 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
8442 raw_printf(p->out, "changes: %3d total_changes: %d\n",
8443 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
8444 }
8445 return 0;
8446}
8447
8448
8449/*
8450** Read input from *in and process it. If *in==0 then input
8451** is interactive - the user is typing it it. Otherwise, input
8452** is coming from a file or device. A prompt is issued and history
8453** is saved only if input is interactive. An interrupt signal will
8454** cause this routine to exit immediately, unless input is interactive.
8455**
8456** Return the number of errors.
8457*/
drh60379d42018-12-13 18:30:01 +00008458static int process_input(ShellState *p){
drh2ce15c32017-07-11 13:34:40 +00008459 char *zLine = 0; /* A single input line */
8460 char *zSql = 0; /* Accumulated SQL text */
8461 int nLine; /* Length of current line */
8462 int nSql = 0; /* Bytes of zSql[] used */
8463 int nAlloc = 0; /* Allocated zSql[] space */
8464 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
8465 int rc; /* Error code */
8466 int errCnt = 0; /* Number of errors seen */
drh2ce15c32017-07-11 13:34:40 +00008467 int startline = 0; /* Line number for start of current input */
8468
drh2c8ee022018-12-13 18:59:30 +00008469 p->lineno = 0;
drh60379d42018-12-13 18:30:01 +00008470 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
drh2ce15c32017-07-11 13:34:40 +00008471 fflush(p->out);
drh60379d42018-12-13 18:30:01 +00008472 zLine = one_input_line(p->in, zLine, nSql>0);
drh2ce15c32017-07-11 13:34:40 +00008473 if( zLine==0 ){
8474 /* End of input */
drh60379d42018-12-13 18:30:01 +00008475 if( p->in==0 && stdin_is_interactive ) printf("\n");
drh2ce15c32017-07-11 13:34:40 +00008476 break;
8477 }
8478 if( seenInterrupt ){
drh60379d42018-12-13 18:30:01 +00008479 if( p->in!=0 ) break;
drh2ce15c32017-07-11 13:34:40 +00008480 seenInterrupt = 0;
8481 }
drh2c8ee022018-12-13 18:59:30 +00008482 p->lineno++;
drh2ce15c32017-07-11 13:34:40 +00008483 if( nSql==0 && _all_whitespace(zLine) ){
8484 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
8485 continue;
8486 }
drh1615c372018-05-12 23:56:22 +00008487 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00008488 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh1615c372018-05-12 23:56:22 +00008489 if( zLine[0]=='.' ){
8490 rc = do_meta_command(zLine, p);
8491 if( rc==2 ){ /* exit requested */
8492 break;
8493 }else if( rc ){
8494 errCnt++;
8495 }
drh2ce15c32017-07-11 13:34:40 +00008496 }
8497 continue;
8498 }
8499 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
8500 memcpy(zLine,";",2);
8501 }
8502 nLine = strlen30(zLine);
8503 if( nSql+nLine+2>=nAlloc ){
8504 nAlloc = nSql+nLine+100;
8505 zSql = realloc(zSql, nAlloc);
drh4b5345c2018-04-24 13:07:40 +00008506 if( zSql==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008507 }
8508 nSqlPrior = nSql;
8509 if( nSql==0 ){
8510 int i;
8511 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
8512 assert( nAlloc>0 && zSql!=0 );
8513 memcpy(zSql, zLine+i, nLine+1-i);
drh2c8ee022018-12-13 18:59:30 +00008514 startline = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00008515 nSql = nLine-i;
8516 }else{
8517 zSql[nSql++] = '\n';
8518 memcpy(zSql+nSql, zLine, nLine+1);
8519 nSql += nLine;
8520 }
8521 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
8522 && sqlite3_complete(zSql) ){
drh60379d42018-12-13 18:30:01 +00008523 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00008524 nSql = 0;
8525 if( p->outCount ){
8526 output_reset(p);
8527 p->outCount = 0;
drh13c20932018-01-10 21:41:55 +00008528 }else{
8529 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00008530 }
8531 }else if( nSql && _all_whitespace(zSql) ){
8532 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
8533 nSql = 0;
8534 }
8535 }
8536 if( nSql && !_all_whitespace(zSql) ){
drh60379d42018-12-13 18:30:01 +00008537 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00008538 }
8539 free(zSql);
8540 free(zLine);
8541 return errCnt>0;
8542}
8543
8544/*
8545** Return a pathname which is the user's home directory. A
8546** 0 return indicates an error of some kind.
8547*/
8548static char *find_home_dir(int clearFlag){
8549 static char *home_dir = NULL;
8550 if( clearFlag ){
8551 free(home_dir);
8552 home_dir = 0;
8553 return 0;
8554 }
8555 if( home_dir ) return home_dir;
8556
8557#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
8558 && !defined(__RTP__) && !defined(_WRS_KERNEL)
8559 {
8560 struct passwd *pwent;
8561 uid_t uid = getuid();
8562 if( (pwent=getpwuid(uid)) != NULL) {
8563 home_dir = pwent->pw_dir;
8564 }
8565 }
8566#endif
8567
8568#if defined(_WIN32_WCE)
8569 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
8570 */
8571 home_dir = "/";
8572#else
8573
8574#if defined(_WIN32) || defined(WIN32)
8575 if (!home_dir) {
8576 home_dir = getenv("USERPROFILE");
8577 }
8578#endif
8579
8580 if (!home_dir) {
8581 home_dir = getenv("HOME");
8582 }
8583
8584#if defined(_WIN32) || defined(WIN32)
8585 if (!home_dir) {
8586 char *zDrive, *zPath;
8587 int n;
8588 zDrive = getenv("HOMEDRIVE");
8589 zPath = getenv("HOMEPATH");
8590 if( zDrive && zPath ){
8591 n = strlen30(zDrive) + strlen30(zPath) + 1;
8592 home_dir = malloc( n );
8593 if( home_dir==0 ) return 0;
8594 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
8595 return home_dir;
8596 }
8597 home_dir = "c:\\";
8598 }
8599#endif
8600
8601#endif /* !_WIN32_WCE */
8602
8603 if( home_dir ){
8604 int n = strlen30(home_dir) + 1;
8605 char *z = malloc( n );
8606 if( z ) memcpy(z, home_dir, n);
8607 home_dir = z;
8608 }
8609
8610 return home_dir;
8611}
8612
8613/*
8614** Read input from the file given by sqliterc_override. Or if that
8615** parameter is NULL, take input from ~/.sqliterc
8616**
8617** Returns the number of errors.
8618*/
8619static void process_sqliterc(
8620 ShellState *p, /* Configuration data */
8621 const char *sqliterc_override /* Name of config file. NULL to use default */
8622){
8623 char *home_dir = NULL;
8624 const char *sqliterc = sqliterc_override;
8625 char *zBuf = 0;
drh60379d42018-12-13 18:30:01 +00008626 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00008627 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00008628
8629 if (sqliterc == NULL) {
8630 home_dir = find_home_dir(0);
8631 if( home_dir==0 ){
8632 raw_printf(stderr, "-- warning: cannot find home directory;"
8633 " cannot read ~/.sqliterc\n");
8634 return;
8635 }
drh2ce15c32017-07-11 13:34:40 +00008636 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
8637 sqliterc = zBuf;
8638 }
drh60379d42018-12-13 18:30:01 +00008639 p->in = fopen(sqliterc,"rb");
8640 if( p->in ){
drh2ce15c32017-07-11 13:34:40 +00008641 if( stdin_is_interactive ){
8642 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
8643 }
drh60379d42018-12-13 18:30:01 +00008644 process_input(p);
8645 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00008646 }
drh60379d42018-12-13 18:30:01 +00008647 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00008648 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00008649 sqlite3_free(zBuf);
8650}
8651
8652/*
8653** Show available command line options
8654*/
8655static const char zOptions[] =
drhda57d962018-03-05 19:34:05 +00008656#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhad7fd5d2018-03-05 20:21:50 +00008657 " -A ARGS... run \".archive ARGS\" and exit\n"
drhda57d962018-03-05 19:34:05 +00008658#endif
drh3baed312018-03-08 18:14:41 +00008659 " -append append the database to the end of the file\n"
drh2ce15c32017-07-11 13:34:40 +00008660 " -ascii set output mode to 'ascii'\n"
8661 " -bail stop after hitting an error\n"
8662 " -batch force batch I/O\n"
8663 " -column set output mode to 'column'\n"
8664 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
8665 " -csv set output mode to 'csv'\n"
drh6ca64482019-01-22 16:06:20 +00008666#if defined(SQLITE_ENABLE_DESERIALIZE)
8667 " -deserialize open the database using sqlite3_deserialize()\n"
8668#endif
drh2ce15c32017-07-11 13:34:40 +00008669 " -echo print commands before execution\n"
8670 " -init FILENAME read/process named file\n"
8671 " -[no]header turn headers on or off\n"
8672#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8673 " -heap SIZE Size of heap for memsys3 or memsys5\n"
8674#endif
8675 " -help show this message\n"
8676 " -html set output mode to HTML\n"
8677 " -interactive force interactive I/O\n"
8678 " -line set output mode to 'line'\n"
8679 " -list set output mode to 'list'\n"
8680 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh6ca64482019-01-22 16:06:20 +00008681#if defined(SQLITE_ENABLE_DESERIALIZE)
8682 " -maxsize N maximum size for a --deserialize database\n"
8683#endif
drhaf482572019-02-04 19:52:39 +00008684 " -memtrace trace all memory allocations and deallocations\n"
drh2ce15c32017-07-11 13:34:40 +00008685 " -mmap N default mmap size set to N\n"
8686#ifdef SQLITE_ENABLE_MULTIPLEX
8687 " -multiplex enable the multiplexor VFS\n"
8688#endif
8689 " -newline SEP set output row separator. Default: '\\n'\n"
8690 " -nullvalue TEXT set text string for NULL values. Default ''\n"
8691 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
8692 " -quote set output mode to 'quote'\n"
drhee269a62018-02-14 23:27:43 +00008693 " -readonly open the database read-only\n"
drh2ce15c32017-07-11 13:34:40 +00008694 " -separator SEP set output column separator. Default: '|'\n"
drha90d84f2018-04-18 15:21:13 +00008695#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8696 " -sorterref SIZE sorter references threshold size\n"
8697#endif
drh2ce15c32017-07-11 13:34:40 +00008698 " -stats print memory stats before each finalize\n"
8699 " -version show SQLite version\n"
8700 " -vfs NAME use NAME as the default VFS\n"
8701#ifdef SQLITE_ENABLE_VFSTRACE
8702 " -vfstrace enable tracing of all VFS calls\n"
8703#endif
drh3baed312018-03-08 18:14:41 +00008704#ifdef SQLITE_HAVE_ZLIB
8705 " -zip open the file as a ZIP Archive\n"
8706#endif
drh2ce15c32017-07-11 13:34:40 +00008707;
8708static void usage(int showDetail){
8709 utf8_printf(stderr,
8710 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8711 "FILENAME is the name of an SQLite database. A new database is created\n"
8712 "if the file does not previously exist.\n", Argv0);
8713 if( showDetail ){
8714 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
8715 }else{
8716 raw_printf(stderr, "Use the -help option for additional information\n");
8717 }
8718 exit(1);
8719}
8720
8721/*
drhe7df8922018-04-18 10:44:58 +00008722** Internal check: Verify that the SQLite is uninitialized. Print a
8723** error message if it is initialized.
8724*/
8725static void verify_uninitialized(void){
8726 if( sqlite3_config(-1)==SQLITE_MISUSE ){
drh8e02a182018-05-30 07:24:41 +00008727 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
drhe7df8922018-04-18 10:44:58 +00008728 " initialization.\n");
8729 }
8730}
8731
8732/*
drh2ce15c32017-07-11 13:34:40 +00008733** Initialize the state information in data
8734*/
8735static void main_init(ShellState *data) {
8736 memset(data, 0, sizeof(*data));
8737 data->normalMode = data->cMode = data->mode = MODE_List;
8738 data->autoExplain = 1;
8739 memcpy(data->colSeparator,SEP_Column, 2);
8740 memcpy(data->rowSeparator,SEP_Row, 2);
8741 data->showHeader = 0;
8742 data->shellFlgs = SHFLG_Lookaside;
drhe7df8922018-04-18 10:44:58 +00008743 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00008744 sqlite3_config(SQLITE_CONFIG_URI, 1);
8745 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
8746 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
8747 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
8748 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
8749}
8750
8751/*
8752** Output text to the console in a font that attracts extra attention.
8753*/
8754#ifdef _WIN32
8755static void printBold(const char *zText){
8756 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
8757 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
8758 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
8759 SetConsoleTextAttribute(out,
8760 FOREGROUND_RED|FOREGROUND_INTENSITY
8761 );
8762 printf("%s", zText);
8763 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
8764}
8765#else
8766static void printBold(const char *zText){
8767 printf("\033[1m%s\033[0m", zText);
8768}
8769#endif
8770
8771/*
8772** Get the argument to an --option. Throw an error and die if no argument
8773** is available.
8774*/
8775static char *cmdline_option_value(int argc, char **argv, int i){
8776 if( i==argc ){
8777 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
8778 argv[0], argv[argc-1]);
8779 exit(1);
8780 }
8781 return argv[i];
8782}
8783
8784#ifndef SQLITE_SHELL_IS_UTF8
8785# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8786# define SQLITE_SHELL_IS_UTF8 (0)
8787# else
8788# define SQLITE_SHELL_IS_UTF8 (1)
8789# endif
8790#endif
8791
8792#if SQLITE_SHELL_IS_UTF8
8793int SQLITE_CDECL main(int argc, char **argv){
8794#else
8795int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
8796 char **argv;
8797#endif
8798 char *zErrMsg = 0;
8799 ShellState data;
8800 const char *zInitFile = 0;
8801 int i;
8802 int rc = 0;
8803 int warnInmemoryDb = 0;
8804 int readStdin = 1;
8805 int nCmd = 0;
8806 char **azCmd = 0;
dan16a47422018-04-18 09:16:11 +00008807 const char *zVfs = 0; /* Value of -vfs command-line option */
drh1f22f622018-05-17 13:29:14 +00008808#if !SQLITE_SHELL_IS_UTF8
8809 char **argvToFree = 0;
8810 int argcToFree = 0;
8811#endif
drh2ce15c32017-07-11 13:34:40 +00008812
8813 setBinaryMode(stdin, 0);
8814 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
8815 stdin_is_interactive = isatty(0);
8816 stdout_is_console = isatty(1);
8817
mistachkin1e8487d2018-07-22 06:25:35 +00008818#if !defined(_WIN32_WCE)
8819 if( getenv("SQLITE_DEBUG_BREAK") ){
8820 if( isatty(0) && isatty(2) ){
8821 fprintf(stderr,
8822 "attach debugger to process %d and press any key to continue.\n",
8823 GETPID());
8824 fgetc(stdin);
8825 }else{
8826#if defined(_WIN32) || defined(WIN32)
8827 DebugBreak();
8828#elif defined(SIGTRAP)
8829 raise(SIGTRAP);
8830#endif
8831 }
8832 }
8833#endif
8834
drh2ce15c32017-07-11 13:34:40 +00008835#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00008836 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00008837 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
8838 sqlite3_sourceid(), SQLITE_SOURCE_ID);
8839 exit(1);
8840 }
8841#endif
8842 main_init(&data);
drh501ea052018-02-15 01:03:37 +00008843
8844 /* On Windows, we must translate command-line arguments into UTF-8.
8845 ** The SQLite memory allocator subsystem has to be enabled in order to
8846 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
8847 ** subsequent sqlite3_config() calls will work. So copy all results into
8848 ** memory that does not come from the SQLite memory allocator.
8849 */
drh4b18c1d2018-02-04 20:33:13 +00008850#if !SQLITE_SHELL_IS_UTF8
drh501ea052018-02-15 01:03:37 +00008851 sqlite3_initialize();
drh1f22f622018-05-17 13:29:14 +00008852 argvToFree = malloc(sizeof(argv[0])*argc*2);
8853 argcToFree = argc;
8854 argv = argvToFree + argc;
drh4b5345c2018-04-24 13:07:40 +00008855 if( argv==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008856 for(i=0; i<argc; i++){
drh501ea052018-02-15 01:03:37 +00008857 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
8858 int n;
drh4b5345c2018-04-24 13:07:40 +00008859 if( z==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00008860 n = (int)strlen(z);
8861 argv[i] = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00008862 if( argv[i]==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00008863 memcpy(argv[i], z, n+1);
drh1f22f622018-05-17 13:29:14 +00008864 argvToFree[i] = argv[i];
drh501ea052018-02-15 01:03:37 +00008865 sqlite3_free(z);
drh2ce15c32017-07-11 13:34:40 +00008866 }
drh501ea052018-02-15 01:03:37 +00008867 sqlite3_shutdown();
drh2ce15c32017-07-11 13:34:40 +00008868#endif
drh501ea052018-02-15 01:03:37 +00008869
drh2ce15c32017-07-11 13:34:40 +00008870 assert( argc>=1 && argv && argv[0] );
8871 Argv0 = argv[0];
8872
8873 /* Make sure we have a valid signal handler early, before anything
8874 ** else is done.
8875 */
8876#ifdef SIGINT
8877 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00008878#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
8879 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00008880#endif
8881
8882#ifdef SQLITE_SHELL_DBNAME_PROC
8883 {
8884 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8885 ** of a C-function that will provide the name of the database file. Use
8886 ** this compile-time option to embed this shell program in larger
8887 ** applications. */
8888 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8889 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
8890 warnInmemoryDb = 0;
8891 }
8892#endif
8893
8894 /* Do an initial pass through the command-line argument to locate
8895 ** the name of the database file, the name of the initialization file,
8896 ** the size of the alternative malloc heap,
8897 ** and the first command to execute.
8898 */
drhe7df8922018-04-18 10:44:58 +00008899 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00008900 for(i=1; i<argc; i++){
8901 char *z;
8902 z = argv[i];
8903 if( z[0]!='-' ){
8904 if( data.zDbFilename==0 ){
8905 data.zDbFilename = z;
8906 }else{
8907 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8908 ** mean that nothing is read from stdin */
8909 readStdin = 0;
8910 nCmd++;
8911 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
drh4b5345c2018-04-24 13:07:40 +00008912 if( azCmd==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008913 azCmd[nCmd-1] = z;
8914 }
8915 }
8916 if( z[1]=='-' ) z++;
8917 if( strcmp(z,"-separator")==0
8918 || strcmp(z,"-nullvalue")==0
8919 || strcmp(z,"-newline")==0
8920 || strcmp(z,"-cmd")==0
8921 ){
8922 (void)cmdline_option_value(argc, argv, ++i);
8923 }else if( strcmp(z,"-init")==0 ){
8924 zInitFile = cmdline_option_value(argc, argv, ++i);
8925 }else if( strcmp(z,"-batch")==0 ){
8926 /* Need to check for batch mode here to so we can avoid printing
8927 ** informational messages (like from process_sqliterc) before
8928 ** we do the actual processing of arguments later in a second pass.
8929 */
8930 stdin_is_interactive = 0;
8931 }else if( strcmp(z,"-heap")==0 ){
8932#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8933 const char *zSize;
8934 sqlite3_int64 szHeap;
8935
8936 zSize = cmdline_option_value(argc, argv, ++i);
8937 szHeap = integerValue(zSize);
8938 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
8939 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
8940#else
8941 (void)cmdline_option_value(argc, argv, ++i);
8942#endif
drh2ce15c32017-07-11 13:34:40 +00008943 }else if( strcmp(z,"-pagecache")==0 ){
8944 int n, sz;
8945 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8946 if( sz>70000 ) sz = 70000;
8947 if( sz<0 ) sz = 0;
8948 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8949 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
8950 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
8951 data.shellFlgs |= SHFLG_Pagecache;
8952 }else if( strcmp(z,"-lookaside")==0 ){
8953 int n, sz;
8954 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
8955 if( sz<0 ) sz = 0;
8956 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
8957 if( n<0 ) n = 0;
8958 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
8959 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
8960#ifdef SQLITE_ENABLE_VFSTRACE
8961 }else if( strcmp(z,"-vfstrace")==0 ){
8962 extern int vfstrace_register(
8963 const char *zTraceName,
8964 const char *zOldVfsName,
8965 int (*xOut)(const char*,void*),
8966 void *pOutArg,
8967 int makeDefault
8968 );
8969 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
8970#endif
8971#ifdef SQLITE_ENABLE_MULTIPLEX
8972 }else if( strcmp(z,"-multiplex")==0 ){
8973 extern int sqlite3_multiple_initialize(const char*,int);
8974 sqlite3_multiplex_initialize(0, 1);
8975#endif
8976 }else if( strcmp(z,"-mmap")==0 ){
8977 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8978 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drha90d84f2018-04-18 15:21:13 +00008979#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8980 }else if( strcmp(z,"-sorterref")==0 ){
8981 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8982 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
8983#endif
drh2ce15c32017-07-11 13:34:40 +00008984 }else if( strcmp(z,"-vfs")==0 ){
dan16a47422018-04-18 09:16:11 +00008985 zVfs = cmdline_option_value(argc, argv, ++i);
drh3baed312018-03-08 18:14:41 +00008986#ifdef SQLITE_HAVE_ZLIB
drh8682e122018-01-07 20:38:10 +00008987 }else if( strcmp(z,"-zip")==0 ){
8988 data.openMode = SHELL_OPEN_ZIPFILE;
8989#endif
8990 }else if( strcmp(z,"-append")==0 ){
8991 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +00008992#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00008993 }else if( strcmp(z,"-deserialize")==0 ){
8994 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +00008995 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
8996 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +00008997#endif
drhee269a62018-02-14 23:27:43 +00008998 }else if( strcmp(z,"-readonly")==0 ){
8999 data.openMode = SHELL_OPEN_READONLY;
drhda57d962018-03-05 19:34:05 +00009000#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00009001 }else if( strncmp(z, "-A",2)==0 ){
drhda57d962018-03-05 19:34:05 +00009002 /* All remaining command-line arguments are passed to the ".archive"
9003 ** command, so ignore them */
9004 break;
9005#endif
drh50b910a2019-01-21 14:55:03 +00009006 }else if( strcmp(z, "-memtrace")==0 ){
9007 sqlite3MemTraceActivate(stderr);
drh2ce15c32017-07-11 13:34:40 +00009008 }
9009 }
drhe7df8922018-04-18 10:44:58 +00009010 verify_uninitialized();
9011
dan16a47422018-04-18 09:16:11 +00009012
drhd11b8f62018-04-25 13:27:07 +00009013#ifdef SQLITE_SHELL_INIT_PROC
9014 {
9015 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
9016 ** of a C-function that will perform initialization actions on SQLite that
9017 ** occur just before or after sqlite3_initialize(). Use this compile-time
9018 ** option to embed this shell program in larger applications. */
9019 extern void SQLITE_SHELL_INIT_PROC(void);
9020 SQLITE_SHELL_INIT_PROC();
9021 }
9022#else
dan16a47422018-04-18 09:16:11 +00009023 /* All the sqlite3_config() calls have now been made. So it is safe
9024 ** to call sqlite3_initialize() and process any command line -vfs option. */
9025 sqlite3_initialize();
drhd11b8f62018-04-25 13:27:07 +00009026#endif
9027
dan16a47422018-04-18 09:16:11 +00009028 if( zVfs ){
9029 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
9030 if( pVfs ){
9031 sqlite3_vfs_register(pVfs, 1);
9032 }else{
9033 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
9034 exit(1);
9035 }
9036 }
9037
drh2ce15c32017-07-11 13:34:40 +00009038 if( data.zDbFilename==0 ){
9039#ifndef SQLITE_OMIT_MEMORYDB
9040 data.zDbFilename = ":memory:";
9041 warnInmemoryDb = argc==1;
9042#else
9043 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
9044 return 1;
9045#endif
9046 }
9047 data.out = stdout;
drh8682e122018-01-07 20:38:10 +00009048 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +00009049
9050 /* Go ahead and open the database file if it already exists. If the
9051 ** file does not exist, delay opening it. This prevents empty database
9052 ** files from being created if a user mistypes the database name argument
9053 ** to the sqlite command-line tool.
9054 */
9055 if( access(data.zDbFilename, 0)==0 ){
9056 open_db(&data, 0);
9057 }
9058
9059 /* Process the initialization file if there is one. If no -init option
9060 ** is given on the command line, look for a file named ~/.sqliterc and
9061 ** try to process it.
9062 */
9063 process_sqliterc(&data,zInitFile);
9064
9065 /* Make a second pass through the command-line argument and set
9066 ** options. This second pass is delayed until after the initialization
9067 ** file is processed so that the command-line arguments will override
9068 ** settings in the initialization file.
9069 */
9070 for(i=1; i<argc; i++){
9071 char *z = argv[i];
9072 if( z[0]!='-' ) continue;
9073 if( z[1]=='-' ){ z++; }
9074 if( strcmp(z,"-init")==0 ){
9075 i++;
9076 }else if( strcmp(z,"-html")==0 ){
9077 data.mode = MODE_Html;
9078 }else if( strcmp(z,"-list")==0 ){
9079 data.mode = MODE_List;
9080 }else if( strcmp(z,"-quote")==0 ){
9081 data.mode = MODE_Quote;
9082 }else if( strcmp(z,"-line")==0 ){
9083 data.mode = MODE_Line;
9084 }else if( strcmp(z,"-column")==0 ){
9085 data.mode = MODE_Column;
9086 }else if( strcmp(z,"-csv")==0 ){
9087 data.mode = MODE_Csv;
9088 memcpy(data.colSeparator,",",2);
drh3baed312018-03-08 18:14:41 +00009089#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00009090 }else if( strcmp(z,"-zip")==0 ){
9091 data.openMode = SHELL_OPEN_ZIPFILE;
9092#endif
9093 }else if( strcmp(z,"-append")==0 ){
9094 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +00009095#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00009096 }else if( strcmp(z,"-deserialize")==0 ){
9097 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +00009098 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
9099 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +00009100#endif
drh4aafe592018-03-23 16:08:30 +00009101 }else if( strcmp(z,"-readonly")==0 ){
9102 data.openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +00009103 }else if( strcmp(z,"-ascii")==0 ){
9104 data.mode = MODE_Ascii;
9105 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
9106 SEP_Unit);
9107 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
9108 SEP_Record);
9109 }else if( strcmp(z,"-separator")==0 ){
9110 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
9111 "%s",cmdline_option_value(argc,argv,++i));
9112 }else if( strcmp(z,"-newline")==0 ){
9113 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
9114 "%s",cmdline_option_value(argc,argv,++i));
9115 }else if( strcmp(z,"-nullvalue")==0 ){
9116 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
9117 "%s",cmdline_option_value(argc,argv,++i));
9118 }else if( strcmp(z,"-header")==0 ){
9119 data.showHeader = 1;
9120 }else if( strcmp(z,"-noheader")==0 ){
9121 data.showHeader = 0;
9122 }else if( strcmp(z,"-echo")==0 ){
9123 ShellSetFlag(&data, SHFLG_Echo);
9124 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +00009125 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +00009126 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +00009127 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +00009128 }else if( strcmp(z,"-stats")==0 ){
9129 data.statsOn = 1;
9130 }else if( strcmp(z,"-scanstats")==0 ){
9131 data.scanstatsOn = 1;
9132 }else if( strcmp(z,"-backslash")==0 ){
9133 /* Undocumented command-line option: -backslash
9134 ** Causes C-style backslash escapes to be evaluated in SQL statements
9135 ** prior to sending the SQL into SQLite. Useful for injecting
9136 ** crazy bytes in the middle of SQL statements for testing and debugging.
9137 */
9138 ShellSetFlag(&data, SHFLG_Backslash);
9139 }else if( strcmp(z,"-bail")==0 ){
9140 bail_on_error = 1;
9141 }else if( strcmp(z,"-version")==0 ){
9142 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
9143 return 0;
9144 }else if( strcmp(z,"-interactive")==0 ){
9145 stdin_is_interactive = 1;
9146 }else if( strcmp(z,"-batch")==0 ){
9147 stdin_is_interactive = 0;
9148 }else if( strcmp(z,"-heap")==0 ){
9149 i++;
drh2ce15c32017-07-11 13:34:40 +00009150 }else if( strcmp(z,"-pagecache")==0 ){
9151 i+=2;
9152 }else if( strcmp(z,"-lookaside")==0 ){
9153 i+=2;
9154 }else if( strcmp(z,"-mmap")==0 ){
9155 i++;
drh50b910a2019-01-21 14:55:03 +00009156 }else if( strcmp(z,"-memtrace")==0 ){
9157 i++;
drha90d84f2018-04-18 15:21:13 +00009158#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9159 }else if( strcmp(z,"-sorterref")==0 ){
9160 i++;
9161#endif
drh2ce15c32017-07-11 13:34:40 +00009162 }else if( strcmp(z,"-vfs")==0 ){
9163 i++;
9164#ifdef SQLITE_ENABLE_VFSTRACE
9165 }else if( strcmp(z,"-vfstrace")==0 ){
9166 i++;
9167#endif
9168#ifdef SQLITE_ENABLE_MULTIPLEX
9169 }else if( strcmp(z,"-multiplex")==0 ){
9170 i++;
9171#endif
9172 }else if( strcmp(z,"-help")==0 ){
9173 usage(1);
9174 }else if( strcmp(z,"-cmd")==0 ){
9175 /* Run commands that follow -cmd first and separately from commands
9176 ** that simply appear on the command-line. This seems goofy. It would
9177 ** be better if all commands ran in the order that they appear. But
9178 ** we retain the goofy behavior for historical compatibility. */
9179 if( i==argc-1 ) break;
9180 z = cmdline_option_value(argc,argv,++i);
9181 if( z[0]=='.' ){
9182 rc = do_meta_command(z, &data);
9183 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
9184 }else{
9185 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00009186 rc = shell_exec(&data, z, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00009187 if( zErrMsg!=0 ){
9188 utf8_printf(stderr,"Error: %s\n", zErrMsg);
9189 if( bail_on_error ) return rc!=0 ? rc : 1;
9190 }else if( rc!=0 ){
9191 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
9192 if( bail_on_error ) return rc;
9193 }
9194 }
drhda57d962018-03-05 19:34:05 +00009195#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00009196 }else if( strncmp(z, "-A", 2)==0 ){
drhda57d962018-03-05 19:34:05 +00009197 if( nCmd>0 ){
9198 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
9199 " with \"%s\"\n", z);
9200 return 1;
9201 }
drhbe4ccb22018-05-17 20:04:24 +00009202 open_db(&data, OPEN_DB_ZIPFILE);
drh93b77312018-03-05 20:20:22 +00009203 if( z[2] ){
9204 argv[i] = &z[2];
drhd0f9cdc2018-05-17 14:09:06 +00009205 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
drh93b77312018-03-05 20:20:22 +00009206 }else{
drhd0f9cdc2018-05-17 14:09:06 +00009207 arDotCommand(&data, 1, argv+i, argc-i);
drh93b77312018-03-05 20:20:22 +00009208 }
drhda57d962018-03-05 19:34:05 +00009209 readStdin = 0;
9210 break;
9211#endif
drh2ce15c32017-07-11 13:34:40 +00009212 }else{
9213 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
9214 raw_printf(stderr,"Use -help for a list of options.\n");
9215 return 1;
9216 }
9217 data.cMode = data.mode;
9218 }
9219
9220 if( !readStdin ){
9221 /* Run all arguments that do not begin with '-' as if they were separate
9222 ** command-line inputs, except for the argToSkip argument which contains
9223 ** the database filename.
9224 */
9225 for(i=0; i<nCmd; i++){
9226 if( azCmd[i][0]=='.' ){
9227 rc = do_meta_command(azCmd[i], &data);
9228 if( rc ) return rc==2 ? 0 : rc;
9229 }else{
9230 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00009231 rc = shell_exec(&data, azCmd[i], &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00009232 if( zErrMsg!=0 ){
9233 utf8_printf(stderr,"Error: %s\n", zErrMsg);
9234 return rc!=0 ? rc : 1;
9235 }else if( rc!=0 ){
9236 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
9237 return rc;
9238 }
9239 }
9240 }
9241 free(azCmd);
9242 }else{
9243 /* Run commands received from standard input
9244 */
9245 if( stdin_is_interactive ){
9246 char *zHome;
drha9e4be32018-10-10 18:56:40 +00009247 char *zHistory;
drh2ce15c32017-07-11 13:34:40 +00009248 int nHistory;
9249 printf(
9250 "SQLite version %s %.19s\n" /*extra-version-info*/
9251 "Enter \".help\" for usage hints.\n",
9252 sqlite3_libversion(), sqlite3_sourceid()
9253 );
9254 if( warnInmemoryDb ){
9255 printf("Connected to a ");
9256 printBold("transient in-memory database");
9257 printf(".\nUse \".open FILENAME\" to reopen on a "
9258 "persistent database.\n");
9259 }
drha9e4be32018-10-10 18:56:40 +00009260 zHistory = getenv("SQLITE_HISTORY");
9261 if( zHistory ){
9262 zHistory = strdup(zHistory);
9263 }else if( (zHome = find_home_dir(0))!=0 ){
drh2ce15c32017-07-11 13:34:40 +00009264 nHistory = strlen30(zHome) + 20;
9265 if( (zHistory = malloc(nHistory))!=0 ){
9266 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
9267 }
9268 }
9269 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +00009270#if HAVE_READLINE || HAVE_EDITLINE
9271 rl_attempted_completion_function = readline_completion;
9272#elif HAVE_LINENOISE
9273 linenoiseSetCompletionCallback(linenoise_completion);
9274#endif
drh60379d42018-12-13 18:30:01 +00009275 data.in = 0;
9276 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +00009277 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +00009278 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +00009279 shell_write_history(zHistory);
9280 free(zHistory);
9281 }
9282 }else{
drh60379d42018-12-13 18:30:01 +00009283 data.in = stdin;
9284 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +00009285 }
9286 }
9287 set_table_name(&data, 0);
9288 if( data.db ){
9289 session_close_all(&data);
drh9e804032018-05-18 17:11:50 +00009290 close_db(data.db);
drh2ce15c32017-07-11 13:34:40 +00009291 }
9292 sqlite3_free(data.zFreeOnClose);
9293 find_home_dir(1);
drh536c3452018-01-11 00:38:39 +00009294 output_reset(&data);
9295 data.doXdgOpen = 0;
drh13c20932018-01-10 21:41:55 +00009296 clearTempFile(&data);
drh2ce15c32017-07-11 13:34:40 +00009297#if !SQLITE_SHELL_IS_UTF8
drh1f22f622018-05-17 13:29:14 +00009298 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
9299 free(argvToFree);
drh2ce15c32017-07-11 13:34:40 +00009300#endif
drh9e804032018-05-18 17:11:50 +00009301 /* Clear the global data structure so that valgrind will detect memory
9302 ** leaks */
9303 memset(&data, 0, sizeof(data));
drh2ce15c32017-07-11 13:34:40 +00009304 return rc;
9305}