blob: d8c57b481ecdb302221d51cfb598743e079b4753 [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
drh9cb02642019-02-28 20:10:52 +00002750/* Create the TEMP table used to store parameter bindings */
2751static void bind_table_init(ShellState *p){
drh346f4e22019-03-25 21:35:41 +00002752 int wrSchema = 0;
2753 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
2754 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
drh9cb02642019-02-28 20:10:52 +00002755 sqlite3_exec(p->db,
drh65c29fd2019-03-25 21:56:26 +00002756 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
drh9cb02642019-02-28 20:10:52 +00002757 " key TEXT PRIMARY KEY,\n"
2758 " value ANY\n"
2759 ") WITHOUT ROWID;",
2760 0, 0, 0);
drh346f4e22019-03-25 21:35:41 +00002761 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
drh9cb02642019-02-28 20:10:52 +00002762}
2763
drh8b738d02019-02-25 18:43:54 +00002764/*
2765** Bind parameters on a prepared statement.
2766**
2767** Parameter bindings are taken from a TEMP table of the form:
2768**
drh1cb02632019-03-25 22:05:22 +00002769** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
drh8b738d02019-02-25 18:43:54 +00002770** WITHOUT ROWID;
2771**
2772** No bindings occur if this table does not exist. The special character '$'
2773** is included in the table name to help prevent collisions with actual tables.
2774** The table must be in the TEMP schema.
2775*/
2776static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2777 int nVar;
2778 int i;
2779 int rc;
2780 sqlite3_stmt *pQ = 0;
2781
2782 nVar = sqlite3_bind_parameter_count(pStmt);
2783 if( nVar==0 ) return; /* Nothing to do */
drh65c29fd2019-03-25 21:56:26 +00002784 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
drh8b738d02019-02-25 18:43:54 +00002785 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2786 return; /* Parameter table does not exist */
2787 }
2788 rc = sqlite3_prepare_v2(pArg->db,
drh65c29fd2019-03-25 21:56:26 +00002789 "SELECT value FROM temp.sqlite_parameters"
drh8b738d02019-02-25 18:43:54 +00002790 " WHERE key=?1", -1, &pQ, 0);
2791 if( rc || pQ==0 ) return;
2792 for(i=1; i<=nVar; i++){
2793 char zNum[30];
2794 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2795 if( zVar==0 ){
2796 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2797 zVar = zNum;
2798 }
2799 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2800 if( sqlite3_step(pQ)==SQLITE_ROW ){
2801 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2802 }else{
2803 sqlite3_bind_null(pStmt, i);
2804 }
2805 sqlite3_reset(pQ);
2806 }
2807 sqlite3_finalize(pQ);
2808}
2809
drh2ce15c32017-07-11 13:34:40 +00002810/*
2811** Run a prepared statement
2812*/
2813static void exec_prepared_stmt(
2814 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002815 sqlite3_stmt *pStmt /* Statment to run */
drh2ce15c32017-07-11 13:34:40 +00002816){
2817 int rc;
2818
2819 /* perform the first step. this will tell us if we
2820 ** have a result set or not and how wide it is.
2821 */
2822 rc = sqlite3_step(pStmt);
2823 /* if we have a result set... */
2824 if( SQLITE_ROW == rc ){
drha10b9992018-03-09 15:24:33 +00002825 /* allocate space for col name ptr, value ptr, and type */
2826 int nCol = sqlite3_column_count(pStmt);
2827 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2828 if( !pData ){
2829 rc = SQLITE_NOMEM;
drh2ce15c32017-07-11 13:34:40 +00002830 }else{
drha10b9992018-03-09 15:24:33 +00002831 char **azCols = (char **)pData; /* Names of result columns */
2832 char **azVals = &azCols[nCol]; /* Results */
2833 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2834 int i, x;
2835 assert(sizeof(int) <= sizeof(char *));
2836 /* save off ptrs to column names */
2837 for(i=0; i<nCol; i++){
2838 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2839 }
drh2ce15c32017-07-11 13:34:40 +00002840 do{
drha10b9992018-03-09 15:24:33 +00002841 /* extract the data and data types */
2842 for(i=0; i<nCol; i++){
2843 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2844 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2845 azVals[i] = "";
2846 }else{
2847 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2848 }
2849 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2850 rc = SQLITE_NOMEM;
2851 break; /* from for */
2852 }
2853 } /* end for */
2854
2855 /* if data and types extracted successfully... */
2856 if( SQLITE_ROW == rc ){
2857 /* call the supplied callback with the result row data */
2858 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2859 rc = SQLITE_ABORT;
2860 }else{
2861 rc = sqlite3_step(pStmt);
2862 }
2863 }
2864 } while( SQLITE_ROW == rc );
2865 sqlite3_free(pData);
drh2ce15c32017-07-11 13:34:40 +00002866 }
2867 }
2868}
2869
dan6b046be2018-01-09 15:25:55 +00002870#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002871/*
dan43efc182017-12-19 17:42:13 +00002872** This function is called to process SQL if the previous shell command
2873** was ".expert". It passes the SQL in the second argument directly to
2874** the sqlite3expert object.
2875**
2876** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2877** code. In this case, (*pzErr) may be set to point to a buffer containing
2878** an English language error message. It is the responsibility of the
2879** caller to eventually free this buffer using sqlite3_free().
2880*/
2881static int expertHandleSQL(
2882 ShellState *pState,
2883 const char *zSql,
2884 char **pzErr
2885){
2886 assert( pState->expert.pExpert );
2887 assert( pzErr==0 || *pzErr==0 );
2888 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2889}
2890
2891/*
2892** This function is called either to silently clean up the object
2893** created by the ".expert" command (if bCancel==1), or to generate a
2894** report from it and then clean it up (if bCancel==0).
2895**
2896** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2897** code. In this case, (*pzErr) may be set to point to a buffer containing
2898** an English language error message. It is the responsibility of the
2899** caller to eventually free this buffer using sqlite3_free().
2900*/
2901static int expertFinish(
2902 ShellState *pState,
2903 int bCancel,
2904 char **pzErr
2905){
2906 int rc = SQLITE_OK;
2907 sqlite3expert *p = pState->expert.pExpert;
2908 assert( p );
2909 assert( bCancel || pzErr==0 || *pzErr==0 );
2910 if( bCancel==0 ){
2911 FILE *out = pState->out;
2912 int bVerbose = pState->expert.bVerbose;
2913
2914 rc = sqlite3_expert_analyze(p, pzErr);
2915 if( rc==SQLITE_OK ){
2916 int nQuery = sqlite3_expert_count(p);
2917 int i;
2918
2919 if( bVerbose ){
2920 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2921 raw_printf(out, "-- Candidates -----------------------------\n");
2922 raw_printf(out, "%s\n", zCand);
2923 }
2924 for(i=0; i<nQuery; i++){
2925 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2926 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2927 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2928 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2929 if( bVerbose ){
2930 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2931 raw_printf(out, "%s\n\n", zSql);
2932 }
2933 raw_printf(out, "%s\n", zIdx);
2934 raw_printf(out, "%s\n", zEQP);
2935 }
2936 }
2937 }
2938 sqlite3_expert_destroy(p);
2939 pState->expert.pExpert = 0;
2940 return rc;
2941}
2942
dan6b046be2018-01-09 15:25:55 +00002943/*
2944** Implementation of ".expert" dot command.
2945*/
2946static int expertDotCommand(
2947 ShellState *pState, /* Current shell tool state */
2948 char **azArg, /* Array of arguments passed to dot command */
2949 int nArg /* Number of entries in azArg[] */
2950){
2951 int rc = SQLITE_OK;
2952 char *zErr = 0;
2953 int i;
2954 int iSample = 0;
2955
2956 assert( pState->expert.pExpert==0 );
2957 memset(&pState->expert, 0, sizeof(ExpertInfo));
2958
2959 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2960 char *z = azArg[i];
2961 int n;
2962 if( z[0]=='-' && z[1]=='-' ) z++;
2963 n = strlen30(z);
2964 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2965 pState->expert.bVerbose = 1;
2966 }
2967 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2968 if( i==(nArg-1) ){
2969 raw_printf(stderr, "option requires an argument: %s\n", z);
2970 rc = SQLITE_ERROR;
2971 }else{
2972 iSample = (int)integerValue(azArg[++i]);
2973 if( iSample<0 || iSample>100 ){
2974 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2975 rc = SQLITE_ERROR;
2976 }
2977 }
2978 }
2979 else{
2980 raw_printf(stderr, "unknown option: %s\n", z);
2981 rc = SQLITE_ERROR;
2982 }
2983 }
2984
2985 if( rc==SQLITE_OK ){
2986 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2987 if( pState->expert.pExpert==0 ){
2988 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2989 rc = SQLITE_ERROR;
2990 }else{
2991 sqlite3_expert_config(
2992 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2993 );
2994 }
2995 }
2996
2997 return rc;
2998}
2999#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00003000
3001/*
drh2ce15c32017-07-11 13:34:40 +00003002** Execute a statement or set of statements. Print
3003** any result rows/columns depending on the current mode
3004** set via the supplied callback.
3005**
3006** This is very similar to SQLite's built-in sqlite3_exec()
3007** function except it takes a slightly different callback
3008** and callback data argument.
3009*/
3010static int shell_exec(
drh2ce15c32017-07-11 13:34:40 +00003011 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00003012 const char *zSql, /* SQL to be evaluated */
drh2ce15c32017-07-11 13:34:40 +00003013 char **pzErrMsg /* Error msg written here */
3014){
3015 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
3016 int rc = SQLITE_OK; /* Return Code */
3017 int rc2;
3018 const char *zLeftover; /* Tail of unprocessed SQL */
drha10b9992018-03-09 15:24:33 +00003019 sqlite3 *db = pArg->db;
drh2ce15c32017-07-11 13:34:40 +00003020
3021 if( pzErrMsg ){
3022 *pzErrMsg = NULL;
3023 }
3024
dan6b046be2018-01-09 15:25:55 +00003025#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00003026 if( pArg->expert.pExpert ){
3027 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3028 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3029 }
dan6b046be2018-01-09 15:25:55 +00003030#endif
dan43efc182017-12-19 17:42:13 +00003031
drh2ce15c32017-07-11 13:34:40 +00003032 while( zSql[0] && (SQLITE_OK == rc) ){
3033 static const char *zStmtSql;
3034 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3035 if( SQLITE_OK != rc ){
3036 if( pzErrMsg ){
3037 *pzErrMsg = save_err_msg(db);
3038 }
3039 }else{
3040 if( !pStmt ){
3041 /* this happens for a comment or white-space */
3042 zSql = zLeftover;
3043 while( IsSpace(zSql[0]) ) zSql++;
3044 continue;
3045 }
3046 zStmtSql = sqlite3_sql(pStmt);
3047 if( zStmtSql==0 ) zStmtSql = "";
3048 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3049
3050 /* save off the prepared statment handle and reset row count */
3051 if( pArg ){
3052 pArg->pStmt = pStmt;
3053 pArg->cnt = 0;
3054 }
3055
3056 /* echo the sql statement if echo on */
3057 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3058 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3059 }
3060
3061 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drh39c5c4a2019-03-06 14:53:27 +00003062 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
drh2ce15c32017-07-11 13:34:40 +00003063 sqlite3_stmt *pExplain;
3064 char *zEQP;
drhada70452017-12-21 21:02:27 +00003065 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00003066 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00003067 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3068 if( pArg->autoEQP>=AUTOEQP_trigger ){
3069 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3070 }
drh2ce15c32017-07-11 13:34:40 +00003071 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3072 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3073 if( rc==SQLITE_OK ){
3074 while( sqlite3_step(pExplain)==SQLITE_ROW ){
drh4b5345c2018-04-24 13:07:40 +00003075 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
drhe2ca99c2018-05-02 00:33:43 +00003076 int iEqpId = sqlite3_column_int(pExplain, 0);
3077 int iParentId = sqlite3_column_int(pExplain, 1);
drh4b5345c2018-04-24 13:07:40 +00003078 if( zEQPLine[0]=='-' ) eqp_render(pArg);
drhe2ca99c2018-05-02 00:33:43 +00003079 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
drh2ce15c32017-07-11 13:34:40 +00003080 }
drh4b5345c2018-04-24 13:07:40 +00003081 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003082 }
3083 sqlite3_finalize(pExplain);
3084 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00003085 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00003086 /* Also do an EXPLAIN for ".eqp full" mode */
3087 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3088 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3089 if( rc==SQLITE_OK ){
3090 pArg->cMode = MODE_Explain;
3091 explain_data_prepare(pArg, pExplain);
drha10b9992018-03-09 15:24:33 +00003092 exec_prepared_stmt(pArg, pExplain);
drh2ce15c32017-07-11 13:34:40 +00003093 explain_data_delete(pArg);
3094 }
3095 sqlite3_finalize(pExplain);
3096 sqlite3_free(zEQP);
3097 }
drh51efe092018-03-20 12:04:38 +00003098 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3099 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3100 /* Reprepare pStmt before reactiving trace modes */
3101 sqlite3_finalize(pStmt);
3102 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
drh3c49eaf2018-06-07 15:23:43 +00003103 if( pArg ) pArg->pStmt = pStmt;
drh51efe092018-03-20 12:04:38 +00003104 }
drh2ce15c32017-07-11 13:34:40 +00003105 restore_debug_trace_modes();
3106 }
3107
3108 if( pArg ){
3109 pArg->cMode = pArg->mode;
drh4b5345c2018-04-24 13:07:40 +00003110 if( pArg->autoExplain ){
drh39c5c4a2019-03-06 14:53:27 +00003111 if( sqlite3_stmt_isexplain(pStmt)==1 ){
drh4b5345c2018-04-24 13:07:40 +00003112 pArg->cMode = MODE_Explain;
3113 }
drh39c5c4a2019-03-06 14:53:27 +00003114 if( sqlite3_stmt_isexplain(pStmt)==2 ){
drh4b5345c2018-04-24 13:07:40 +00003115 pArg->cMode = MODE_EQP;
3116 }
drh2ce15c32017-07-11 13:34:40 +00003117 }
3118
3119 /* If the shell is currently in ".explain" mode, gather the extra
3120 ** data required to add indents to the output.*/
3121 if( pArg->cMode==MODE_Explain ){
3122 explain_data_prepare(pArg, pStmt);
3123 }
3124 }
3125
drh8b738d02019-02-25 18:43:54 +00003126 bind_prepared_stmt(pArg, pStmt);
drha10b9992018-03-09 15:24:33 +00003127 exec_prepared_stmt(pArg, pStmt);
drh2ce15c32017-07-11 13:34:40 +00003128 explain_data_delete(pArg);
drh4b5345c2018-04-24 13:07:40 +00003129 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003130
3131 /* print usage stats if stats on */
3132 if( pArg && pArg->statsOn ){
3133 display_stats(db, pArg, 0);
3134 }
3135
3136 /* print loop-counters if required */
3137 if( pArg && pArg->scanstatsOn ){
3138 display_scanstats(db, pArg);
3139 }
3140
3141 /* Finalize the statement just executed. If this fails, save a
3142 ** copy of the error message. Otherwise, set zSql to point to the
3143 ** next statement to execute. */
3144 rc2 = sqlite3_finalize(pStmt);
3145 if( rc!=SQLITE_NOMEM ) rc = rc2;
3146 if( rc==SQLITE_OK ){
3147 zSql = zLeftover;
3148 while( IsSpace(zSql[0]) ) zSql++;
3149 }else if( pzErrMsg ){
3150 *pzErrMsg = save_err_msg(db);
3151 }
3152
3153 /* clear saved stmt handle */
3154 if( pArg ){
3155 pArg->pStmt = NULL;
3156 }
3157 }
3158 } /* end while */
3159
3160 return rc;
3161}
3162
3163/*
3164** Release memory previously allocated by tableColumnList().
3165*/
3166static void freeColumnList(char **azCol){
3167 int i;
3168 for(i=1; azCol[i]; i++){
3169 sqlite3_free(azCol[i]);
3170 }
3171 /* azCol[0] is a static string */
3172 sqlite3_free(azCol);
3173}
3174
3175/*
3176** Return a list of pointers to strings which are the names of all
3177** columns in table zTab. The memory to hold the names is dynamically
3178** allocated and must be released by the caller using a subsequent call
3179** to freeColumnList().
3180**
3181** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3182** value that needs to be preserved, then azCol[0] is filled in with the
3183** name of the rowid column.
3184**
3185** The first regular column in the table is azCol[1]. The list is terminated
3186** by an entry with azCol[i]==0.
3187*/
3188static char **tableColumnList(ShellState *p, const char *zTab){
3189 char **azCol = 0;
3190 sqlite3_stmt *pStmt;
3191 char *zSql;
3192 int nCol = 0;
3193 int nAlloc = 0;
3194 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3195 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3196 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3197 int rc;
3198
3199 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3200 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3201 sqlite3_free(zSql);
3202 if( rc ) return 0;
3203 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3204 if( nCol>=nAlloc-2 ){
3205 nAlloc = nAlloc*2 + nCol + 10;
3206 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
drh4b5345c2018-04-24 13:07:40 +00003207 if( azCol==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00003208 }
3209 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3210 if( sqlite3_column_int(pStmt, 5) ){
3211 nPK++;
3212 if( nPK==1
3213 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3214 "INTEGER")==0
3215 ){
3216 isIPK = 1;
3217 }else{
3218 isIPK = 0;
3219 }
3220 }
3221 }
3222 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00003223 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003224 azCol[0] = 0;
3225 azCol[nCol+1] = 0;
3226
3227 /* The decision of whether or not a rowid really needs to be preserved
3228 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3229 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3230 ** rowids on tables where the rowid is inaccessible because there are other
3231 ** columns in the table named "rowid", "_rowid_", and "oid".
3232 */
3233 if( preserveRowid && isIPK ){
3234 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3235 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3236 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3237 ** ROWID aliases. To distinguish these cases, check to see if
3238 ** there is a "pk" entry in "PRAGMA index_list". There will be
3239 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3240 */
3241 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3242 " WHERE origin='pk'", zTab);
3243 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3244 sqlite3_free(zSql);
3245 if( rc ){
3246 freeColumnList(azCol);
3247 return 0;
3248 }
3249 rc = sqlite3_step(pStmt);
3250 sqlite3_finalize(pStmt);
3251 preserveRowid = rc==SQLITE_ROW;
3252 }
3253 if( preserveRowid ){
3254 /* Only preserve the rowid if we can find a name to use for the
3255 ** rowid */
3256 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3257 int i, j;
3258 for(j=0; j<3; j++){
3259 for(i=1; i<=nCol; i++){
3260 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3261 }
3262 if( i>nCol ){
3263 /* At this point, we know that azRowid[j] is not the name of any
3264 ** ordinary column in the table. Verify that azRowid[j] is a valid
3265 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3266 ** tables will fail this last check */
3267 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3268 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3269 break;
3270 }
3271 }
3272 }
3273 return azCol;
3274}
3275
3276/*
3277** Toggle the reverse_unordered_selects setting.
3278*/
3279static void toggleSelectOrder(sqlite3 *db){
3280 sqlite3_stmt *pStmt = 0;
3281 int iSetting = 0;
3282 char zStmt[100];
3283 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3284 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3285 iSetting = sqlite3_column_int(pStmt, 0);
3286 }
3287 sqlite3_finalize(pStmt);
3288 sqlite3_snprintf(sizeof(zStmt), zStmt,
3289 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3290 sqlite3_exec(db, zStmt, 0, 0, 0);
3291}
3292
3293/*
3294** This is a different callback routine used for dumping the database.
3295** Each row received by this callback consists of a table name,
3296** the table type ("index" or "table") and SQL to create the table.
3297** This routine should print text sufficient to recreate the table.
3298*/
3299static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3300 int rc;
3301 const char *zTable;
3302 const char *zType;
3303 const char *zSql;
3304 ShellState *p = (ShellState *)pArg;
3305
3306 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00003307 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003308 zTable = azArg[0];
3309 zType = azArg[1];
3310 zSql = azArg[2];
3311
3312 if( strcmp(zTable, "sqlite_sequence")==0 ){
3313 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3314 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3315 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3316 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3317 return 0;
3318 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3319 char *zIns;
3320 if( !p->writableSchema ){
3321 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3322 p->writableSchema = 1;
3323 }
3324 zIns = sqlite3_mprintf(
3325 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3326 "VALUES('table','%q','%q',0,'%q');",
3327 zTable, zTable, zSql);
3328 utf8_printf(p->out, "%s\n", zIns);
3329 sqlite3_free(zIns);
3330 return 0;
3331 }else{
3332 printSchemaLine(p->out, zSql, ";\n");
3333 }
3334
3335 if( strcmp(zType, "table")==0 ){
3336 ShellText sSelect;
3337 ShellText sTable;
3338 char **azCol;
3339 int i;
3340 char *savedDestTable;
3341 int savedMode;
3342
3343 azCol = tableColumnList(p, zTable);
3344 if( azCol==0 ){
3345 p->nErr++;
3346 return 0;
3347 }
3348
3349 /* Always quote the table name, even if it appears to be pure ascii,
3350 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3351 initText(&sTable);
3352 appendText(&sTable, zTable, quoteChar(zTable));
3353 /* If preserving the rowid, add a column list after the table name.
3354 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3355 ** instead of the usual "INSERT INTO tab VALUES(...)".
3356 */
3357 if( azCol[0] ){
3358 appendText(&sTable, "(", 0);
3359 appendText(&sTable, azCol[0], 0);
3360 for(i=1; azCol[i]; i++){
3361 appendText(&sTable, ",", 0);
3362 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3363 }
3364 appendText(&sTable, ")", 0);
3365 }
3366
3367 /* Build an appropriate SELECT statement */
3368 initText(&sSelect);
3369 appendText(&sSelect, "SELECT ", 0);
3370 if( azCol[0] ){
3371 appendText(&sSelect, azCol[0], 0);
3372 appendText(&sSelect, ",", 0);
3373 }
3374 for(i=1; azCol[i]; i++){
3375 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3376 if( azCol[i+1] ){
3377 appendText(&sSelect, ",", 0);
3378 }
3379 }
3380 freeColumnList(azCol);
3381 appendText(&sSelect, " FROM ", 0);
3382 appendText(&sSelect, zTable, quoteChar(zTable));
3383
3384 savedDestTable = p->zDestTable;
3385 savedMode = p->mode;
3386 p->zDestTable = sTable.z;
3387 p->mode = p->cMode = MODE_Insert;
drha10b9992018-03-09 15:24:33 +00003388 rc = shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003389 if( (rc&0xff)==SQLITE_CORRUPT ){
3390 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3391 toggleSelectOrder(p->db);
drha10b9992018-03-09 15:24:33 +00003392 shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003393 toggleSelectOrder(p->db);
3394 }
3395 p->zDestTable = savedDestTable;
3396 p->mode = savedMode;
3397 freeText(&sTable);
3398 freeText(&sSelect);
3399 if( rc ) p->nErr++;
3400 }
3401 return 0;
3402}
3403
3404/*
3405** Run zQuery. Use dump_callback() as the callback routine so that
3406** the contents of the query are output as SQL statements.
3407**
3408** If we get a SQLITE_CORRUPT error, rerun the query after appending
3409** "ORDER BY rowid DESC" to the end.
3410*/
3411static int run_schema_dump_query(
3412 ShellState *p,
3413 const char *zQuery
3414){
3415 int rc;
3416 char *zErr = 0;
3417 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3418 if( rc==SQLITE_CORRUPT ){
3419 char *zQ2;
3420 int len = strlen30(zQuery);
3421 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3422 if( zErr ){
3423 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3424 sqlite3_free(zErr);
3425 zErr = 0;
3426 }
3427 zQ2 = malloc( len+100 );
3428 if( zQ2==0 ) return rc;
3429 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3430 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3431 if( rc ){
3432 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3433 }else{
3434 rc = SQLITE_CORRUPT;
3435 }
3436 sqlite3_free(zErr);
3437 free(zQ2);
3438 }
3439 return rc;
3440}
3441
3442/*
drh98aa2ab2018-09-26 16:53:51 +00003443** Text of help messages.
3444**
3445** The help text for each individual command begins with a line that starts
3446** with ".". Subsequent lines are supplimental information.
3447**
3448** There must be two or more spaces between the end of the command and the
3449** start of the description of what that command does.
drh2ce15c32017-07-11 13:34:40 +00003450*/
drh98aa2ab2018-09-26 16:53:51 +00003451static const char *(azHelp[]) = {
drhe37c0e12018-01-06 19:19:50 +00003452#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drh98aa2ab2018-09-26 16:53:51 +00003453 ".archive ... Manage SQL archives",
3454 " Each command must have exactly one of the following options:",
3455 " -c, --create Create a new archive",
drhaf5a2e12019-03-25 15:09:19 +00003456 " -u, --update Add files or update files with changed mtime",
drhb17ea912019-03-25 14:24:19 +00003457 " -i, --insert Like -u but always add even if mtime unchanged",
drh98aa2ab2018-09-26 16:53:51 +00003458 " -t, --list List contents of archive",
3459 " -x, --extract Extract files from archive",
3460 " Optional arguments:",
3461 " -v, --verbose Print each filename as it is processed",
3462 " -f FILE, --file FILE Operate on archive FILE (default is current db)",
3463 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS",
3464 " -C DIR, --directory DIR Change to directory DIR to read/extract files",
3465 " -n, --dryrun Show the SQL that would have occurred",
3466 " Examples:",
3467 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar",
3468 " .ar -tf archive.sar # List members of archive.sar",
3469 " .ar -xvf archive.sar # Verbosely extract files from archive.sar",
3470 " See also:",
3471 " http://sqlite.org/cli.html#sqlar_archive_support",
drhe37c0e12018-01-06 19:19:50 +00003472#endif
drh2ce15c32017-07-11 13:34:40 +00003473#ifndef SQLITE_OMIT_AUTHORIZATION
drh98aa2ab2018-09-26 16:53:51 +00003474 ".auth ON|OFF Show authorizer callbacks",
drh2ce15c32017-07-11 13:34:40 +00003475#endif
drh98aa2ab2018-09-26 16:53:51 +00003476 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3477 " --append Use the appendvfs",
drha50bffb2018-12-08 01:09:14 +00003478 " --async Write to FILE without a journal and without fsync()",
drh98aa2ab2018-09-26 16:53:51 +00003479 ".bail on|off Stop after hitting an error. Default OFF",
3480 ".binary on|off Turn binary output on or off. Default OFF",
3481 ".cd DIRECTORY Change the working directory to DIRECTORY",
3482 ".changes on|off Show number of rows changed by SQL",
3483 ".check GLOB Fail if output since .testcase does not match",
3484 ".clone NEWDB Clone data into NEWDB from the existing database",
3485 ".databases List names and files of attached databases",
3486 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3487 ".dbinfo ?DB? Show status information about the database",
drheb7f2a02018-09-26 18:02:32 +00003488 ".dump ?TABLE? ... Render all database content as SQL",
3489 " Options:",
3490 " --preserve-rowids Include ROWID values in the output",
3491 " --newlines Allow unescaped newline characters in output",
3492 " TABLE is LIKE pattern for the tables to dump",
drh98aa2ab2018-09-26 16:53:51 +00003493 ".echo on|off Turn command echo on or off",
drhb4e50392019-01-26 15:40:04 +00003494 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
3495 " Other Modes:",
3496#ifdef SQLITE_DEBUG
3497 " test Show raw EXPLAIN QUERY PLAN output",
3498 " trace Like \"full\" but also enable \"PRAGMA vdbe_trace\"",
3499#endif
3500 " trigger Like \"full\" but also show trigger bytecode",
drh98aa2ab2018-09-26 16:53:51 +00003501 ".excel Display the output of next command in a spreadsheet",
drheb7f2a02018-09-26 18:02:32 +00003502 ".exit ?CODE? Exit this program with return-code CODE",
drh98aa2ab2018-09-26 16:53:51 +00003503 ".expert EXPERIMENTAL. Suggest indexes for specified queries",
drh2ce15c32017-07-11 13:34:40 +00003504/* Because explain mode comes on automatically now, the ".explain" mode
3505** is removed from the help screen. It is still supported for legacy, however */
drh98aa2ab2018-09-26 16:53:51 +00003506/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/
3507 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3508 ".headers on|off Turn display of headers on or off",
3509 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3510 ".import FILE TABLE Import data from FILE into TABLE",
drh2ce15c32017-07-11 13:34:40 +00003511#ifndef SQLITE_OMIT_TEST_CONTROL
drh98aa2ab2018-09-26 16:53:51 +00003512 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
drh2ce15c32017-07-11 13:34:40 +00003513#endif
drh98aa2ab2018-09-26 16:53:51 +00003514 ".indexes ?TABLE? Show names of indexes",
3515 " If TABLE is specified, only show indexes for",
3516 " tables matching TABLE using the LIKE operator.",
drh2ce15c32017-07-11 13:34:40 +00003517#ifdef SQLITE_ENABLE_IOTRACE
drh98aa2ab2018-09-26 16:53:51 +00003518 ".iotrace FILE Enable I/O diagnostic logging to FILE",
drh2ce15c32017-07-11 13:34:40 +00003519#endif
drh98aa2ab2018-09-26 16:53:51 +00003520 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3521 ".lint OPTIONS Report potential schema issues.",
3522 " Options:",
3523 " fkey-indexes Find missing foreign key indexes",
drh2ce15c32017-07-11 13:34:40 +00003524#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh98aa2ab2018-09-26 16:53:51 +00003525 ".load FILE ?ENTRY? Load an extension library",
drh2ce15c32017-07-11 13:34:40 +00003526#endif
drh98aa2ab2018-09-26 16:53:51 +00003527 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3528 ".mode MODE ?TABLE? Set output mode",
3529 " MODE is one of:",
3530 " ascii Columns/rows delimited by 0x1F and 0x1E",
3531 " csv Comma-separated values",
3532 " column Left-aligned columns. (See .width)",
3533 " html HTML <table> code",
3534 " insert SQL insert statements for TABLE",
3535 " line One value per line",
3536 " list Values delimited by \"|\"",
3537 " quote Escape answers as for SQL",
3538 " tabs Tab-separated values",
3539 " tcl TCL list elements",
3540 ".nullvalue STRING Use STRING in place of NULL values",
3541 ".once (-e|-x|FILE) Output for the next SQL command only to FILE",
3542 " If FILE begins with '|' then open as a pipe",
3543 " Other options:",
3544 " -e Invoke system text editor",
3545 " -x Open in a spreadsheet",
3546 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3547 " Options:",
drh60f34ae2018-10-30 13:19:49 +00003548 " --append Use appendvfs to append database to the end of FILE",
drha751f392018-10-30 15:31:22 +00003549#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00003550 " --deserialize Load into memory useing sqlite3_deserialize()",
drh33746482018-12-13 15:06:26 +00003551 " --hexdb Load the output of \"dbtotxt\" as an in-memory database",
drh6ca64482019-01-22 16:06:20 +00003552 " --maxsize N Maximum size for --hexdb or --deserialized database",
drha751f392018-10-30 15:31:22 +00003553#endif
drh60f34ae2018-10-30 13:19:49 +00003554 " --new Initialize FILE to an empty database",
3555 " --readonly Open FILE readonly",
3556 " --zip FILE is a ZIP archive",
drh98aa2ab2018-09-26 16:53:51 +00003557 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
3558 " If FILE begins with '|' then open it as a pipe.",
drh9cb02642019-02-28 20:10:52 +00003559 ".parameter CMD ... Manage SQL parameter bindings",
3560 " clear Erase all bindings",
3561 " init Initialize the TEMP table that holds bindings",
3562 " list List the current parameter bindings",
3563 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
3564 " PARAMETER should start with '$', ':', '@', or '?'",
3565 " unset PARAMETER Remove PARAMETER from the binding table",
drh98aa2ab2018-09-26 16:53:51 +00003566 ".print STRING... Print literal STRING",
drh569b1d92019-02-05 20:51:41 +00003567#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00003568 ".progress N Invoke progress handler after every N opcodes",
3569 " --limit N Interrupt after N progress callbacks",
3570 " --once Do no more than one progress interrupt",
3571 " --quiet|-q No output except at interrupts",
3572 " --reset Reset the count for each input and interrupt",
drh569b1d92019-02-05 20:51:41 +00003573#endif
drh98aa2ab2018-09-26 16:53:51 +00003574 ".prompt MAIN CONTINUE Replace the standard prompts",
3575 ".quit Exit this program",
3576 ".read FILE Read input from FILE",
3577 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
3578 ".save FILE Write in-memory database into FILE",
3579 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
3580 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
3581 " Options:",
3582 " --indent Try to pretty-print the schema",
drheb7f2a02018-09-26 18:02:32 +00003583 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
3584 " Options:",
3585 " --init Create a new SELFTEST table",
3586 " -v Verbose output",
drh98aa2ab2018-09-26 16:53:51 +00003587 ".separator COL ?ROW? Change the column and row separators",
drh2ce15c32017-07-11 13:34:40 +00003588#if defined(SQLITE_ENABLE_SESSION)
drheb7f2a02018-09-26 18:02:32 +00003589 ".session ?NAME? CMD ... Create or control sessions",
3590 " Subcommands:",
3591 " attach TABLE Attach TABLE",
3592 " changeset FILE Write a changeset into FILE",
3593 " close Close one session",
3594 " enable ?BOOLEAN? Set or query the enable bit",
3595 " filter GLOB... Reject tables matching GLOBs",
3596 " indirect ?BOOLEAN? Mark or query the indirect status",
3597 " isempty Query whether the session is empty",
3598 " list List currently open session names",
3599 " open DB NAME Open a new session on DB",
3600 " patchset FILE Write a patchset into FILE",
3601 " If ?NAME? is omitted, the first defined session is used.",
drh2ce15c32017-07-11 13:34:40 +00003602#endif
drheb7f2a02018-09-26 18:02:32 +00003603 ".sha3sum ... Compute a SHA3 hash of database content",
3604 " Options:",
3605 " --schema Also hash the sqlite_master table",
3606 " --sha3-224 Use the sha3-224 algorithm",
3607 " --sha3-256 Use the sha3-256 algorithm. This is the default.",
3608 " --sha3-384 Use the sha3-384 algorithm",
3609 " --sha3-512 Use the sha3-512 algorithm",
3610 " Any other argument is a LIKE pattern for tables to hash",
drh04a28c32018-01-31 01:38:44 +00003611#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003612 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003613#endif
drh98aa2ab2018-09-26 16:53:51 +00003614 ".show Show the current values for various settings",
3615 ".stats ?on|off? Show stats or turn stats on or off",
drh04a28c32018-01-31 01:38:44 +00003616#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003617 ".system CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003618#endif
drh98aa2ab2018-09-26 16:53:51 +00003619 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
3620 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
3621 ".timeout MS Try opening locked tables for MS milliseconds",
3622 ".timer on|off Turn SQL timer on or off",
drh707821f2018-12-05 13:39:06 +00003623#ifndef SQLITE_OMIT_TRACE
3624 ".trace ?OPTIONS? Output each SQL statement as it is run",
3625 " FILE Send output to FILE",
3626 " stdout Send output to stdout",
3627 " stderr Send output to stderr",
3628 " off Disable tracing",
3629 " --expanded Expand query parameters",
3630#ifdef SQLITE_ENABLE_NORMALIZE
3631 " --normalized Normal the SQL statements",
3632#endif
3633 " --plain Show SQL as it is input",
3634 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
3635 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
3636 " --row Trace each row (SQLITE_TRACE_ROW)",
3637 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
3638#endif /* SQLITE_OMIT_TRACE */
drh98aa2ab2018-09-26 16:53:51 +00003639 ".vfsinfo ?AUX? Information about the top-level VFS",
3640 ".vfslist List all available VFSes",
3641 ".vfsname ?AUX? Print the name of the VFS stack",
3642 ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
3643 " Negative values right-justify",
3644};
3645
3646/*
3647** Output help text.
3648**
3649** zPattern describes the set of commands for which help text is provided.
3650** If zPattern is NULL, then show all commands, but only give a one-line
3651** description of each.
3652**
3653** Return the number of matches.
3654*/
3655static int showHelp(FILE *out, const char *zPattern){
drhe93f8262018-10-11 16:53:37 +00003656 int i = 0;
3657 int j = 0;
drh98aa2ab2018-09-26 16:53:51 +00003658 int n = 0;
3659 char *zPat;
drh488cddf2018-10-06 14:38:17 +00003660 if( zPattern==0
3661 || zPattern[0]=='0'
3662 || strcmp(zPattern,"-a")==0
3663 || strcmp(zPattern,"-all")==0
3664 ){
drh98aa2ab2018-09-26 16:53:51 +00003665 /* Show all commands, but only one line per command */
drh488cddf2018-10-06 14:38:17 +00003666 if( zPattern==0 ) zPattern = "";
drh98aa2ab2018-09-26 16:53:51 +00003667 for(i=0; i<ArraySize(azHelp); i++){
drh488cddf2018-10-06 14:38:17 +00003668 if( azHelp[i][0]=='.' || zPattern[0] ){
drh98aa2ab2018-09-26 16:53:51 +00003669 utf8_printf(out, "%s\n", azHelp[i]);
3670 n++;
3671 }
3672 }
3673 }else{
3674 /* Look for commands that for which zPattern is an exact prefix */
3675 zPat = sqlite3_mprintf(".%s*", zPattern);
3676 for(i=0; i<ArraySize(azHelp); i++){
3677 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3678 utf8_printf(out, "%s\n", azHelp[i]);
drheb7f2a02018-09-26 18:02:32 +00003679 j = i+1;
drh98aa2ab2018-09-26 16:53:51 +00003680 n++;
3681 }
3682 }
3683 sqlite3_free(zPat);
drheb7f2a02018-09-26 18:02:32 +00003684 if( n ){
3685 if( n==1 ){
3686 /* when zPattern is a prefix of exactly one command, then include the
3687 ** details of that command, which should begin at offset j */
3688 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3689 utf8_printf(out, "%s\n", azHelp[j]);
3690 j++;
3691 }
3692 }
3693 return n;
3694 }
3695 /* Look for commands that contain zPattern anywhere. Show the complete
3696 ** text of all commands that match. */
drh98aa2ab2018-09-26 16:53:51 +00003697 zPat = sqlite3_mprintf("%%%s%%", zPattern);
3698 for(i=0; i<ArraySize(azHelp); i++){
3699 if( azHelp[i][0]=='.' ) j = i;
3700 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3701 utf8_printf(out, "%s\n", azHelp[j]);
3702 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3703 j++;
3704 utf8_printf(out, "%s\n", azHelp[j]);
3705 }
3706 i = j;
3707 n++;
3708 }
3709 }
3710 sqlite3_free(zPat);
3711 }
3712 return n;
3713}
drh2ce15c32017-07-11 13:34:40 +00003714
drh2ce15c32017-07-11 13:34:40 +00003715/* Forward reference */
drh60379d42018-12-13 18:30:01 +00003716static int process_input(ShellState *p);
drh2ce15c32017-07-11 13:34:40 +00003717
3718/*
3719** Read the content of file zName into memory obtained from sqlite3_malloc64()
3720** and return a pointer to the buffer. The caller is responsible for freeing
3721** the memory.
3722**
3723** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3724** read.
3725**
3726** For convenience, a nul-terminator byte is always appended to the data read
3727** from the file before the buffer is returned. This byte is not included in
3728** the final value of (*pnByte), if applicable.
3729**
3730** NULL is returned if any error is encountered. The final value of *pnByte
3731** is undefined in this case.
3732*/
3733static char *readFile(const char *zName, int *pnByte){
3734 FILE *in = fopen(zName, "rb");
3735 long nIn;
3736 size_t nRead;
3737 char *pBuf;
3738 if( in==0 ) return 0;
3739 fseek(in, 0, SEEK_END);
3740 nIn = ftell(in);
3741 rewind(in);
3742 pBuf = sqlite3_malloc64( nIn+1 );
drh1dbb1472018-10-11 10:37:24 +00003743 if( pBuf==0 ){ fclose(in); return 0; }
drh2ce15c32017-07-11 13:34:40 +00003744 nRead = fread(pBuf, nIn, 1, in);
3745 fclose(in);
3746 if( nRead!=1 ){
3747 sqlite3_free(pBuf);
3748 return 0;
3749 }
3750 pBuf[nIn] = 0;
3751 if( pnByte ) *pnByte = nIn;
3752 return pBuf;
3753}
3754
3755#if defined(SQLITE_ENABLE_SESSION)
3756/*
3757** Close a single OpenSession object and release all of its associated
3758** resources.
3759*/
3760static void session_close(OpenSession *pSession){
3761 int i;
3762 sqlite3session_delete(pSession->p);
3763 sqlite3_free(pSession->zName);
3764 for(i=0; i<pSession->nFilter; i++){
3765 sqlite3_free(pSession->azFilter[i]);
3766 }
3767 sqlite3_free(pSession->azFilter);
3768 memset(pSession, 0, sizeof(OpenSession));
3769}
3770#endif
3771
3772/*
3773** Close all OpenSession objects and release all associated resources.
3774*/
3775#if defined(SQLITE_ENABLE_SESSION)
3776static void session_close_all(ShellState *p){
3777 int i;
3778 for(i=0; i<p->nSession; i++){
3779 session_close(&p->aSession[i]);
3780 }
3781 p->nSession = 0;
3782}
3783#else
3784# define session_close_all(X)
3785#endif
3786
3787/*
3788** Implementation of the xFilter function for an open session. Omit
3789** any tables named by ".session filter" but let all other table through.
3790*/
3791#if defined(SQLITE_ENABLE_SESSION)
3792static int session_filter(void *pCtx, const char *zTab){
3793 OpenSession *pSession = (OpenSession*)pCtx;
3794 int i;
3795 for(i=0; i<pSession->nFilter; i++){
3796 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3797 }
3798 return 1;
3799}
3800#endif
3801
3802/*
drh1fa6d9f2018-01-06 21:46:01 +00003803** Try to deduce the type of file for zName based on its content. Return
3804** one of the SHELL_OPEN_* constants.
drh1bf208c2018-03-09 21:54:01 +00003805**
3806** If the file does not exist or is empty but its name looks like a ZIP
3807** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3808** Otherwise, assume an ordinary database regardless of the filename if
3809** the type cannot be determined from content.
drh1fa6d9f2018-01-06 21:46:01 +00003810*/
drhfc97c1c2018-05-14 00:41:12 +00003811int deduceDatabaseType(const char *zName, int dfltZip){
drh1fa6d9f2018-01-06 21:46:01 +00003812 FILE *f = fopen(zName, "rb");
3813 size_t n;
3814 int rc = SHELL_OPEN_UNSPEC;
3815 char zBuf[100];
drh1bf208c2018-03-09 21:54:01 +00003816 if( f==0 ){
drhbe4ccb22018-05-17 20:04:24 +00003817 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3818 return SHELL_OPEN_ZIPFILE;
3819 }else{
3820 return SHELL_OPEN_NORMAL;
3821 }
drh1bf208c2018-03-09 21:54:01 +00003822 }
drh2b3c4af2018-10-30 14:36:21 +00003823 n = fread(zBuf, 16, 1, f);
3824 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
3825 fclose(f);
3826 return SHELL_OPEN_NORMAL;
3827 }
drh1fa6d9f2018-01-06 21:46:01 +00003828 fseek(f, -25, SEEK_END);
3829 n = fread(zBuf, 25, 1, f);
3830 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3831 rc = SHELL_OPEN_APPENDVFS;
3832 }else{
3833 fseek(f, -22, SEEK_END);
3834 n = fread(zBuf, 22, 1, f);
3835 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3836 && zBuf[3]==0x06 ){
3837 rc = SHELL_OPEN_ZIPFILE;
drh1bf208c2018-03-09 21:54:01 +00003838 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
mistachkina3926f42018-05-14 12:23:04 +00003839 rc = SHELL_OPEN_ZIPFILE;
drh1fa6d9f2018-01-06 21:46:01 +00003840 }
3841 }
3842 fclose(f);
3843 return rc;
3844}
3845
drh33746482018-12-13 15:06:26 +00003846#ifdef SQLITE_ENABLE_DESERIALIZE
3847/*
3848** Reconstruct an in-memory database using the output from the "dbtotxt"
3849** program. Read content from the file in p->zDbFilename. If p->zDbFilename
3850** is 0, then read from standard input.
3851*/
3852static unsigned char *readHexDb(ShellState *p, int *pnData){
3853 unsigned char *a = 0;
drh2c8ee022018-12-13 18:59:30 +00003854 int nLine;
drh33746482018-12-13 15:06:26 +00003855 int n = 0;
3856 int pgsz = 0;
3857 int iOffset = 0;
3858 int j, k;
3859 int rc;
3860 FILE *in;
3861 unsigned char x[16];
drh2c8ee022018-12-13 18:59:30 +00003862 char zLine[1000];
drh33746482018-12-13 15:06:26 +00003863 if( p->zDbFilename ){
3864 in = fopen(p->zDbFilename, "r");
3865 if( in==0 ){
3866 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
3867 return 0;
3868 }
drh2c8ee022018-12-13 18:59:30 +00003869 nLine = 0;
drh33746482018-12-13 15:06:26 +00003870 }else{
drh60379d42018-12-13 18:30:01 +00003871 in = p->in;
drh2c8ee022018-12-13 18:59:30 +00003872 nLine = p->lineno;
drh33746482018-12-13 15:06:26 +00003873 }
3874 *pnData = 0;
drh2c8ee022018-12-13 18:59:30 +00003875 nLine++;
drh33746482018-12-13 15:06:26 +00003876 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
3877 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
3878 if( rc!=2 ) goto readHexDb_error;
3879 if( n<=0 ) goto readHexDb_error;
3880 a = sqlite3_malloc( n );
3881 if( a==0 ){
3882 utf8_printf(stderr, "Out of memory!\n");
3883 goto readHexDb_error;
3884 }
3885 memset(a, 0, n);
3886 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
3887 utf8_printf(stderr, "invalid pagesize\n");
3888 goto readHexDb_error;
3889 }
drh2c8ee022018-12-13 18:59:30 +00003890 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
drh33746482018-12-13 15:06:26 +00003891 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
3892 if( rc==2 ){
3893 iOffset = k;
3894 continue;
3895 }
3896 if( strncmp(zLine, "| end ", 6)==0 ){
3897 break;
3898 }
3899 rc = sscanf(zLine,"| %d: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx"
3900 " %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx",
3901 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
3902 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
3903 if( rc==17 ){
3904 k = iOffset+j;
drhf354e772018-12-13 22:58:52 +00003905 if( k+16<=n ){
3906 memcpy(a+k, x, 16);
drh33746482018-12-13 15:06:26 +00003907 }
drh33746482018-12-13 15:06:26 +00003908 }
3909 }
3910 *pnData = n;
drh2c8ee022018-12-13 18:59:30 +00003911 if( in!=p->in ){
3912 fclose(in);
3913 }else{
3914 p->lineno = nLine;
3915 }
drh33746482018-12-13 15:06:26 +00003916 return a;
3917
3918readHexDb_error:
3919 if( in!=stdin ){
3920 fclose(in);
3921 }else{
drh60379d42018-12-13 18:30:01 +00003922 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
drh2c8ee022018-12-13 18:59:30 +00003923 nLine++;
drh33746482018-12-13 15:06:26 +00003924 if(strncmp(zLine, "| end ", 6)==0 ) break;
3925 }
drh2c8ee022018-12-13 18:59:30 +00003926 p->lineno = nLine;
drh33746482018-12-13 15:06:26 +00003927 }
3928 sqlite3_free(a);
3929 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
3930 return 0;
3931}
3932#endif /* SQLITE_ENABLE_DESERIALIZE */
3933
drhbe4ccb22018-05-17 20:04:24 +00003934/* Flags for open_db().
3935**
3936** The default behavior of open_db() is to exit(1) if the database fails to
3937** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
3938** but still returns without calling exit.
3939**
3940** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
3941** ZIP archive if the file does not exist or is empty and its name matches
3942** the *.zip pattern.
3943*/
3944#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
3945#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
3946
drh1fa6d9f2018-01-06 21:46:01 +00003947/*
drh2ce15c32017-07-11 13:34:40 +00003948** Make sure the database is open. If it is not, then open it. If
3949** the database fails to open, print an error message and exit.
3950*/
drhbe4ccb22018-05-17 20:04:24 +00003951static void open_db(ShellState *p, int openFlags){
drh2ce15c32017-07-11 13:34:40 +00003952 if( p->db==0 ){
drhf2072d12018-05-11 15:10:11 +00003953 if( p->openMode==SHELL_OPEN_UNSPEC ){
3954 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
3955 p->openMode = SHELL_OPEN_NORMAL;
drhbe4ccb22018-05-17 20:04:24 +00003956 }else{
3957 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
3958 (openFlags & OPEN_DB_ZIPFILE)!=0);
drhf2072d12018-05-11 15:10:11 +00003959 }
drh1fa6d9f2018-01-06 21:46:01 +00003960 }
3961 switch( p->openMode ){
3962 case SHELL_OPEN_APPENDVFS: {
3963 sqlite3_open_v2(p->zDbFilename, &p->db,
3964 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
3965 break;
3966 }
drh33746482018-12-13 15:06:26 +00003967 case SHELL_OPEN_HEXDB:
drh60f34ae2018-10-30 13:19:49 +00003968 case SHELL_OPEN_DESERIALIZE: {
3969 sqlite3_open(0, &p->db);
3970 break;
3971 }
drh1fa6d9f2018-01-06 21:46:01 +00003972 case SHELL_OPEN_ZIPFILE: {
3973 sqlite3_open(":memory:", &p->db);
3974 break;
3975 }
drhee269a62018-02-14 23:27:43 +00003976 case SHELL_OPEN_READONLY: {
3977 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
3978 break;
3979 }
drh1fa6d9f2018-01-06 21:46:01 +00003980 case SHELL_OPEN_UNSPEC:
3981 case SHELL_OPEN_NORMAL: {
3982 sqlite3_open(p->zDbFilename, &p->db);
3983 break;
3984 }
3985 }
drh2ce15c32017-07-11 13:34:40 +00003986 globalDb = p->db;
3987 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3988 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3989 p->zDbFilename, sqlite3_errmsg(p->db));
drhf25cc4f2019-01-04 14:29:21 +00003990 if( openFlags & OPEN_DB_KEEPALIVE ){
3991 sqlite3_open(":memory:", &p->db);
3992 return;
3993 }
drh2ce15c32017-07-11 13:34:40 +00003994 exit(1);
3995 }
3996#ifndef SQLITE_OMIT_LOAD_EXTENSION
3997 sqlite3_enable_load_extension(p->db, 1);
3998#endif
3999 sqlite3_fileio_init(p->db, 0, 0);
4000 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00004001 sqlite3_completion_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00004002#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00004003 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00004004 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00004005#endif
drhceba7922018-01-01 21:28:25 +00004006 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00004007 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00004008 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4009 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00004010 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4011 shellPutsFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00004012#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00004013 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4014 editFunc, 0, 0);
4015 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4016 editFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00004017#endif
drh1fa6d9f2018-01-06 21:46:01 +00004018 if( p->openMode==SHELL_OPEN_ZIPFILE ){
4019 char *zSql = sqlite3_mprintf(
4020 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
4021 sqlite3_exec(p->db, zSql, 0, 0, 0);
4022 sqlite3_free(zSql);
drha751f392018-10-30 15:31:22 +00004023 }
4024#ifdef SQLITE_ENABLE_DESERIALIZE
drh33746482018-12-13 15:06:26 +00004025 else
4026 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
mistachkin99490932018-12-17 22:19:57 +00004027 int rc;
drh60f34ae2018-10-30 13:19:49 +00004028 int nData = 0;
drh33746482018-12-13 15:06:26 +00004029 unsigned char *aData;
4030 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4031 aData = (unsigned char*)readFile(p->zDbFilename, &nData);
4032 }else{
4033 aData = readHexDb(p, &nData);
4034 if( aData==0 ){
4035 utf8_printf(stderr, "Error in hexdb input\n");
4036 return;
4037 }
4038 }
mistachkin99490932018-12-17 22:19:57 +00004039 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
drh60f34ae2018-10-30 13:19:49 +00004040 SQLITE_DESERIALIZE_RESIZEABLE |
4041 SQLITE_DESERIALIZE_FREEONCLOSE);
4042 if( rc ){
4043 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4044 }
drh6ca64482019-01-22 16:06:20 +00004045 if( p->szMax>0 ){
4046 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4047 }
drh1fa6d9f2018-01-06 21:46:01 +00004048 }
drha751f392018-10-30 15:31:22 +00004049#endif
drh2ce15c32017-07-11 13:34:40 +00004050 }
4051}
4052
drh9e804032018-05-18 17:11:50 +00004053/*
4054** Attempt to close the databaes connection. Report errors.
4055*/
4056void close_db(sqlite3 *db){
4057 int rc = sqlite3_close(db);
4058 if( rc ){
4059 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4060 rc, sqlite3_errmsg(db));
4061 }
4062}
4063
drh56eb09b2017-07-11 13:59:07 +00004064#if HAVE_READLINE || HAVE_EDITLINE
4065/*
4066** Readline completion callbacks
4067*/
4068static char *readline_completion_generator(const char *text, int state){
4069 static sqlite3_stmt *pStmt = 0;
4070 char *zRet;
4071 if( state==0 ){
4072 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00004073 sqlite3_finalize(pStmt);
4074 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4075 " FROM completion(%Q) ORDER BY 1", text);
4076 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4077 sqlite3_free(zSql);
4078 }
4079 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00004080 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00004081 }else{
4082 sqlite3_finalize(pStmt);
4083 pStmt = 0;
4084 zRet = 0;
4085 }
4086 return zRet;
4087}
4088static char **readline_completion(const char *zText, int iStart, int iEnd){
4089 rl_attempted_completion_over = 1;
4090 return rl_completion_matches(zText, readline_completion_generator);
4091}
4092
4093#elif HAVE_LINENOISE
4094/*
4095** Linenoise completion callback
4096*/
4097static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00004098 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00004099 int i, iStart;
4100 sqlite3_stmt *pStmt = 0;
4101 char *zSql;
4102 char zBuf[1000];
4103
4104 if( nLine>sizeof(zBuf)-30 ) return;
drh1615c372018-05-12 23:56:22 +00004105 if( zLine[0]=='.' || zLine[0]=='#') return;
drh56eb09b2017-07-11 13:59:07 +00004106 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4107 if( i==nLine-1 ) return;
4108 iStart = i+1;
4109 memcpy(zBuf, zLine, iStart);
4110 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4111 " FROM completion(%Q,%Q) ORDER BY 1",
4112 &zLine[iStart], zLine);
4113 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4114 sqlite3_free(zSql);
4115 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4116 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4117 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4118 int nCompletion = sqlite3_column_bytes(pStmt, 0);
4119 if( iStart+nCompletion < sizeof(zBuf)-1 ){
4120 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4121 linenoiseAddCompletion(lc, zBuf);
4122 }
4123 }
4124 sqlite3_finalize(pStmt);
4125}
4126#endif
4127
drh2ce15c32017-07-11 13:34:40 +00004128/*
4129** Do C-language style dequoting.
4130**
4131** \a -> alarm
4132** \b -> backspace
4133** \t -> tab
4134** \n -> newline
4135** \v -> vertical tab
4136** \f -> form feed
4137** \r -> carriage return
4138** \s -> space
4139** \" -> "
4140** \' -> '
4141** \\ -> backslash
4142** \NNN -> ascii character NNN in octal
4143*/
4144static void resolve_backslashes(char *z){
4145 int i, j;
4146 char c;
4147 while( *z && *z!='\\' ) z++;
4148 for(i=j=0; (c = z[i])!=0; i++, j++){
4149 if( c=='\\' && z[i+1]!=0 ){
4150 c = z[++i];
4151 if( c=='a' ){
4152 c = '\a';
4153 }else if( c=='b' ){
4154 c = '\b';
4155 }else if( c=='t' ){
4156 c = '\t';
4157 }else if( c=='n' ){
4158 c = '\n';
4159 }else if( c=='v' ){
4160 c = '\v';
4161 }else if( c=='f' ){
4162 c = '\f';
4163 }else if( c=='r' ){
4164 c = '\r';
4165 }else if( c=='"' ){
4166 c = '"';
4167 }else if( c=='\'' ){
4168 c = '\'';
4169 }else if( c=='\\' ){
4170 c = '\\';
4171 }else if( c>='0' && c<='7' ){
4172 c -= '0';
4173 if( z[i+1]>='0' && z[i+1]<='7' ){
4174 i++;
4175 c = (c<<3) + z[i] - '0';
4176 if( z[i+1]>='0' && z[i+1]<='7' ){
4177 i++;
4178 c = (c<<3) + z[i] - '0';
4179 }
4180 }
4181 }
4182 }
4183 z[j] = c;
4184 }
4185 if( j<i ) z[j] = 0;
4186}
4187
4188/*
drh2ce15c32017-07-11 13:34:40 +00004189** Interpret zArg as either an integer or a boolean value. Return 1 or 0
4190** for TRUE and FALSE. Return the integer value if appropriate.
4191*/
4192static int booleanValue(const char *zArg){
4193 int i;
4194 if( zArg[0]=='0' && zArg[1]=='x' ){
4195 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4196 }else{
4197 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4198 }
4199 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4200 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4201 return 1;
4202 }
4203 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4204 return 0;
4205 }
4206 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4207 zArg);
4208 return 0;
4209}
4210
4211/*
4212** Set or clear a shell flag according to a boolean value.
4213*/
4214static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4215 if( booleanValue(zArg) ){
4216 ShellSetFlag(p, mFlag);
4217 }else{
4218 ShellClearFlag(p, mFlag);
4219 }
4220}
4221
4222/*
4223** Close an output file, assuming it is not stderr or stdout
4224*/
4225static void output_file_close(FILE *f){
4226 if( f && f!=stdout && f!=stderr ) fclose(f);
4227}
4228
4229/*
4230** Try to open an output file. The names "stdout" and "stderr" are
4231** recognized and do the right thing. NULL is returned if the output
4232** filename is "off".
4233*/
drha92a01a2018-01-10 22:15:37 +00004234static FILE *output_file_open(const char *zFile, int bTextMode){
drh2ce15c32017-07-11 13:34:40 +00004235 FILE *f;
4236 if( strcmp(zFile,"stdout")==0 ){
4237 f = stdout;
4238 }else if( strcmp(zFile, "stderr")==0 ){
4239 f = stderr;
4240 }else if( strcmp(zFile, "off")==0 ){
4241 f = 0;
4242 }else{
drha92a01a2018-01-10 22:15:37 +00004243 f = fopen(zFile, bTextMode ? "w" : "wb");
drh2ce15c32017-07-11 13:34:40 +00004244 if( f==0 ){
4245 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4246 }
4247 }
4248 return f;
4249}
4250
drh707821f2018-12-05 13:39:06 +00004251#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00004252/*
4253** A routine for handling output from sqlite3_trace().
4254*/
4255static int sql_trace_callback(
drh707821f2018-12-05 13:39:06 +00004256 unsigned mType, /* The trace type */
4257 void *pArg, /* The ShellState pointer */
4258 void *pP, /* Usually a pointer to sqlite_stmt */
4259 void *pX /* Auxiliary output */
drh2ce15c32017-07-11 13:34:40 +00004260){
drh707821f2018-12-05 13:39:06 +00004261 ShellState *p = (ShellState*)pArg;
4262 sqlite3_stmt *pStmt;
4263 const char *zSql;
4264 int nSql;
4265 if( p->traceOut==0 ) return 0;
4266 if( mType==SQLITE_TRACE_CLOSE ){
4267 utf8_printf(p->traceOut, "-- closing database connection\n");
4268 return 0;
4269 }
4270 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4271 zSql = (const char*)pX;
4272 }else{
4273 pStmt = (sqlite3_stmt*)pP;
4274 switch( p->eTraceType ){
4275 case SHELL_TRACE_EXPANDED: {
4276 zSql = sqlite3_expanded_sql(pStmt);
4277 break;
4278 }
4279#ifdef SQLITE_ENABLE_NORMALIZE
4280 case SHELL_TRACE_NORMALIZED: {
4281 zSql = sqlite3_normalized_sql(pStmt);
4282 break;
4283 }
4284#endif
4285 default: {
4286 zSql = sqlite3_sql(pStmt);
4287 break;
4288 }
4289 }
4290 }
4291 if( zSql==0 ) return 0;
4292 nSql = strlen30(zSql);
4293 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4294 switch( mType ){
4295 case SQLITE_TRACE_ROW:
4296 case SQLITE_TRACE_STMT: {
4297 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4298 break;
4299 }
4300 case SQLITE_TRACE_PROFILE: {
4301 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4302 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4303 break;
4304 }
drh2ce15c32017-07-11 13:34:40 +00004305 }
4306 return 0;
4307}
4308#endif
drh2ce15c32017-07-11 13:34:40 +00004309
4310/*
4311** A no-op routine that runs with the ".breakpoint" doc-command. This is
4312** a useful spot to set a debugger breakpoint.
4313*/
4314static void test_breakpoint(void){
4315 static int nCall = 0;
4316 nCall++;
4317}
4318
4319/*
4320** An object used to read a CSV and other files for import.
4321*/
4322typedef struct ImportCtx ImportCtx;
4323struct ImportCtx {
4324 const char *zFile; /* Name of the input file */
4325 FILE *in; /* Read the CSV text from this input stream */
4326 char *z; /* Accumulated text for a field */
4327 int n; /* Number of bytes in z */
4328 int nAlloc; /* Space allocated for z[] */
4329 int nLine; /* Current line number */
4330 int bNotFirst; /* True if one or more bytes already read */
4331 int cTerm; /* Character that terminated the most recent field */
4332 int cColSep; /* The column separator character. (Usually ",") */
4333 int cRowSep; /* The row separator character. (Usually "\n") */
4334};
4335
4336/* Append a single byte to z[] */
4337static void import_append_char(ImportCtx *p, int c){
4338 if( p->n+1>=p->nAlloc ){
4339 p->nAlloc += p->nAlloc + 100;
4340 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drh4b5345c2018-04-24 13:07:40 +00004341 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004342 }
4343 p->z[p->n++] = (char)c;
4344}
4345
4346/* Read a single field of CSV text. Compatible with rfc4180 and extended
4347** with the option of having a separator other than ",".
4348**
4349** + Input comes from p->in.
4350** + Store results in p->z of length p->n. Space to hold p->z comes
4351** from sqlite3_malloc64().
4352** + Use p->cSep as the column separator. The default is ",".
4353** + Use p->rSep as the row separator. The default is "\n".
4354** + Keep track of the line number in p->nLine.
4355** + Store the character that terminates the field in p->cTerm. Store
4356** EOF on end-of-file.
4357** + Report syntax errors on stderr
4358*/
4359static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4360 int c;
4361 int cSep = p->cColSep;
4362 int rSep = p->cRowSep;
4363 p->n = 0;
4364 c = fgetc(p->in);
4365 if( c==EOF || seenInterrupt ){
4366 p->cTerm = EOF;
4367 return 0;
4368 }
4369 if( c=='"' ){
4370 int pc, ppc;
4371 int startLine = p->nLine;
4372 int cQuote = c;
4373 pc = ppc = 0;
4374 while( 1 ){
4375 c = fgetc(p->in);
4376 if( c==rSep ) p->nLine++;
4377 if( c==cQuote ){
4378 if( pc==cQuote ){
4379 pc = 0;
4380 continue;
4381 }
4382 }
4383 if( (c==cSep && pc==cQuote)
4384 || (c==rSep && pc==cQuote)
4385 || (c==rSep && pc=='\r' && ppc==cQuote)
4386 || (c==EOF && pc==cQuote)
4387 ){
4388 do{ p->n--; }while( p->z[p->n]!=cQuote );
4389 p->cTerm = c;
4390 break;
4391 }
4392 if( pc==cQuote && c!='\r' ){
4393 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4394 p->zFile, p->nLine, cQuote);
4395 }
4396 if( c==EOF ){
4397 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4398 p->zFile, startLine, cQuote);
4399 p->cTerm = c;
4400 break;
4401 }
4402 import_append_char(p, c);
4403 ppc = pc;
4404 pc = c;
4405 }
4406 }else{
4407 /* If this is the first field being parsed and it begins with the
4408 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4409 if( (c&0xff)==0xef && p->bNotFirst==0 ){
4410 import_append_char(p, c);
4411 c = fgetc(p->in);
4412 if( (c&0xff)==0xbb ){
4413 import_append_char(p, c);
4414 c = fgetc(p->in);
4415 if( (c&0xff)==0xbf ){
4416 p->bNotFirst = 1;
4417 p->n = 0;
4418 return csv_read_one_field(p);
4419 }
4420 }
4421 }
4422 while( c!=EOF && c!=cSep && c!=rSep ){
4423 import_append_char(p, c);
4424 c = fgetc(p->in);
4425 }
4426 if( c==rSep ){
4427 p->nLine++;
4428 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4429 }
4430 p->cTerm = c;
4431 }
4432 if( p->z ) p->z[p->n] = 0;
4433 p->bNotFirst = 1;
4434 return p->z;
4435}
4436
4437/* Read a single field of ASCII delimited text.
4438**
4439** + Input comes from p->in.
4440** + Store results in p->z of length p->n. Space to hold p->z comes
4441** from sqlite3_malloc64().
4442** + Use p->cSep as the column separator. The default is "\x1F".
4443** + Use p->rSep as the row separator. The default is "\x1E".
4444** + Keep track of the row number in p->nLine.
4445** + Store the character that terminates the field in p->cTerm. Store
4446** EOF on end-of-file.
4447** + Report syntax errors on stderr
4448*/
4449static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4450 int c;
4451 int cSep = p->cColSep;
4452 int rSep = p->cRowSep;
4453 p->n = 0;
4454 c = fgetc(p->in);
4455 if( c==EOF || seenInterrupt ){
4456 p->cTerm = EOF;
4457 return 0;
4458 }
4459 while( c!=EOF && c!=cSep && c!=rSep ){
4460 import_append_char(p, c);
4461 c = fgetc(p->in);
4462 }
4463 if( c==rSep ){
4464 p->nLine++;
4465 }
4466 p->cTerm = c;
4467 if( p->z ) p->z[p->n] = 0;
4468 return p->z;
4469}
4470
4471/*
4472** Try to transfer data for table zTable. If an error is seen while
4473** moving forward, try to go backwards. The backwards movement won't
4474** work for WITHOUT ROWID tables.
4475*/
4476static void tryToCloneData(
4477 ShellState *p,
4478 sqlite3 *newDb,
4479 const char *zTable
4480){
4481 sqlite3_stmt *pQuery = 0;
4482 sqlite3_stmt *pInsert = 0;
4483 char *zQuery = 0;
4484 char *zInsert = 0;
4485 int rc;
4486 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00004487 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00004488 int k = 0;
4489 int cnt = 0;
4490 const int spinRate = 10000;
4491
4492 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4493 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4494 if( rc ){
4495 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4496 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4497 zQuery);
4498 goto end_data_xfer;
4499 }
4500 n = sqlite3_column_count(pQuery);
4501 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh4b5345c2018-04-24 13:07:40 +00004502 if( zInsert==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004503 sqlite3_snprintf(200+nTable,zInsert,
4504 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00004505 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00004506 for(j=1; j<n; j++){
4507 memcpy(zInsert+i, ",?", 2);
4508 i += 2;
4509 }
4510 memcpy(zInsert+i, ");", 3);
4511 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4512 if( rc ){
4513 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4514 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4515 zQuery);
4516 goto end_data_xfer;
4517 }
4518 for(k=0; k<2; k++){
4519 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4520 for(i=0; i<n; i++){
4521 switch( sqlite3_column_type(pQuery, i) ){
4522 case SQLITE_NULL: {
4523 sqlite3_bind_null(pInsert, i+1);
4524 break;
4525 }
4526 case SQLITE_INTEGER: {
4527 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4528 break;
4529 }
4530 case SQLITE_FLOAT: {
4531 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4532 break;
4533 }
4534 case SQLITE_TEXT: {
4535 sqlite3_bind_text(pInsert, i+1,
4536 (const char*)sqlite3_column_text(pQuery,i),
4537 -1, SQLITE_STATIC);
4538 break;
4539 }
4540 case SQLITE_BLOB: {
4541 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4542 sqlite3_column_bytes(pQuery,i),
4543 SQLITE_STATIC);
4544 break;
4545 }
4546 }
4547 } /* End for */
4548 rc = sqlite3_step(pInsert);
4549 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4550 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4551 sqlite3_errmsg(newDb));
4552 }
4553 sqlite3_reset(pInsert);
4554 cnt++;
4555 if( (cnt%spinRate)==0 ){
4556 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4557 fflush(stdout);
4558 }
4559 } /* End while */
4560 if( rc==SQLITE_DONE ) break;
4561 sqlite3_finalize(pQuery);
4562 sqlite3_free(zQuery);
4563 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4564 zTable);
4565 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4566 if( rc ){
4567 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4568 break;
4569 }
4570 } /* End for(k=0...) */
4571
4572end_data_xfer:
4573 sqlite3_finalize(pQuery);
4574 sqlite3_finalize(pInsert);
4575 sqlite3_free(zQuery);
4576 sqlite3_free(zInsert);
4577}
4578
4579
4580/*
4581** Try to transfer all rows of the schema that match zWhere. For
4582** each row, invoke xForEach() on the object defined by that row.
4583** If an error is encountered while moving forward through the
4584** sqlite_master table, try again moving backwards.
4585*/
4586static void tryToCloneSchema(
4587 ShellState *p,
4588 sqlite3 *newDb,
4589 const char *zWhere,
4590 void (*xForEach)(ShellState*,sqlite3*,const char*)
4591){
4592 sqlite3_stmt *pQuery = 0;
4593 char *zQuery = 0;
4594 int rc;
4595 const unsigned char *zName;
4596 const unsigned char *zSql;
4597 char *zErrMsg = 0;
4598
4599 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4600 " WHERE %s", zWhere);
4601 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4602 if( rc ){
4603 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4604 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4605 zQuery);
4606 goto end_schema_xfer;
4607 }
4608 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4609 zName = sqlite3_column_text(pQuery, 0);
4610 zSql = sqlite3_column_text(pQuery, 1);
4611 printf("%s... ", zName); fflush(stdout);
4612 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4613 if( zErrMsg ){
4614 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4615 sqlite3_free(zErrMsg);
4616 zErrMsg = 0;
4617 }
4618 if( xForEach ){
4619 xForEach(p, newDb, (const char*)zName);
4620 }
4621 printf("done\n");
4622 }
4623 if( rc!=SQLITE_DONE ){
4624 sqlite3_finalize(pQuery);
4625 sqlite3_free(zQuery);
4626 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4627 " WHERE %s ORDER BY rowid DESC", zWhere);
4628 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4629 if( rc ){
4630 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4631 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4632 zQuery);
4633 goto end_schema_xfer;
4634 }
4635 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4636 zName = sqlite3_column_text(pQuery, 0);
4637 zSql = sqlite3_column_text(pQuery, 1);
4638 printf("%s... ", zName); fflush(stdout);
4639 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4640 if( zErrMsg ){
4641 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4642 sqlite3_free(zErrMsg);
4643 zErrMsg = 0;
4644 }
4645 if( xForEach ){
4646 xForEach(p, newDb, (const char*)zName);
4647 }
4648 printf("done\n");
4649 }
4650 }
4651end_schema_xfer:
4652 sqlite3_finalize(pQuery);
4653 sqlite3_free(zQuery);
4654}
4655
4656/*
4657** Open a new database file named "zNewDb". Try to recover as much information
4658** as possible out of the main database (which might be corrupt) and write it
4659** into zNewDb.
4660*/
4661static void tryToClone(ShellState *p, const char *zNewDb){
4662 int rc;
4663 sqlite3 *newDb = 0;
4664 if( access(zNewDb,0)==0 ){
4665 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4666 return;
4667 }
4668 rc = sqlite3_open(zNewDb, &newDb);
4669 if( rc ){
4670 utf8_printf(stderr, "Cannot create output database: %s\n",
4671 sqlite3_errmsg(newDb));
4672 }else{
4673 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4674 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4675 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4676 tryToCloneSchema(p, newDb, "type!='table'", 0);
4677 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4678 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4679 }
drh9e804032018-05-18 17:11:50 +00004680 close_db(newDb);
drh2ce15c32017-07-11 13:34:40 +00004681}
4682
4683/*
drh13c20932018-01-10 21:41:55 +00004684** Change the output file back to stdout.
4685**
4686** If the p->doXdgOpen flag is set, that means the output was being
4687** redirected to a temporary file named by p->zTempFile. In that case,
4688** launch start/open/xdg-open on that temporary file.
drh2ce15c32017-07-11 13:34:40 +00004689*/
4690static void output_reset(ShellState *p){
4691 if( p->outfile[0]=='|' ){
4692#ifndef SQLITE_OMIT_POPEN
4693 pclose(p->out);
4694#endif
4695 }else{
4696 output_file_close(p->out);
drh04a28c32018-01-31 01:38:44 +00004697#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00004698 if( p->doXdgOpen ){
4699 const char *zXdgOpenCmd =
4700#if defined(_WIN32)
4701 "start";
4702#elif defined(__APPLE__)
4703 "open";
4704#else
4705 "xdg-open";
4706#endif
4707 char *zCmd;
4708 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
drha92a01a2018-01-10 22:15:37 +00004709 if( system(zCmd) ){
4710 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4711 }
drh13c20932018-01-10 21:41:55 +00004712 sqlite3_free(zCmd);
drh3c484e82018-01-10 22:27:21 +00004713 outputModePop(p);
drh13c20932018-01-10 21:41:55 +00004714 p->doXdgOpen = 0;
4715 }
drh04a28c32018-01-31 01:38:44 +00004716#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00004717 }
4718 p->outfile[0] = 0;
4719 p->out = stdout;
4720}
4721
4722/*
4723** Run an SQL command and return the single integer result.
4724*/
4725static int db_int(ShellState *p, const char *zSql){
4726 sqlite3_stmt *pStmt;
4727 int res = 0;
4728 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4729 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4730 res = sqlite3_column_int(pStmt,0);
4731 }
4732 sqlite3_finalize(pStmt);
4733 return res;
4734}
4735
4736/*
4737** Convert a 2-byte or 4-byte big-endian integer into a native integer
4738*/
4739static unsigned int get2byteInt(unsigned char *a){
4740 return (a[0]<<8) + a[1];
4741}
4742static unsigned int get4byteInt(unsigned char *a){
4743 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4744}
4745
4746/*
4747** Implementation of the ".info" command.
4748**
4749** Return 1 on error, 2 to exit, and 0 otherwise.
4750*/
4751static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4752 static const struct { const char *zName; int ofst; } aField[] = {
4753 { "file change counter:", 24 },
4754 { "database page count:", 28 },
4755 { "freelist page count:", 36 },
4756 { "schema cookie:", 40 },
4757 { "schema format:", 44 },
4758 { "default cache size:", 48 },
4759 { "autovacuum top root:", 52 },
4760 { "incremental vacuum:", 64 },
4761 { "text encoding:", 56 },
4762 { "user version:", 60 },
4763 { "application id:", 68 },
4764 { "software version:", 96 },
4765 };
4766 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4767 { "number of tables:",
4768 "SELECT count(*) FROM %s WHERE type='table'" },
4769 { "number of indexes:",
4770 "SELECT count(*) FROM %s WHERE type='index'" },
4771 { "number of triggers:",
4772 "SELECT count(*) FROM %s WHERE type='trigger'" },
4773 { "number of views:",
4774 "SELECT count(*) FROM %s WHERE type='view'" },
4775 { "schema size:",
4776 "SELECT total(length(sql)) FROM %s" },
4777 };
drh87c889c2019-03-20 18:22:51 +00004778 int i, rc;
drhea99a312018-07-18 19:09:07 +00004779 unsigned iDataVersion;
drh2ce15c32017-07-11 13:34:40 +00004780 char *zSchemaTab;
4781 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004782 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004783 unsigned char aHdr[100];
4784 open_db(p, 0);
4785 if( p->db==0 ) return 1;
drh87c889c2019-03-20 18:22:51 +00004786 rc = sqlite3_prepare_v2(p->db,
4787 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4788 -1, &pStmt, 0);
4789 if( rc ){
4790 if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){
4791 utf8_printf(stderr, "the \".dbinfo\" command requires the "
4792 "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n");
4793 }else{
4794 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
4795 }
4796 sqlite3_finalize(pStmt);
4797 return 1;
4798 }
drh512e6c32017-10-11 17:51:08 +00004799 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4800 if( sqlite3_step(pStmt)==SQLITE_ROW
4801 && sqlite3_column_bytes(pStmt,0)>100
4802 ){
4803 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4804 sqlite3_finalize(pStmt);
4805 }else{
drh2ce15c32017-07-11 13:34:40 +00004806 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004807 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004808 return 1;
4809 }
4810 i = get2byteInt(aHdr+16);
4811 if( i==1 ) i = 65536;
4812 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4813 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4814 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4815 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4816 for(i=0; i<ArraySize(aField); i++){
4817 int ofst = aField[i].ofst;
4818 unsigned int val = get4byteInt(aHdr + ofst);
4819 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4820 switch( ofst ){
4821 case 56: {
4822 if( val==1 ) raw_printf(p->out, " (utf8)");
4823 if( val==2 ) raw_printf(p->out, " (utf16le)");
4824 if( val==3 ) raw_printf(p->out, " (utf16be)");
4825 }
4826 }
4827 raw_printf(p->out, "\n");
4828 }
4829 if( zDb==0 ){
4830 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4831 }else if( strcmp(zDb,"temp")==0 ){
4832 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4833 }else{
4834 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4835 }
4836 for(i=0; i<ArraySize(aQuery); i++){
4837 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4838 int val = db_int(p, zSql);
4839 sqlite3_free(zSql);
4840 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4841 }
4842 sqlite3_free(zSchemaTab);
drhea99a312018-07-18 19:09:07 +00004843 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
4844 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
drh2ce15c32017-07-11 13:34:40 +00004845 return 0;
4846}
4847
4848/*
4849** Print the current sqlite3_errmsg() value to stderr and return 1.
4850*/
4851static int shellDatabaseError(sqlite3 *db){
4852 const char *zErr = sqlite3_errmsg(db);
4853 utf8_printf(stderr, "Error: %s\n", zErr);
4854 return 1;
4855}
4856
4857/*
drh2ce15c32017-07-11 13:34:40 +00004858** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4859** if they match and FALSE (0) if they do not match.
4860**
4861** Globbing rules:
4862**
4863** '*' Matches any sequence of zero or more characters.
4864**
4865** '?' Matches exactly one character.
4866**
4867** [...] Matches one character from the enclosed list of
4868** characters.
4869**
4870** [^...] Matches one character not in the enclosed list.
4871**
4872** '#' Matches any sequence of one or more digits with an
4873** optional + or - sign in front
4874**
4875** ' ' Any span of whitespace matches any other span of
4876** whitespace.
4877**
4878** Extra whitespace at the end of z[] is ignored.
4879*/
4880static int testcase_glob(const char *zGlob, const char *z){
4881 int c, c2;
4882 int invert;
4883 int seen;
4884
4885 while( (c = (*(zGlob++)))!=0 ){
4886 if( IsSpace(c) ){
4887 if( !IsSpace(*z) ) return 0;
4888 while( IsSpace(*zGlob) ) zGlob++;
4889 while( IsSpace(*z) ) z++;
4890 }else if( c=='*' ){
4891 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4892 if( c=='?' && (*(z++))==0 ) return 0;
4893 }
4894 if( c==0 ){
4895 return 1;
4896 }else if( c=='[' ){
4897 while( *z && testcase_glob(zGlob-1,z)==0 ){
4898 z++;
4899 }
4900 return (*z)!=0;
4901 }
4902 while( (c2 = (*(z++)))!=0 ){
4903 while( c2!=c ){
4904 c2 = *(z++);
4905 if( c2==0 ) return 0;
4906 }
4907 if( testcase_glob(zGlob,z) ) return 1;
4908 }
4909 return 0;
4910 }else if( c=='?' ){
4911 if( (*(z++))==0 ) return 0;
4912 }else if( c=='[' ){
4913 int prior_c = 0;
4914 seen = 0;
4915 invert = 0;
4916 c = *(z++);
4917 if( c==0 ) return 0;
4918 c2 = *(zGlob++);
4919 if( c2=='^' ){
4920 invert = 1;
4921 c2 = *(zGlob++);
4922 }
4923 if( c2==']' ){
4924 if( c==']' ) seen = 1;
4925 c2 = *(zGlob++);
4926 }
4927 while( c2 && c2!=']' ){
4928 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4929 c2 = *(zGlob++);
4930 if( c>=prior_c && c<=c2 ) seen = 1;
4931 prior_c = 0;
4932 }else{
4933 if( c==c2 ){
4934 seen = 1;
4935 }
4936 prior_c = c2;
4937 }
4938 c2 = *(zGlob++);
4939 }
4940 if( c2==0 || (seen ^ invert)==0 ) return 0;
4941 }else if( c=='#' ){
4942 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4943 if( !IsDigit(z[0]) ) return 0;
4944 z++;
4945 while( IsDigit(z[0]) ){ z++; }
4946 }else{
4947 if( c!=(*(z++)) ) return 0;
4948 }
4949 }
4950 while( IsSpace(*z) ){ z++; }
4951 return *z==0;
4952}
4953
4954
4955/*
4956** Compare the string as a command-line option with either one or two
4957** initial "-" characters.
4958*/
4959static int optionMatch(const char *zStr, const char *zOpt){
4960 if( zStr[0]!='-' ) return 0;
4961 zStr++;
4962 if( zStr[0]=='-' ) zStr++;
4963 return strcmp(zStr, zOpt)==0;
4964}
4965
4966/*
4967** Delete a file.
4968*/
4969int shellDeleteFile(const char *zFilename){
4970 int rc;
4971#ifdef _WIN32
4972 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4973 rc = _wunlink(z);
4974 sqlite3_free(z);
4975#else
4976 rc = unlink(zFilename);
4977#endif
4978 return rc;
4979}
4980
drh13c20932018-01-10 21:41:55 +00004981/*
4982** Try to delete the temporary file (if there is one) and free the
4983** memory used to hold the name of the temp file.
4984*/
4985static void clearTempFile(ShellState *p){
4986 if( p->zTempFile==0 ) return;
drh536c3452018-01-11 00:38:39 +00004987 if( p->doXdgOpen ) return;
drh13c20932018-01-10 21:41:55 +00004988 if( shellDeleteFile(p->zTempFile) ) return;
4989 sqlite3_free(p->zTempFile);
4990 p->zTempFile = 0;
4991}
4992
4993/*
4994** Create a new temp file name with the given suffix.
4995*/
4996static void newTempFile(ShellState *p, const char *zSuffix){
4997 clearTempFile(p);
4998 sqlite3_free(p->zTempFile);
4999 p->zTempFile = 0;
drh7f3bf8a2018-01-10 21:50:08 +00005000 if( p->db ){
5001 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5002 }
drh13c20932018-01-10 21:41:55 +00005003 if( p->zTempFile==0 ){
5004 sqlite3_uint64 r;
5005 sqlite3_randomness(sizeof(r), &r);
5006 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
5007 }else{
5008 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5009 }
5010 if( p->zTempFile==0 ){
5011 raw_printf(stderr, "out of memory\n");
5012 exit(1);
5013 }
5014}
5015
drh2ce15c32017-07-11 13:34:40 +00005016
5017/*
5018** The implementation of SQL scalar function fkey_collate_clause(), used
5019** by the ".lint fkey-indexes" command. This scalar function is always
5020** called with four arguments - the parent table name, the parent column name,
5021** the child table name and the child column name.
5022**
5023** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5024**
5025** If either of the named tables or columns do not exist, this function
5026** returns an empty string. An empty string is also returned if both tables
5027** and columns exist but have the same default collation sequence. Or,
5028** if both exist but the default collation sequences are different, this
5029** function returns the string " COLLATE <parent-collation>", where
5030** <parent-collation> is the default collation sequence of the parent column.
5031*/
5032static void shellFkeyCollateClause(
5033 sqlite3_context *pCtx,
5034 int nVal,
5035 sqlite3_value **apVal
5036){
5037 sqlite3 *db = sqlite3_context_db_handle(pCtx);
5038 const char *zParent;
5039 const char *zParentCol;
5040 const char *zParentSeq;
5041 const char *zChild;
5042 const char *zChildCol;
5043 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
5044 int rc;
5045
5046 assert( nVal==4 );
5047 zParent = (const char*)sqlite3_value_text(apVal[0]);
5048 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5049 zChild = (const char*)sqlite3_value_text(apVal[2]);
5050 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5051
5052 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5053 rc = sqlite3_table_column_metadata(
5054 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5055 );
5056 if( rc==SQLITE_OK ){
5057 rc = sqlite3_table_column_metadata(
5058 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5059 );
5060 }
5061
5062 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5063 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5064 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5065 sqlite3_free(z);
5066 }
5067}
5068
5069
5070/*
5071** The implementation of dot-command ".lint fkey-indexes".
5072*/
5073static int lintFkeyIndexes(
5074 ShellState *pState, /* Current shell tool state */
5075 char **azArg, /* Array of arguments passed to dot command */
5076 int nArg /* Number of entries in azArg[] */
5077){
5078 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
5079 FILE *out = pState->out; /* Stream to write non-error output to */
5080 int bVerbose = 0; /* If -verbose is present */
5081 int bGroupByParent = 0; /* If -groupbyparent is present */
5082 int i; /* To iterate through azArg[] */
5083 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
5084 int rc; /* Return code */
5085 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
5086
5087 /*
5088 ** This SELECT statement returns one row for each foreign key constraint
5089 ** in the schema of the main database. The column values are:
5090 **
5091 ** 0. The text of an SQL statement similar to:
5092 **
danf9679312017-12-01 18:40:18 +00005093 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00005094 **
danf9679312017-12-01 18:40:18 +00005095 ** This SELECT is similar to the one that the foreign keys implementation
5096 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00005097 ** be used to optimize this query, then it can also be used by the FK
5098 ** implementation to optimize DELETE or UPDATE statements on the parent
5099 ** table.
5100 **
5101 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5102 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5103 ** contains an index that can be used to optimize the query.
5104 **
5105 ** 2. Human readable text that describes the child table and columns. e.g.
5106 **
5107 ** "child_table(child_key1, child_key2)"
5108 **
5109 ** 3. Human readable text that describes the parent table and columns. e.g.
5110 **
5111 ** "parent_table(parent_key1, parent_key2)"
5112 **
5113 ** 4. A full CREATE INDEX statement for an index that could be used to
5114 ** optimize DELETE or UPDATE statements on the parent table. e.g.
5115 **
5116 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
5117 **
5118 ** 5. The name of the parent table.
5119 **
5120 ** These six values are used by the C logic below to generate the report.
5121 */
5122 const char *zSql =
5123 "SELECT "
danf9679312017-12-01 18:40:18 +00005124 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00005125 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5126 " || fkey_collate_clause("
5127 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5128 ", "
5129 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
5130 " || group_concat('*=?', ' AND ') || ')'"
5131 ", "
5132 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
5133 ", "
5134 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5135 ", "
5136 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5137 " || ' ON ' || quote(s.name) || '('"
5138 " || group_concat(quote(f.[from]) ||"
5139 " fkey_collate_clause("
5140 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5141 " || ');'"
5142 ", "
5143 " f.[table] "
5144 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
5145 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5146 "GROUP BY s.name, f.id "
5147 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5148 ;
5149 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
5150
5151 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00005152 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00005153 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5154 bVerbose = 1;
5155 }
5156 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5157 bGroupByParent = 1;
5158 zIndent = " ";
5159 }
5160 else{
5161 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5162 azArg[0], azArg[1]
5163 );
5164 return SQLITE_ERROR;
5165 }
5166 }
5167
5168 /* Register the fkey_collate_clause() SQL function */
5169 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5170 0, shellFkeyCollateClause, 0, 0
5171 );
5172
5173
5174 if( rc==SQLITE_OK ){
5175 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5176 }
5177 if( rc==SQLITE_OK ){
5178 sqlite3_bind_int(pSql, 1, bGroupByParent);
5179 }
5180
5181 if( rc==SQLITE_OK ){
5182 int rc2;
5183 char *zPrev = 0;
5184 while( SQLITE_ROW==sqlite3_step(pSql) ){
5185 int res = -1;
5186 sqlite3_stmt *pExplain = 0;
5187 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5188 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5189 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5190 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5191 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5192 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5193
5194 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5195 if( rc!=SQLITE_OK ) break;
5196 if( SQLITE_ROW==sqlite3_step(pExplain) ){
5197 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5198 res = (
5199 0==sqlite3_strglob(zGlob, zPlan)
5200 || 0==sqlite3_strglob(zGlobIPK, zPlan)
5201 );
5202 }
5203 rc = sqlite3_finalize(pExplain);
5204 if( rc!=SQLITE_OK ) break;
5205
5206 if( res<0 ){
5207 raw_printf(stderr, "Error: internal error");
5208 break;
5209 }else{
5210 if( bGroupByParent
5211 && (bVerbose || res==0)
5212 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5213 ){
5214 raw_printf(out, "-- Parent table %s\n", zParent);
5215 sqlite3_free(zPrev);
5216 zPrev = sqlite3_mprintf("%s", zParent);
5217 }
5218
5219 if( res==0 ){
5220 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5221 }else if( bVerbose ){
5222 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5223 zIndent, zFrom, zTarget
5224 );
5225 }
5226 }
5227 }
5228 sqlite3_free(zPrev);
5229
5230 if( rc!=SQLITE_OK ){
5231 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5232 }
5233
5234 rc2 = sqlite3_finalize(pSql);
5235 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5236 rc = rc2;
5237 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5238 }
5239 }else{
5240 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5241 }
5242
5243 return rc;
5244}
5245
5246/*
5247** Implementation of ".lint" dot command.
5248*/
5249static int lintDotCommand(
5250 ShellState *pState, /* Current shell tool state */
5251 char **azArg, /* Array of arguments passed to dot command */
5252 int nArg /* Number of entries in azArg[] */
5253){
5254 int n;
drhaf2770f2018-01-05 14:55:43 +00005255 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00005256 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5257 return lintFkeyIndexes(pState, azArg, nArg);
5258
5259 usage:
5260 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5261 raw_printf(stderr, "Where sub-commands are:\n");
5262 raw_printf(stderr, " fkey-indexes\n");
5263 return SQLITE_ERROR;
5264}
5265
drhe37c0e12018-01-06 19:19:50 +00005266#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5267/*********************************************************************************
5268** The ".archive" or ".ar" command.
5269*/
danfd0245d2017-12-07 15:44:29 +00005270static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00005271 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00005272 int *pRc,
5273 const char *zSql,
5274 sqlite3_stmt **ppStmt
5275){
5276 *ppStmt = 0;
5277 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00005278 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00005279 if( rc!=SQLITE_OK ){
5280 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00005281 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00005282 );
5283 *pRc = rc;
5284 }
5285 }
5286}
5287
danac15e2d2017-12-14 19:15:07 +00005288static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00005289 sqlite3 *db,
5290 int *pRc,
danac15e2d2017-12-14 19:15:07 +00005291 sqlite3_stmt **ppStmt,
5292 const char *zFmt,
5293 ...
dan3f67ddf2017-12-13 20:04:53 +00005294){
danac15e2d2017-12-14 19:15:07 +00005295 *ppStmt = 0;
5296 if( *pRc==SQLITE_OK ){
5297 va_list ap;
5298 char *z;
5299 va_start(ap, zFmt);
5300 z = sqlite3_vmprintf(zFmt, ap);
drh1dbb1472018-10-11 10:37:24 +00005301 va_end(ap);
dan3f67ddf2017-12-13 20:04:53 +00005302 if( z==0 ){
5303 *pRc = SQLITE_NOMEM;
5304 }else{
5305 shellPrepare(db, pRc, z, ppStmt);
5306 sqlite3_free(z);
5307 }
dan3f67ddf2017-12-13 20:04:53 +00005308 }
5309}
5310
danfd0245d2017-12-07 15:44:29 +00005311static void shellFinalize(
5312 int *pRc,
5313 sqlite3_stmt *pStmt
5314){
dan25c12182017-12-07 21:03:33 +00005315 if( pStmt ){
5316 sqlite3 *db = sqlite3_db_handle(pStmt);
5317 int rc = sqlite3_finalize(pStmt);
5318 if( *pRc==SQLITE_OK ){
5319 if( rc!=SQLITE_OK ){
5320 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5321 }
5322 *pRc = rc;
5323 }
5324 }
danfd0245d2017-12-07 15:44:29 +00005325}
5326
5327static void shellReset(
5328 int *pRc,
5329 sqlite3_stmt *pStmt
5330){
5331 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00005332 if( *pRc==SQLITE_OK ){
5333 if( rc!=SQLITE_OK ){
5334 sqlite3 *db = sqlite3_db_handle(pStmt);
5335 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5336 }
5337 *pRc = rc;
5338 }
danfd0245d2017-12-07 15:44:29 +00005339}
drhe37c0e12018-01-06 19:19:50 +00005340/*
dan88be0202017-12-09 17:58:02 +00005341** Structure representing a single ".ar" command.
5342*/
5343typedef struct ArCommand ArCommand;
5344struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00005345 u8 eCmd; /* An AR_CMD_* value */
5346 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00005347 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00005348 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00005349 u8 bAppend; /* True if --append */
drhd0f9cdc2018-05-17 14:09:06 +00005350 u8 fromCmdLine; /* Run from -A instead of .archive */
drhb376b3d2018-01-10 13:11:51 +00005351 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00005352 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00005353 const char *zFile; /* --file argument, or NULL */
5354 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00005355 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00005356 ShellState *p; /* Shell state */
5357 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00005358};
5359
5360/*
5361** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5362*/
dan0d0547f2017-12-14 15:40:42 +00005363static int arUsage(FILE *f){
drh98aa2ab2018-09-26 16:53:51 +00005364 showHelp(f,"archive");
dan0d0547f2017-12-14 15:40:42 +00005365 return SQLITE_ERROR;
5366}
5367
5368/*
5369** Print an error message for the .ar command to stderr and return
5370** SQLITE_ERROR.
5371*/
drhd0f9cdc2018-05-17 14:09:06 +00005372static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
dan0d0547f2017-12-14 15:40:42 +00005373 va_list ap;
5374 char *z;
5375 va_start(ap, zFmt);
5376 z = sqlite3_vmprintf(zFmt, ap);
5377 va_end(ap);
drhd0f9cdc2018-05-17 14:09:06 +00005378 utf8_printf(stderr, "Error: %s\n", z);
5379 if( pAr->fromCmdLine ){
5380 utf8_printf(stderr, "Use \"-A\" for more help\n");
5381 }else{
5382 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5383 }
dan0d0547f2017-12-14 15:40:42 +00005384 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00005385 return SQLITE_ERROR;
5386}
5387
5388/*
5389** Values for ArCommand.eCmd.
5390*/
dand4b56e52017-12-12 20:04:59 +00005391#define AR_CMD_CREATE 1
drhb17ea912019-03-25 14:24:19 +00005392#define AR_CMD_UPDATE 2
5393#define AR_CMD_INSERT 3
5394#define AR_CMD_EXTRACT 4
5395#define AR_CMD_LIST 5
5396#define AR_CMD_HELP 6
dand4b56e52017-12-12 20:04:59 +00005397
5398/*
5399** Other (non-command) switches.
5400*/
drhb17ea912019-03-25 14:24:19 +00005401#define AR_SWITCH_VERBOSE 7
5402#define AR_SWITCH_FILE 8
5403#define AR_SWITCH_DIRECTORY 9
5404#define AR_SWITCH_APPEND 10
5405#define AR_SWITCH_DRYRUN 11
dand4b56e52017-12-12 20:04:59 +00005406
5407static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5408 switch( eSwitch ){
5409 case AR_CMD_CREATE:
5410 case AR_CMD_EXTRACT:
5411 case AR_CMD_LIST:
5412 case AR_CMD_UPDATE:
drhb17ea912019-03-25 14:24:19 +00005413 case AR_CMD_INSERT:
dan0d0547f2017-12-14 15:40:42 +00005414 case AR_CMD_HELP:
5415 if( pAr->eCmd ){
drhd0f9cdc2018-05-17 14:09:06 +00005416 return arErrorMsg(pAr, "multiple command options");
dan0d0547f2017-12-14 15:40:42 +00005417 }
dand4b56e52017-12-12 20:04:59 +00005418 pAr->eCmd = eSwitch;
5419 break;
5420
drhb376b3d2018-01-10 13:11:51 +00005421 case AR_SWITCH_DRYRUN:
5422 pAr->bDryRun = 1;
5423 break;
dand4b56e52017-12-12 20:04:59 +00005424 case AR_SWITCH_VERBOSE:
5425 pAr->bVerbose = 1;
5426 break;
drha5676c42018-01-10 15:17:34 +00005427 case AR_SWITCH_APPEND:
5428 pAr->bAppend = 1;
drhca7733b2018-01-10 18:09:20 +00005429 /* Fall thru into --file */
dand4b56e52017-12-12 20:04:59 +00005430 case AR_SWITCH_FILE:
5431 pAr->zFile = zArg;
5432 break;
5433 case AR_SWITCH_DIRECTORY:
5434 pAr->zDir = zArg;
5435 break;
5436 }
5437
5438 return SQLITE_OK;
5439}
dan88be0202017-12-09 17:58:02 +00005440
5441/*
5442** Parse the command line for an ".ar" command. The results are written into
5443** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5444** successfully, otherwise an error message is written to stderr and
5445** SQLITE_ERROR returned.
5446*/
5447static int arParseCommand(
5448 char **azArg, /* Array of arguments passed to dot command */
5449 int nArg, /* Number of entries in azArg[] */
5450 ArCommand *pAr /* Populate this object */
5451){
dand4b56e52017-12-12 20:04:59 +00005452 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00005453 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00005454 char cShort;
5455 u8 eSwitch;
5456 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00005457 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00005458 { "create", 'c', AR_CMD_CREATE, 0 },
5459 { "extract", 'x', AR_CMD_EXTRACT, 0 },
drhb17ea912019-03-25 14:24:19 +00005460 { "insert", 'i', AR_CMD_INSERT, 0 },
drhb376b3d2018-01-10 13:11:51 +00005461 { "list", 't', AR_CMD_LIST, 0 },
5462 { "update", 'u', AR_CMD_UPDATE, 0 },
5463 { "help", 'h', AR_CMD_HELP, 0 },
5464 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
5465 { "file", 'f', AR_SWITCH_FILE, 1 },
drhca7733b2018-01-10 18:09:20 +00005466 { "append", 'a', AR_SWITCH_APPEND, 1 },
drhb376b3d2018-01-10 13:11:51 +00005467 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drhb376b3d2018-01-10 13:11:51 +00005468 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00005469 };
5470 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5471 struct ArSwitch *pEnd = &aSwitch[nSwitch];
5472
dan88be0202017-12-09 17:58:02 +00005473 if( nArg<=1 ){
drh98aa2ab2018-09-26 16:53:51 +00005474 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
dan0d0547f2017-12-14 15:40:42 +00005475 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00005476 }else{
5477 char *z = azArg[1];
dan88be0202017-12-09 17:58:02 +00005478 if( z[0]!='-' ){
5479 /* Traditional style [tar] invocation */
5480 int i;
5481 int iArg = 2;
5482 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00005483 const char *zArg = 0;
5484 struct ArSwitch *pOpt;
5485 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5486 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00005487 }
dan0d0547f2017-12-14 15:40:42 +00005488 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005489 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005490 }
dand4b56e52017-12-12 20:04:59 +00005491 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005492 if( iArg>=nArg ){
drhd0f9cdc2018-05-17 14:09:06 +00005493 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005494 }
dand4b56e52017-12-12 20:04:59 +00005495 zArg = azArg[iArg++];
5496 }
5497 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00005498 }
dan88be0202017-12-09 17:58:02 +00005499 pAr->nArg = nArg-iArg;
5500 if( pAr->nArg>0 ){
5501 pAr->azArg = &azArg[iArg];
5502 }
dand4b56e52017-12-12 20:04:59 +00005503 }else{
5504 /* Non-traditional invocation */
5505 int iArg;
5506 for(iArg=1; iArg<nArg; iArg++){
5507 int n;
5508 z = azArg[iArg];
5509 if( z[0]!='-' ){
5510 /* All remaining command line words are command arguments. */
5511 pAr->azArg = &azArg[iArg];
5512 pAr->nArg = nArg-iArg;
5513 break;
5514 }
drhaf2770f2018-01-05 14:55:43 +00005515 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00005516
5517 if( z[1]!='-' ){
5518 int i;
5519 /* One or more short options */
5520 for(i=1; i<n; i++){
5521 const char *zArg = 0;
5522 struct ArSwitch *pOpt;
5523 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5524 if( z[i]==pOpt->cShort ) break;
5525 }
dan0d0547f2017-12-14 15:40:42 +00005526 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005527 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005528 }
dand4b56e52017-12-12 20:04:59 +00005529 if( pOpt->bArg ){
5530 if( i<(n-1) ){
5531 zArg = &z[i+1];
5532 i = n;
5533 }else{
dan0d0547f2017-12-14 15:40:42 +00005534 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005535 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005536 }
dand4b56e52017-12-12 20:04:59 +00005537 zArg = azArg[++iArg];
5538 }
5539 }
5540 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5541 }
5542 }else if( z[2]=='\0' ){
5543 /* A -- option, indicating that all remaining command line words
5544 ** are command arguments. */
5545 pAr->azArg = &azArg[iArg+1];
5546 pAr->nArg = nArg-iArg-1;
5547 break;
5548 }else{
5549 /* A long option */
5550 const char *zArg = 0; /* Argument for option, if any */
5551 struct ArSwitch *pMatch = 0; /* Matching option */
5552 struct ArSwitch *pOpt; /* Iterator */
5553 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5554 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00005555 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00005556 if( pMatch ){
drhd0f9cdc2018-05-17 14:09:06 +00005557 return arErrorMsg(pAr, "ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00005558 }else{
5559 pMatch = pOpt;
5560 }
5561 }
5562 }
5563
5564 if( pMatch==0 ){
drhd0f9cdc2018-05-17 14:09:06 +00005565 return arErrorMsg(pAr, "unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00005566 }
5567 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005568 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005569 return arErrorMsg(pAr, "option requires an argument: %s", z);
dan0d0547f2017-12-14 15:40:42 +00005570 }
dand4b56e52017-12-12 20:04:59 +00005571 zArg = azArg[++iArg];
5572 }
5573 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5574 }
5575 }
dan88be0202017-12-09 17:58:02 +00005576 }
5577 }
5578
5579 return SQLITE_OK;
5580}
5581
5582/*
dan3f67ddf2017-12-13 20:04:53 +00005583** This function assumes that all arguments within the ArCommand.azArg[]
5584** array refer to archive members, as for the --extract or --list commands.
5585** It checks that each of them are present. If any specified file is not
5586** present in the archive, an error is printed to stderr and an error
5587** code returned. Otherwise, if all specified arguments are present in
5588** the archive, SQLITE_OK is returned.
5589**
5590** This function strips any trailing '/' characters from each argument.
5591** This is consistent with the way the [tar] command seems to work on
5592** Linux.
5593*/
drhb376b3d2018-01-10 13:11:51 +00005594static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00005595 int rc = SQLITE_OK;
5596 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00005597 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00005598 sqlite3_stmt *pTest = 0;
5599
drhb376b3d2018-01-10 13:11:51 +00005600 shellPreparePrintf(pAr->db, &rc, &pTest,
5601 "SELECT name FROM %s WHERE name=$name",
5602 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00005603 );
drhb376b3d2018-01-10 13:11:51 +00005604 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00005605 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5606 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00005607 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00005608 int bOk = 0;
5609 while( n>0 && z[n-1]=='/' ) n--;
5610 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00005611 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00005612 if( SQLITE_ROW==sqlite3_step(pTest) ){
5613 bOk = 1;
5614 }
5615 shellReset(&rc, pTest);
5616 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00005617 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00005618 rc = SQLITE_ERROR;
5619 }
5620 }
5621 shellFinalize(&rc, pTest);
5622 }
dan3f67ddf2017-12-13 20:04:53 +00005623 return rc;
5624}
5625
5626/*
5627** Format a WHERE clause that can be used against the "sqlar" table to
5628** identify all archive members that match the command arguments held
5629** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5630** The caller is responsible for eventually calling sqlite3_free() on
5631** any non-NULL (*pzWhere) value.
5632*/
5633static void arWhereClause(
5634 int *pRc,
5635 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00005636 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00005637){
5638 char *zWhere = 0;
5639 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00005640 if( pAr->nArg==0 ){
5641 zWhere = sqlite3_mprintf("1");
5642 }else{
5643 int i;
5644 const char *zSep = "";
5645 for(i=0; i<pAr->nArg; i++){
5646 const char *z = pAr->azArg[i];
5647 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00005648 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5649 zWhere, zSep, z, strlen30(z)+1, z
5650 );
danac15e2d2017-12-14 19:15:07 +00005651 if( zWhere==0 ){
5652 *pRc = SQLITE_NOMEM;
5653 break;
5654 }
5655 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00005656 }
dan3f67ddf2017-12-13 20:04:53 +00005657 }
5658 }
5659 *pzWhere = zWhere;
5660}
5661
5662/*
dan88be0202017-12-09 17:58:02 +00005663** Implementation of .ar "lisT" command.
5664*/
drhb376b3d2018-01-10 13:11:51 +00005665static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00005666 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00005667 const char *azCols[] = {
5668 "name",
drh410cad92018-01-10 17:19:16 +00005669 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00005670 };
dan5a78b812017-12-27 18:54:11 +00005671
dan3f67ddf2017-12-13 20:04:53 +00005672 char *zWhere = 0;
5673 sqlite3_stmt *pSql = 0;
5674 int rc;
5675
drhb376b3d2018-01-10 13:11:51 +00005676 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005677 arWhereClause(&rc, pAr, &zWhere);
5678
drhb376b3d2018-01-10 13:11:51 +00005679 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5680 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00005681 if( pAr->bDryRun ){
5682 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5683 }else{
5684 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5685 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00005686 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5687 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00005688 sqlite3_column_int(pSql, 1),
5689 sqlite3_column_text(pSql, 2),
5690 sqlite3_column_text(pSql, 3)
5691 );
5692 }else{
5693 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5694 }
danb5090e42017-12-27 21:13:21 +00005695 }
dan3f67ddf2017-12-13 20:04:53 +00005696 }
dan5a78b812017-12-27 18:54:11 +00005697 shellFinalize(&rc, pSql);
drhd0f9cdc2018-05-17 14:09:06 +00005698 sqlite3_free(zWhere);
dan3f67ddf2017-12-13 20:04:53 +00005699 return rc;
dan88be0202017-12-09 17:58:02 +00005700}
5701
5702
danfd0245d2017-12-07 15:44:29 +00005703/*
5704** Implementation of .ar "eXtract" command.
5705*/
drhb376b3d2018-01-10 13:11:51 +00005706static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00005707 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00005708 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00005709 " ($dir || name),"
5710 " writefile(($dir || name), %s, mode, mtime) "
drh0cfd46a2018-06-06 01:18:01 +00005711 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5712 " AND name NOT GLOB '*..[/\\]*'";
dan5a78b812017-12-27 18:54:11 +00005713
5714 const char *azExtraArg[] = {
5715 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00005716 "data"
dan5a78b812017-12-27 18:54:11 +00005717 };
dan5a78b812017-12-27 18:54:11 +00005718
danfd0245d2017-12-07 15:44:29 +00005719 sqlite3_stmt *pSql = 0;
5720 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00005721 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00005722 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00005723 int i, j;
dan2ad09492017-12-09 18:28:22 +00005724
dan3f67ddf2017-12-13 20:04:53 +00005725 /* If arguments are specified, check that they actually exist within
5726 ** the archive before proceeding. And formulate a WHERE clause to
5727 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00005728 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005729 arWhereClause(&rc, pAr, &zWhere);
5730
5731 if( rc==SQLITE_OK ){
5732 if( pAr->zDir ){
5733 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5734 }else{
5735 zDir = sqlite3_mprintf("");
5736 }
5737 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00005738 }
danfd0245d2017-12-07 15:44:29 +00005739
drhb376b3d2018-01-10 13:11:51 +00005740 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5741 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00005742 );
5743
dan2ad09492017-12-09 18:28:22 +00005744 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005745 j = sqlite3_bind_parameter_index(pSql, "$dir");
5746 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00005747
danac15e2d2017-12-14 19:15:07 +00005748 /* Run the SELECT statement twice. The first time, writefile() is called
5749 ** for all archive members that should be extracted. The second time,
5750 ** only for the directories. This is because the timestamps for
5751 ** extracted directories must be reset after they are populated (as
5752 ** populating them changes the timestamp). */
5753 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00005754 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5755 sqlite3_bind_int(pSql, j, i);
5756 if( pAr->bDryRun ){
5757 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5758 }else{
5759 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5760 if( i==0 && pAr->bVerbose ){
5761 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5762 }
danac15e2d2017-12-14 19:15:07 +00005763 }
5764 }
5765 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005766 }
danac15e2d2017-12-14 19:15:07 +00005767 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005768 }
dan25c12182017-12-07 21:03:33 +00005769
dan2ad09492017-12-09 18:28:22 +00005770 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00005771 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00005772 return rc;
5773}
5774
drhb376b3d2018-01-10 13:11:51 +00005775/*
5776** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5777*/
5778static int arExecSql(ArCommand *pAr, const char *zSql){
5779 int rc;
5780 if( pAr->bDryRun ){
5781 utf8_printf(pAr->p->out, "%s\n", zSql);
5782 rc = SQLITE_OK;
5783 }else{
drh410cad92018-01-10 17:19:16 +00005784 char *zErr = 0;
5785 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5786 if( zErr ){
5787 utf8_printf(stdout, "ERROR: %s\n", zErr);
5788 sqlite3_free(zErr);
5789 }
drhb376b3d2018-01-10 13:11:51 +00005790 }
5791 return rc;
5792}
5793
dan1ad3f612017-12-11 20:22:02 +00005794
danfd0245d2017-12-07 15:44:29 +00005795/*
drhb17ea912019-03-25 14:24:19 +00005796** Implementation of .ar "create", "insert", and "update" commands.
5797**
5798** create -> Create a new SQL archive
5799** insert -> Insert or reinsert all files listed
5800** update -> Insert files that have changed or that were not
5801** previously in the archive
danfd0245d2017-12-07 15:44:29 +00005802**
5803** Create the "sqlar" table in the database if it does not already exist.
5804** Then add each file in the azFile[] array to the archive. Directories
5805** are added recursively. If argument bVerbose is non-zero, a message is
5806** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00005807**
5808** The create command is the same as update, except that it drops
drhb17ea912019-03-25 14:24:19 +00005809** any existing "sqlar" table before beginning. The "insert" command
5810** always overwrites every file named on the command-line, where as
5811** "update" only overwrites if the size or mtime or mode has changed.
danfd0245d2017-12-07 15:44:29 +00005812*/
drhb376b3d2018-01-10 13:11:51 +00005813static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00005814 ArCommand *pAr, /* Command arguments and options */
drhb17ea912019-03-25 14:24:19 +00005815 int bUpdate, /* true for a --create. */
5816 int bOnlyIfChanged /* Only update if file has changed */
danfd0245d2017-12-07 15:44:29 +00005817){
dand4b56e52017-12-12 20:04:59 +00005818 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00005819 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5820 " name TEXT PRIMARY KEY, -- name of the file\n"
5821 " mode INT, -- access permissions\n"
5822 " mtime INT, -- last modification time\n"
5823 " sz INT, -- original file size\n"
5824 " data BLOB -- compressed content\n"
5825 ")";
dand4b56e52017-12-12 20:04:59 +00005826 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh1bf208c2018-03-09 21:54:01 +00005827 const char *zInsertFmt[2] = {
5828 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
drh634c70f2018-01-10 16:50:18 +00005829 " SELECT\n"
5830 " %s,\n"
5831 " mode,\n"
5832 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00005833 " CASE substr(lsmode(mode),1,1)\n"
5834 " WHEN '-' THEN length(data)\n"
5835 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00005836 " ELSE -1 END,\n"
drh69d2d352018-03-09 22:18:53 +00005837 " sqlar_compress(data)\n"
drhb17ea912019-03-25 14:24:19 +00005838 " FROM fsdir(%Q,%Q) AS disk\n"
5839 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
5840 ,
drh1bf208c2018-03-09 21:54:01 +00005841 "REPLACE INTO %s(name,mode,mtime,data)\n"
5842 " SELECT\n"
5843 " %s,\n"
5844 " mode,\n"
5845 " mtime,\n"
5846 " data\n"
drhb17ea912019-03-25 14:24:19 +00005847 " FROM fsdir(%Q,%Q) AS disk\n"
5848 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
drh1bf208c2018-03-09 21:54:01 +00005849 };
danfd0245d2017-12-07 15:44:29 +00005850 int i; /* For iterating through azFile[] */
5851 int rc; /* Return code */
drh1bf208c2018-03-09 21:54:01 +00005852 const char *zTab = 0; /* SQL table into which to insert */
5853 char *zSql;
5854 char zTemp[50];
drhb17ea912019-03-25 14:24:19 +00005855 char *zExists = 0;
danfd0245d2017-12-07 15:44:29 +00005856
drh1bf208c2018-03-09 21:54:01 +00005857 arExecSql(pAr, "PRAGMA page_size=512");
drhb376b3d2018-01-10 13:11:51 +00005858 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00005859 if( rc!=SQLITE_OK ) return rc;
drh1bf208c2018-03-09 21:54:01 +00005860 zTemp[0] = 0;
5861 if( pAr->bZip ){
5862 /* Initialize the zipfile virtual table, if necessary */
5863 if( pAr->zFile ){
5864 sqlite3_uint64 r;
5865 sqlite3_randomness(sizeof(r),&r);
5866 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5867 zTab = zTemp;
5868 zSql = sqlite3_mprintf(
5869 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5870 zTab, pAr->zFile
5871 );
5872 rc = arExecSql(pAr, zSql);
5873 sqlite3_free(zSql);
5874 }else{
5875 zTab = "zip";
5876 }
5877 }else{
5878 /* Initialize the table for an SQLAR */
5879 zTab = "sqlar";
5880 if( bUpdate==0 ){
5881 rc = arExecSql(pAr, zDrop);
5882 if( rc!=SQLITE_OK ) goto end_ar_transaction;
5883 }
5884 rc = arExecSql(pAr, zCreate);
dan06741a32017-12-13 20:17:18 +00005885 }
drhb17ea912019-03-25 14:24:19 +00005886 if( bOnlyIfChanged ){
5887 zExists = sqlite3_mprintf(
5888 " AND NOT EXISTS("
5889 "SELECT 1 FROM %s AS mem"
5890 " WHERE mem.name=disk.name"
5891 " AND mem.mtime=disk.mtime"
5892 " AND mem.mode=disk.mode)", zTab);
5893 }else{
5894 zExists = sqlite3_mprintf("");
5895 }
5896 if( zExists==0 ) rc = SQLITE_NOMEM;
dan88be0202017-12-09 17:58:02 +00005897 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
mistachkince2052b2018-03-23 00:31:53 +00005898 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
drh634c70f2018-01-10 16:50:18 +00005899 pAr->bVerbose ? "shell_putsnl(name)" : "name",
drhb17ea912019-03-25 14:24:19 +00005900 pAr->azArg[i], pAr->zDir, zExists);
mistachkince2052b2018-03-23 00:31:53 +00005901 rc = arExecSql(pAr, zSql2);
5902 sqlite3_free(zSql2);
danfd0245d2017-12-07 15:44:29 +00005903 }
drh1bf208c2018-03-09 21:54:01 +00005904end_ar_transaction:
danfd0245d2017-12-07 15:44:29 +00005905 if( rc!=SQLITE_OK ){
drh2bd207f2019-01-11 17:19:59 +00005906 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00005907 }else{
drhb376b3d2018-01-10 13:11:51 +00005908 rc = arExecSql(pAr, "RELEASE ar;");
drh1bf208c2018-03-09 21:54:01 +00005909 if( pAr->bZip && pAr->zFile ){
5910 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
5911 arExecSql(pAr, zSql);
5912 sqlite3_free(zSql);
5913 }
danfd0245d2017-12-07 15:44:29 +00005914 }
drhb17ea912019-03-25 14:24:19 +00005915 sqlite3_free(zExists);
danfd0245d2017-12-07 15:44:29 +00005916 return rc;
5917}
5918
5919/*
5920** Implementation of ".ar" dot command.
5921*/
5922static int arDotCommand(
5923 ShellState *pState, /* Current shell tool state */
drhd0f9cdc2018-05-17 14:09:06 +00005924 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
danfd0245d2017-12-07 15:44:29 +00005925 char **azArg, /* Array of arguments passed to dot command */
5926 int nArg /* Number of entries in azArg[] */
5927){
dan88be0202017-12-09 17:58:02 +00005928 ArCommand cmd;
5929 int rc;
drh34660642018-01-10 17:39:54 +00005930 memset(&cmd, 0, sizeof(cmd));
drhd0f9cdc2018-05-17 14:09:06 +00005931 cmd.fromCmdLine = fromCmdLine;
dan88be0202017-12-09 17:58:02 +00005932 rc = arParseCommand(azArg, nArg, &cmd);
5933 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00005934 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00005935 cmd.p = pState;
5936 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00005937 if( cmd.zFile ){
drh1bf208c2018-03-09 21:54:01 +00005938 eDbType = deduceDatabaseType(cmd.zFile, 1);
drha5676c42018-01-10 15:17:34 +00005939 }else{
5940 eDbType = pState->openMode;
5941 }
5942 if( eDbType==SHELL_OPEN_ZIPFILE ){
drh1bf208c2018-03-09 21:54:01 +00005943 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
5944 if( cmd.zFile==0 ){
5945 cmd.zSrcTable = sqlite3_mprintf("zip");
5946 }else{
5947 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
5948 }
dan5a78b812017-12-27 18:54:11 +00005949 }
drha5676c42018-01-10 15:17:34 +00005950 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00005951 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00005952 int flags;
drha5676c42018-01-10 15:17:34 +00005953 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
drhb17ea912019-03-25 14:24:19 +00005954 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
5955 || cmd.eCmd==AR_CMD_UPDATE ){
dand4b56e52017-12-12 20:04:59 +00005956 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
5957 }else{
5958 flags = SQLITE_OPEN_READONLY;
5959 }
drha82c95b2018-01-10 14:00:00 +00005960 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00005961 if( cmd.bDryRun ){
5962 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
5963 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
5964 }
5965 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
5966 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00005967 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005968 utf8_printf(stderr, "cannot open file: %s (%s)\n",
5969 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00005970 );
drha5676c42018-01-10 15:17:34 +00005971 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00005972 }
drhb376b3d2018-01-10 13:11:51 +00005973 sqlite3_fileio_init(cmd.db, 0, 0);
drhb376b3d2018-01-10 13:11:51 +00005974 sqlite3_sqlar_init(cmd.db, 0, 0);
drh34660642018-01-10 17:39:54 +00005975 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
5976 shellPutsFunc, 0, 0);
5977
dand4b56e52017-12-12 20:04:59 +00005978 }
drhd0f9cdc2018-05-17 14:09:06 +00005979 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
drh634c70f2018-01-10 16:50:18 +00005980 if( cmd.eCmd!=AR_CMD_CREATE
5981 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
5982 ){
drha5676c42018-01-10 15:17:34 +00005983 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
5984 rc = SQLITE_ERROR;
5985 goto end_ar_command;
5986 }
5987 cmd.zSrcTable = sqlite3_mprintf("sqlar");
5988 }
dand4b56e52017-12-12 20:04:59 +00005989
dan88be0202017-12-09 17:58:02 +00005990 switch( cmd.eCmd ){
5991 case AR_CMD_CREATE:
drhb17ea912019-03-25 14:24:19 +00005992 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
dan88be0202017-12-09 17:58:02 +00005993 break;
danfd0245d2017-12-07 15:44:29 +00005994
dan88be0202017-12-09 17:58:02 +00005995 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00005996 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00005997 break;
5998
5999 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00006000 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00006001 break;
6002
dan0d0547f2017-12-14 15:40:42 +00006003 case AR_CMD_HELP:
6004 arUsage(pState->out);
6005 break;
6006
drhb17ea912019-03-25 14:24:19 +00006007 case AR_CMD_INSERT:
6008 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6009 break;
6010
dan88be0202017-12-09 17:58:02 +00006011 default:
6012 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb17ea912019-03-25 14:24:19 +00006013 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
dan88be0202017-12-09 17:58:02 +00006014 break;
danfd0245d2017-12-07 15:44:29 +00006015 }
6016 }
drha5676c42018-01-10 15:17:34 +00006017end_ar_command:
6018 if( cmd.db!=pState->db ){
drh9e804032018-05-18 17:11:50 +00006019 close_db(cmd.db);
drha5676c42018-01-10 15:17:34 +00006020 }
6021 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00006022
dan88be0202017-12-09 17:58:02 +00006023 return rc;
danfd0245d2017-12-07 15:44:29 +00006024}
drhe37c0e12018-01-06 19:19:50 +00006025/* End of the ".archive" or ".ar" command logic
6026**********************************************************************************/
6027#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00006028
drh2ce15c32017-07-11 13:34:40 +00006029
6030/*
6031** If an input line begins with "." then invoke this routine to
6032** process that line.
6033**
6034** Return 1 on error, 2 to exit, and 0 otherwise.
6035*/
6036static int do_meta_command(char *zLine, ShellState *p){
6037 int h = 1;
6038 int nArg = 0;
6039 int n, c;
6040 int rc = 0;
6041 char *azArg[50];
6042
dan6b046be2018-01-09 15:25:55 +00006043#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006044 if( p->expert.pExpert ){
6045 expertFinish(p, 1, 0);
6046 }
dan6b046be2018-01-09 15:25:55 +00006047#endif
dan43efc182017-12-19 17:42:13 +00006048
drh2ce15c32017-07-11 13:34:40 +00006049 /* Parse the input line into tokens.
6050 */
6051 while( zLine[h] && nArg<ArraySize(azArg) ){
6052 while( IsSpace(zLine[h]) ){ h++; }
6053 if( zLine[h]==0 ) break;
6054 if( zLine[h]=='\'' || zLine[h]=='"' ){
6055 int delim = zLine[h++];
6056 azArg[nArg++] = &zLine[h];
6057 while( zLine[h] && zLine[h]!=delim ){
6058 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
6059 h++;
6060 }
6061 if( zLine[h]==delim ){
6062 zLine[h++] = 0;
6063 }
6064 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
6065 }else{
6066 azArg[nArg++] = &zLine[h];
6067 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
6068 if( zLine[h] ) zLine[h++] = 0;
6069 resolve_backslashes(azArg[nArg-1]);
6070 }
6071 }
6072
6073 /* Process the input line.
6074 */
6075 if( nArg==0 ) return 0; /* no tokens, no error */
6076 n = strlen30(azArg[0]);
6077 c = azArg[0][0];
drh13c20932018-01-10 21:41:55 +00006078 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00006079
6080#ifndef SQLITE_OMIT_AUTHORIZATION
6081 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
6082 if( nArg!=2 ){
6083 raw_printf(stderr, "Usage: .auth ON|OFF\n");
6084 rc = 1;
6085 goto meta_command_exit;
6086 }
6087 open_db(p, 0);
6088 if( booleanValue(azArg[1]) ){
6089 sqlite3_set_authorizer(p->db, shellAuth, p);
6090 }else{
6091 sqlite3_set_authorizer(p->db, 0, 0);
6092 }
6093 }else
6094#endif
6095
drhe37c0e12018-01-06 19:19:50 +00006096#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6097 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00006098 open_db(p, 0);
drhd0f9cdc2018-05-17 14:09:06 +00006099 rc = arDotCommand(p, 0, azArg, nArg);
danfd0245d2017-12-07 15:44:29 +00006100 }else
6101#endif
6102
drh2ce15c32017-07-11 13:34:40 +00006103 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
6104 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
6105 ){
6106 const char *zDestFile = 0;
6107 const char *zDb = 0;
6108 sqlite3 *pDest;
6109 sqlite3_backup *pBackup;
6110 int j;
drha50bffb2018-12-08 01:09:14 +00006111 int bAsync = 0;
drh69ed38a2018-05-14 00:23:08 +00006112 const char *zVfs = 0;
drh2ce15c32017-07-11 13:34:40 +00006113 for(j=1; j<nArg; j++){
6114 const char *z = azArg[j];
6115 if( z[0]=='-' ){
drh69ed38a2018-05-14 00:23:08 +00006116 if( z[1]=='-' ) z++;
6117 if( strcmp(z, "-append")==0 ){
6118 zVfs = "apndvfs";
6119 }else
drha50bffb2018-12-08 01:09:14 +00006120 if( strcmp(z, "-async")==0 ){
6121 bAsync = 1;
6122 }else
drh2ce15c32017-07-11 13:34:40 +00006123 {
6124 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
6125 return 1;
6126 }
6127 }else if( zDestFile==0 ){
6128 zDestFile = azArg[j];
6129 }else if( zDb==0 ){
6130 zDb = zDestFile;
6131 zDestFile = azArg[j];
6132 }else{
drha50bffb2018-12-08 01:09:14 +00006133 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
drh2ce15c32017-07-11 13:34:40 +00006134 return 1;
6135 }
6136 }
6137 if( zDestFile==0 ){
6138 raw_printf(stderr, "missing FILENAME argument on .backup\n");
6139 return 1;
6140 }
6141 if( zDb==0 ) zDb = "main";
drh69ed38a2018-05-14 00:23:08 +00006142 rc = sqlite3_open_v2(zDestFile, &pDest,
6143 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
drh2ce15c32017-07-11 13:34:40 +00006144 if( rc!=SQLITE_OK ){
6145 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9e804032018-05-18 17:11:50 +00006146 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006147 return 1;
6148 }
drha50bffb2018-12-08 01:09:14 +00006149 if( bAsync ){
6150 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
6151 0, 0, 0);
6152 }
drh2ce15c32017-07-11 13:34:40 +00006153 open_db(p, 0);
6154 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
6155 if( pBackup==0 ){
6156 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9e804032018-05-18 17:11:50 +00006157 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006158 return 1;
6159 }
6160 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
6161 sqlite3_backup_finish(pBackup);
6162 if( rc==SQLITE_DONE ){
6163 rc = 0;
6164 }else{
6165 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
6166 rc = 1;
6167 }
drh9e804032018-05-18 17:11:50 +00006168 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006169 }else
6170
6171 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
6172 if( nArg==2 ){
6173 bail_on_error = booleanValue(azArg[1]);
6174 }else{
6175 raw_printf(stderr, "Usage: .bail on|off\n");
6176 rc = 1;
6177 }
6178 }else
6179
6180 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
6181 if( nArg==2 ){
6182 if( booleanValue(azArg[1]) ){
6183 setBinaryMode(p->out, 1);
6184 }else{
6185 setTextMode(p->out, 1);
6186 }
6187 }else{
6188 raw_printf(stderr, "Usage: .binary on|off\n");
6189 rc = 1;
6190 }
6191 }else
6192
6193 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
6194 if( nArg==2 ){
6195#if defined(_WIN32) || defined(WIN32)
6196 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
6197 rc = !SetCurrentDirectoryW(z);
6198 sqlite3_free(z);
6199#else
6200 rc = chdir(azArg[1]);
6201#endif
6202 if( rc ){
6203 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
6204 rc = 1;
6205 }
6206 }else{
6207 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
6208 rc = 1;
6209 }
6210 }else
6211
6212 /* The undocumented ".breakpoint" command causes a call to the no-op
6213 ** routine named test_breakpoint().
6214 */
6215 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
6216 test_breakpoint();
6217 }else
6218
6219 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
6220 if( nArg==2 ){
6221 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
6222 }else{
6223 raw_printf(stderr, "Usage: .changes on|off\n");
6224 rc = 1;
6225 }
6226 }else
6227
6228 /* Cancel output redirection, if it is currently set (by .testcase)
6229 ** Then read the content of the testcase-out.txt file and compare against
6230 ** azArg[1]. If there are differences, report an error and exit.
6231 */
6232 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
6233 char *zRes = 0;
6234 output_reset(p);
6235 if( nArg!=2 ){
6236 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
6237 rc = 2;
6238 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
6239 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
6240 rc = 2;
6241 }else if( testcase_glob(azArg[1],zRes)==0 ){
6242 utf8_printf(stderr,
6243 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
6244 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00006245 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00006246 }else{
6247 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
6248 p->nCheck++;
6249 }
6250 sqlite3_free(zRes);
6251 }else
6252
6253 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
6254 if( nArg==2 ){
6255 tryToClone(p, azArg[1]);
6256 }else{
6257 raw_printf(stderr, "Usage: .clone FILENAME\n");
6258 rc = 1;
6259 }
6260 }else
6261
6262 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
6263 ShellState data;
6264 char *zErrMsg = 0;
6265 open_db(p, 0);
6266 memcpy(&data, p, sizeof(data));
6267 data.showHeader = 0;
6268 data.cMode = data.mode = MODE_List;
6269 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
6270 data.cnt = 0;
6271 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
6272 callback, &data, &zErrMsg);
6273 if( zErrMsg ){
6274 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6275 sqlite3_free(zErrMsg);
6276 rc = 1;
6277 }
6278 }else
6279
drh7df01192018-04-28 12:43:16 +00006280 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
drheb7f2a02018-09-26 18:02:32 +00006281 static const struct DbConfigChoices {
6282 const char *zName;
6283 int op;
6284 } aDbConfig[] = {
drh7df01192018-04-28 12:43:16 +00006285 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
6286 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
6287 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
6288 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
6289 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
6290 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
6291 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
6292 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
drha296cda2018-11-03 16:09:59 +00006293 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
drh7df01192018-04-28 12:43:16 +00006294 };
6295 int ii, v;
6296 open_db(p, 0);
6297 for(ii=0; ii<ArraySize(aDbConfig); ii++){
6298 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
6299 if( nArg>=3 ){
6300 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
6301 }
6302 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
6303 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
6304 if( nArg>1 ) break;
6305 }
6306 if( nArg>1 && ii==ArraySize(aDbConfig) ){
6307 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
6308 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
6309 }
6310 }else
6311
6312 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00006313 rc = shell_dbinfo_command(p, nArg, azArg);
6314 }else
6315
6316 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
6317 const char *zLike = 0;
6318 int i;
6319 int savedShowHeader = p->showHeader;
drhf213b332018-07-05 17:35:46 +00006320 int savedShellFlags = p->shellFlgs;
6321 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
drh2ce15c32017-07-11 13:34:40 +00006322 for(i=1; i<nArg; i++){
6323 if( azArg[i][0]=='-' ){
6324 const char *z = azArg[i]+1;
6325 if( z[0]=='-' ) z++;
6326 if( strcmp(z,"preserve-rowids")==0 ){
6327#ifdef SQLITE_OMIT_VIRTUALTABLE
6328 raw_printf(stderr, "The --preserve-rowids option is not compatible"
6329 " with SQLITE_OMIT_VIRTUALTABLE\n");
6330 rc = 1;
6331 goto meta_command_exit;
6332#else
6333 ShellSetFlag(p, SHFLG_PreserveRowid);
6334#endif
6335 }else
6336 if( strcmp(z,"newlines")==0 ){
6337 ShellSetFlag(p, SHFLG_Newlines);
6338 }else
6339 {
6340 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
6341 rc = 1;
6342 goto meta_command_exit;
6343 }
6344 }else if( zLike ){
6345 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
6346 "?--newlines? ?LIKE-PATTERN?\n");
6347 rc = 1;
6348 goto meta_command_exit;
6349 }else{
6350 zLike = azArg[i];
6351 }
6352 }
6353 open_db(p, 0);
6354 /* When playing back a "dump", the content might appear in an order
6355 ** which causes immediate foreign key constraints to be violated.
6356 ** So disable foreign-key constraint enforcement to prevent problems. */
6357 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
6358 raw_printf(p->out, "BEGIN TRANSACTION;\n");
6359 p->writableSchema = 0;
6360 p->showHeader = 0;
6361 /* Set writable_schema=ON since doing so forces SQLite to initialize
6362 ** as much of the schema as it can even if the sqlite_master table is
6363 ** corrupt. */
6364 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
6365 p->nErr = 0;
6366 if( zLike==0 ){
6367 run_schema_dump_query(p,
6368 "SELECT name, type, sql FROM sqlite_master "
6369 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
6370 );
6371 run_schema_dump_query(p,
6372 "SELECT name, type, sql FROM sqlite_master "
6373 "WHERE name=='sqlite_sequence'"
6374 );
6375 run_table_dump_query(p,
6376 "SELECT sql FROM sqlite_master "
6377 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
6378 );
6379 }else{
6380 char *zSql;
6381 zSql = sqlite3_mprintf(
6382 "SELECT name, type, sql FROM sqlite_master "
6383 "WHERE tbl_name LIKE %Q AND type=='table'"
6384 " AND sql NOT NULL", zLike);
6385 run_schema_dump_query(p,zSql);
6386 sqlite3_free(zSql);
6387 zSql = sqlite3_mprintf(
6388 "SELECT sql FROM sqlite_master "
6389 "WHERE sql NOT NULL"
6390 " AND type IN ('index','trigger','view')"
6391 " AND tbl_name LIKE %Q", zLike);
6392 run_table_dump_query(p, zSql, 0);
6393 sqlite3_free(zSql);
6394 }
6395 if( p->writableSchema ){
6396 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
6397 p->writableSchema = 0;
6398 }
6399 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6400 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
6401 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
6402 p->showHeader = savedShowHeader;
drhf213b332018-07-05 17:35:46 +00006403 p->shellFlgs = savedShellFlags;
drh2ce15c32017-07-11 13:34:40 +00006404 }else
6405
6406 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
6407 if( nArg==2 ){
6408 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
6409 }else{
6410 raw_printf(stderr, "Usage: .echo on|off\n");
6411 rc = 1;
6412 }
6413 }else
6414
6415 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
6416 if( nArg==2 ){
drhe2ca99c2018-05-02 00:33:43 +00006417 p->autoEQPtest = 0;
drhb4e50392019-01-26 15:40:04 +00006418 if( p->autoEQPtrace ){
6419 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
6420 p->autoEQPtrace = 0;
6421 }
drh2ce15c32017-07-11 13:34:40 +00006422 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00006423 p->autoEQP = AUTOEQP_full;
6424 }else if( strcmp(azArg[1],"trigger")==0 ){
6425 p->autoEQP = AUTOEQP_trigger;
drhb4e50392019-01-26 15:40:04 +00006426#ifdef SQLITE_DEBUG
drhe2ca99c2018-05-02 00:33:43 +00006427 }else if( strcmp(azArg[1],"test")==0 ){
6428 p->autoEQP = AUTOEQP_on;
6429 p->autoEQPtest = 1;
drhb4e50392019-01-26 15:40:04 +00006430 }else if( strcmp(azArg[1],"trace")==0 ){
6431 p->autoEQP = AUTOEQP_full;
6432 p->autoEQPtrace = 1;
6433 open_db(p, 0);
drhc07eee72019-01-27 19:50:56 +00006434 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
drhb4e50392019-01-26 15:40:04 +00006435 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
6436#endif
drh2ce15c32017-07-11 13:34:40 +00006437 }else{
mistachkinb71aa092018-01-23 00:05:18 +00006438 p->autoEQP = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00006439 }
6440 }else{
drhb4e50392019-01-26 15:40:04 +00006441 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00006442 rc = 1;
6443 }
6444 }else
6445
6446 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
6447 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
6448 rc = 2;
6449 }else
6450
6451 /* The ".explain" command is automatic now. It is largely pointless. It
6452 ** retained purely for backwards compatibility */
6453 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
6454 int val = 1;
6455 if( nArg>=2 ){
6456 if( strcmp(azArg[1],"auto")==0 ){
6457 val = 99;
6458 }else{
6459 val = booleanValue(azArg[1]);
6460 }
6461 }
6462 if( val==1 && p->mode!=MODE_Explain ){
6463 p->normalMode = p->mode;
6464 p->mode = MODE_Explain;
6465 p->autoExplain = 0;
6466 }else if( val==0 ){
6467 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6468 p->autoExplain = 0;
6469 }else if( val==99 ){
6470 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
6471 p->autoExplain = 1;
6472 }
6473 }else
6474
dan6b046be2018-01-09 15:25:55 +00006475#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006476 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
6477 open_db(p, 0);
6478 expertDotCommand(p, azArg, nArg);
6479 }else
dan6b046be2018-01-09 15:25:55 +00006480#endif
dan43efc182017-12-19 17:42:13 +00006481
drh2ce15c32017-07-11 13:34:40 +00006482 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
6483 ShellState data;
6484 char *zErrMsg = 0;
6485 int doStats = 0;
6486 memcpy(&data, p, sizeof(data));
6487 data.showHeader = 0;
6488 data.cMode = data.mode = MODE_Semi;
6489 if( nArg==2 && optionMatch(azArg[1], "indent") ){
6490 data.cMode = data.mode = MODE_Pretty;
6491 nArg = 1;
6492 }
6493 if( nArg!=1 ){
6494 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
6495 rc = 1;
6496 goto meta_command_exit;
6497 }
6498 open_db(p, 0);
6499 rc = sqlite3_exec(p->db,
6500 "SELECT sql FROM"
6501 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
6502 " FROM sqlite_master UNION ALL"
6503 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
6504 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
6505 "ORDER BY rowid",
6506 callback, &data, &zErrMsg
6507 );
6508 if( rc==SQLITE_OK ){
6509 sqlite3_stmt *pStmt;
6510 rc = sqlite3_prepare_v2(p->db,
6511 "SELECT rowid FROM sqlite_master"
6512 " WHERE name GLOB 'sqlite_stat[134]'",
6513 -1, &pStmt, 0);
6514 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
6515 sqlite3_finalize(pStmt);
6516 }
6517 if( doStats==0 ){
6518 raw_printf(p->out, "/* No STAT tables available */\n");
6519 }else{
6520 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6521 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
6522 callback, &data, &zErrMsg);
6523 data.cMode = data.mode = MODE_Insert;
6524 data.zDestTable = "sqlite_stat1";
drh4c540452018-05-08 23:17:36 +00006525 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006526 data.zDestTable = "sqlite_stat3";
drh4c540452018-05-08 23:17:36 +00006527 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006528 data.zDestTable = "sqlite_stat4";
drh4c540452018-05-08 23:17:36 +00006529 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00006530 raw_printf(p->out, "ANALYZE sqlite_master;\n");
6531 }
6532 }else
6533
6534 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
6535 if( nArg==2 ){
6536 p->showHeader = booleanValue(azArg[1]);
6537 }else{
6538 raw_printf(stderr, "Usage: .headers on|off\n");
6539 rc = 1;
6540 }
6541 }else
6542
6543 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
drh98aa2ab2018-09-26 16:53:51 +00006544 if( nArg>=2 ){
drhe93f8262018-10-11 16:53:37 +00006545 n = showHelp(p->out, azArg[1]);
drh98aa2ab2018-09-26 16:53:51 +00006546 if( n==0 ){
6547 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
6548 }
6549 }else{
6550 showHelp(p->out, 0);
6551 }
drh2ce15c32017-07-11 13:34:40 +00006552 }else
6553
6554 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
6555 char *zTable; /* Insert data into this table */
6556 char *zFile; /* Name of file to extra content from */
6557 sqlite3_stmt *pStmt = NULL; /* A statement */
6558 int nCol; /* Number of columns in the table */
6559 int nByte; /* Number of bytes in an SQL string */
6560 int i, j; /* Loop counters */
6561 int needCommit; /* True to COMMIT or ROLLBACK at end */
6562 int nSep; /* Number of bytes in p->colSeparator[] */
6563 char *zSql; /* An SQL statement */
6564 ImportCtx sCtx; /* Reader context */
6565 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
6566 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
6567
6568 if( nArg!=3 ){
6569 raw_printf(stderr, "Usage: .import FILE TABLE\n");
6570 goto meta_command_exit;
6571 }
6572 zFile = azArg[1];
6573 zTable = azArg[2];
6574 seenInterrupt = 0;
6575 memset(&sCtx, 0, sizeof(sCtx));
6576 open_db(p, 0);
6577 nSep = strlen30(p->colSeparator);
6578 if( nSep==0 ){
6579 raw_printf(stderr,
6580 "Error: non-null column separator required for import\n");
6581 return 1;
6582 }
6583 if( nSep>1 ){
6584 raw_printf(stderr, "Error: multi-character column separators not allowed"
6585 " for import\n");
6586 return 1;
6587 }
6588 nSep = strlen30(p->rowSeparator);
6589 if( nSep==0 ){
6590 raw_printf(stderr, "Error: non-null row separator required for import\n");
6591 return 1;
6592 }
6593 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
6594 /* When importing CSV (only), if the row separator is set to the
6595 ** default output row separator, change it to the default input
6596 ** row separator. This avoids having to maintain different input
6597 ** and output row separators. */
6598 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6599 nSep = strlen30(p->rowSeparator);
6600 }
6601 if( nSep>1 ){
6602 raw_printf(stderr, "Error: multi-character row separators not allowed"
6603 " for import\n");
6604 return 1;
6605 }
6606 sCtx.zFile = zFile;
6607 sCtx.nLine = 1;
6608 if( sCtx.zFile[0]=='|' ){
6609#ifdef SQLITE_OMIT_POPEN
6610 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6611 return 1;
6612#else
6613 sCtx.in = popen(sCtx.zFile+1, "r");
6614 sCtx.zFile = "<pipe>";
6615 xCloser = pclose;
6616#endif
6617 }else{
6618 sCtx.in = fopen(sCtx.zFile, "rb");
6619 xCloser = fclose;
6620 }
6621 if( p->mode==MODE_Ascii ){
6622 xRead = ascii_read_one_field;
6623 }else{
6624 xRead = csv_read_one_field;
6625 }
6626 if( sCtx.in==0 ){
6627 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
6628 return 1;
6629 }
6630 sCtx.cColSep = p->colSeparator[0];
6631 sCtx.cRowSep = p->rowSeparator[0];
6632 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
6633 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00006634 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00006635 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00006636 }
6637 nByte = strlen30(zSql);
6638 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6639 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
6640 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
6641 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
6642 char cSep = '(';
6643 while( xRead(&sCtx) ){
6644 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
6645 cSep = ',';
6646 if( sCtx.cTerm!=sCtx.cColSep ) break;
6647 }
6648 if( cSep=='(' ){
6649 sqlite3_free(zCreate);
6650 sqlite3_free(sCtx.z);
6651 xCloser(sCtx.in);
6652 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
6653 return 1;
6654 }
6655 zCreate = sqlite3_mprintf("%z\n)", zCreate);
6656 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
6657 sqlite3_free(zCreate);
6658 if( rc ){
6659 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
6660 sqlite3_errmsg(p->db));
6661 sqlite3_free(sCtx.z);
6662 xCloser(sCtx.in);
6663 return 1;
6664 }
6665 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6666 }
6667 sqlite3_free(zSql);
6668 if( rc ){
6669 if (pStmt) sqlite3_finalize(pStmt);
6670 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
6671 xCloser(sCtx.in);
6672 return 1;
6673 }
6674 nCol = sqlite3_column_count(pStmt);
6675 sqlite3_finalize(pStmt);
6676 pStmt = 0;
6677 if( nCol==0 ) return 0; /* no columns, no error */
6678 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
6679 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00006680 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00006681 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00006682 }
6683 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
6684 j = strlen30(zSql);
6685 for(i=1; i<nCol; i++){
6686 zSql[j++] = ',';
6687 zSql[j++] = '?';
6688 }
6689 zSql[j++] = ')';
6690 zSql[j] = 0;
6691 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6692 sqlite3_free(zSql);
6693 if( rc ){
6694 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6695 if (pStmt) sqlite3_finalize(pStmt);
6696 xCloser(sCtx.in);
6697 return 1;
6698 }
6699 needCommit = sqlite3_get_autocommit(p->db);
6700 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
6701 do{
6702 int startLine = sCtx.nLine;
6703 for(i=0; i<nCol; i++){
6704 char *z = xRead(&sCtx);
6705 /*
6706 ** Did we reach end-of-file before finding any columns?
6707 ** If so, stop instead of NULL filling the remaining columns.
6708 */
6709 if( z==0 && i==0 ) break;
6710 /*
6711 ** Did we reach end-of-file OR end-of-line before finding any
6712 ** columns in ASCII mode? If so, stop instead of NULL filling
6713 ** the remaining columns.
6714 */
6715 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
6716 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
6717 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
6718 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6719 "filling the rest with NULL\n",
6720 sCtx.zFile, startLine, nCol, i+1);
6721 i += 2;
6722 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
6723 }
6724 }
6725 if( sCtx.cTerm==sCtx.cColSep ){
6726 do{
6727 xRead(&sCtx);
6728 i++;
6729 }while( sCtx.cTerm==sCtx.cColSep );
6730 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
6731 "extras ignored\n",
6732 sCtx.zFile, startLine, nCol, i);
6733 }
6734 if( i>=nCol ){
6735 sqlite3_step(pStmt);
6736 rc = sqlite3_reset(pStmt);
6737 if( rc!=SQLITE_OK ){
6738 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
6739 startLine, sqlite3_errmsg(p->db));
6740 }
6741 }
6742 }while( sCtx.cTerm!=EOF );
6743
6744 xCloser(sCtx.in);
6745 sqlite3_free(sCtx.z);
6746 sqlite3_finalize(pStmt);
6747 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
6748 }else
6749
6750#ifndef SQLITE_UNTESTABLE
6751 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
6752 char *zSql;
6753 char *zCollist = 0;
6754 sqlite3_stmt *pStmt;
6755 int tnum = 0;
6756 int i;
drh48d219a2018-04-23 18:38:48 +00006757 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
6758 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
6759 " .imposter off\n");
drh2ce15c32017-07-11 13:34:40 +00006760 rc = 1;
6761 goto meta_command_exit;
6762 }
6763 open_db(p, 0);
drh48d219a2018-04-23 18:38:48 +00006764 if( nArg==2 ){
6765 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
6766 goto meta_command_exit;
6767 }
drh2ce15c32017-07-11 13:34:40 +00006768 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6769 " WHERE name='%q' AND type='index'", azArg[1]);
6770 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6771 sqlite3_free(zSql);
6772 if( sqlite3_step(pStmt)==SQLITE_ROW ){
6773 tnum = sqlite3_column_int(pStmt, 0);
6774 }
6775 sqlite3_finalize(pStmt);
6776 if( tnum==0 ){
6777 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
6778 rc = 1;
6779 goto meta_command_exit;
6780 }
6781 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
6782 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6783 sqlite3_free(zSql);
6784 i = 0;
6785 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6786 char zLabel[20];
6787 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
6788 i++;
6789 if( zCol==0 ){
6790 if( sqlite3_column_int(pStmt,1)==-1 ){
6791 zCol = "_ROWID_";
6792 }else{
6793 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
6794 zCol = zLabel;
6795 }
6796 }
6797 if( zCollist==0 ){
6798 zCollist = sqlite3_mprintf("\"%w\"", zCol);
6799 }else{
6800 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
6801 }
6802 }
6803 sqlite3_finalize(pStmt);
6804 zSql = sqlite3_mprintf(
6805 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6806 azArg[2], zCollist, zCollist);
6807 sqlite3_free(zCollist);
6808 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
6809 if( rc==SQLITE_OK ){
6810 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
6811 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
6812 if( rc ){
6813 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
6814 }else{
6815 utf8_printf(stdout, "%s;\n", zSql);
6816 raw_printf(stdout,
6817 "WARNING: writing to an imposter table will corrupt the index!\n"
6818 );
6819 }
6820 }else{
6821 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
6822 rc = 1;
6823 }
6824 sqlite3_free(zSql);
6825 }else
6826#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6827
6828#ifdef SQLITE_ENABLE_IOTRACE
6829 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
6830 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
6831 if( iotrace && iotrace!=stdout ) fclose(iotrace);
6832 iotrace = 0;
6833 if( nArg<2 ){
6834 sqlite3IoTrace = 0;
6835 }else if( strcmp(azArg[1], "-")==0 ){
6836 sqlite3IoTrace = iotracePrintf;
6837 iotrace = stdout;
6838 }else{
6839 iotrace = fopen(azArg[1], "w");
6840 if( iotrace==0 ){
6841 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
6842 sqlite3IoTrace = 0;
6843 rc = 1;
6844 }else{
6845 sqlite3IoTrace = iotracePrintf;
6846 }
6847 }
6848 }else
6849#endif
6850
6851 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
6852 static const struct {
6853 const char *zLimitName; /* Name of a limit */
6854 int limitCode; /* Integer code for that limit */
6855 } aLimit[] = {
6856 { "length", SQLITE_LIMIT_LENGTH },
6857 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
6858 { "column", SQLITE_LIMIT_COLUMN },
6859 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
6860 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
6861 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
6862 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
6863 { "attached", SQLITE_LIMIT_ATTACHED },
6864 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
6865 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
6866 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
6867 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
6868 };
6869 int i, n2;
6870 open_db(p, 0);
6871 if( nArg==1 ){
6872 for(i=0; i<ArraySize(aLimit); i++){
6873 printf("%20s %d\n", aLimit[i].zLimitName,
6874 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
6875 }
6876 }else if( nArg>3 ){
6877 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
6878 rc = 1;
6879 goto meta_command_exit;
6880 }else{
6881 int iLimit = -1;
6882 n2 = strlen30(azArg[1]);
6883 for(i=0; i<ArraySize(aLimit); i++){
6884 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
6885 if( iLimit<0 ){
6886 iLimit = i;
6887 }else{
6888 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
6889 rc = 1;
6890 goto meta_command_exit;
6891 }
6892 }
6893 }
6894 if( iLimit<0 ){
6895 utf8_printf(stderr, "unknown limit: \"%s\"\n"
6896 "enter \".limits\" with no arguments for a list.\n",
6897 azArg[1]);
6898 rc = 1;
6899 goto meta_command_exit;
6900 }
6901 if( nArg==3 ){
6902 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
6903 (int)integerValue(azArg[2]));
6904 }
6905 printf("%20s %d\n", aLimit[iLimit].zLimitName,
6906 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
6907 }
6908 }else
6909
6910 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
6911 open_db(p, 0);
6912 lintDotCommand(p, azArg, nArg);
6913 }else
6914
6915#ifndef SQLITE_OMIT_LOAD_EXTENSION
6916 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
6917 const char *zFile, *zProc;
6918 char *zErrMsg = 0;
6919 if( nArg<2 ){
6920 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
6921 rc = 1;
6922 goto meta_command_exit;
6923 }
6924 zFile = azArg[1];
6925 zProc = nArg>=3 ? azArg[2] : 0;
6926 open_db(p, 0);
6927 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
6928 if( rc!=SQLITE_OK ){
6929 utf8_printf(stderr, "Error: %s\n", zErrMsg);
6930 sqlite3_free(zErrMsg);
6931 rc = 1;
6932 }
6933 }else
6934#endif
6935
6936 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
6937 if( nArg!=2 ){
6938 raw_printf(stderr, "Usage: .log FILENAME\n");
6939 rc = 1;
6940 }else{
6941 const char *zFile = azArg[1];
6942 output_file_close(p->pLog);
drha92a01a2018-01-10 22:15:37 +00006943 p->pLog = output_file_open(zFile, 0);
drh2ce15c32017-07-11 13:34:40 +00006944 }
6945 }else
6946
6947 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6948 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00006949 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00006950 int c2 = zMode[0];
6951 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
6952 p->mode = MODE_Line;
6953 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6954 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
6955 p->mode = MODE_Column;
6956 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6957 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
6958 p->mode = MODE_List;
6959 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6960 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6961 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
6962 p->mode = MODE_Html;
6963 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
6964 p->mode = MODE_Tcl;
6965 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
6966 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
6967 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
6968 p->mode = MODE_Csv;
6969 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
6970 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
6971 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
6972 p->mode = MODE_List;
6973 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
6974 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
6975 p->mode = MODE_Insert;
6976 set_table_name(p, nArg>=3 ? azArg[2] : "table");
6977 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6978 p->mode = MODE_Quote;
6979 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6980 p->mode = MODE_Ascii;
6981 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6982 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
6983 }else if( nArg==1 ){
6984 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6985 }else{
6986 raw_printf(stderr, "Error: mode should be one of: "
6987 "ascii column csv html insert line list quote tabs tcl\n");
6988 rc = 1;
6989 }
6990 p->cMode = p->mode;
6991 }else
6992
6993 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6994 if( nArg==2 ){
6995 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6996 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
6997 }else{
6998 raw_printf(stderr, "Usage: .nullvalue STRING\n");
6999 rc = 1;
7000 }
7001 }else
7002
7003 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
7004 char *zNewFilename; /* Name of the database file to open */
7005 int iName = 1; /* Index in azArg[] of the filename */
7006 int newFlag = 0; /* True to delete file before opening */
7007 /* Close the existing database */
7008 session_close_all(p);
drh9e804032018-05-18 17:11:50 +00007009 close_db(p->db);
drh2ce15c32017-07-11 13:34:40 +00007010 p->db = 0;
7011 p->zDbFilename = 0;
7012 sqlite3_free(p->zFreeOnClose);
7013 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00007014 p->openMode = SHELL_OPEN_UNSPEC;
drh6ca64482019-01-22 16:06:20 +00007015 p->szMax = 0;
drh2ce15c32017-07-11 13:34:40 +00007016 /* Check for command-line arguments */
7017 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
7018 const char *z = azArg[iName];
7019 if( optionMatch(z,"new") ){
7020 newFlag = 1;
drh3baed312018-03-08 18:14:41 +00007021#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00007022 }else if( optionMatch(z, "zip") ){
7023 p->openMode = SHELL_OPEN_ZIPFILE;
7024#endif
7025 }else if( optionMatch(z, "append") ){
7026 p->openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00007027 }else if( optionMatch(z, "readonly") ){
7028 p->openMode = SHELL_OPEN_READONLY;
drha751f392018-10-30 15:31:22 +00007029#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00007030 }else if( optionMatch(z, "deserialize") ){
7031 p->openMode = SHELL_OPEN_DESERIALIZE;
drh33746482018-12-13 15:06:26 +00007032 }else if( optionMatch(z, "hexdb") ){
7033 p->openMode = SHELL_OPEN_HEXDB;
drh6ca64482019-01-22 16:06:20 +00007034 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
7035 p->szMax = integerValue(azArg[++iName]);
drh33746482018-12-13 15:06:26 +00007036#endif /* SQLITE_ENABLE_DESERIALIZE */
drh2ce15c32017-07-11 13:34:40 +00007037 }else if( z[0]=='-' ){
7038 utf8_printf(stderr, "unknown option: %s\n", z);
7039 rc = 1;
7040 goto meta_command_exit;
7041 }
7042 }
7043 /* If a filename is specified, try to open it first */
7044 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
drh33746482018-12-13 15:06:26 +00007045 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
drh2ce15c32017-07-11 13:34:40 +00007046 if( newFlag ) shellDeleteFile(zNewFilename);
7047 p->zDbFilename = zNewFilename;
drhbe4ccb22018-05-17 20:04:24 +00007048 open_db(p, OPEN_DB_KEEPALIVE);
drh2ce15c32017-07-11 13:34:40 +00007049 if( p->db==0 ){
7050 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
7051 sqlite3_free(zNewFilename);
7052 }else{
7053 p->zFreeOnClose = zNewFilename;
7054 }
7055 }
7056 if( p->db==0 ){
7057 /* As a fall-back open a TEMP database */
7058 p->zDbFilename = 0;
7059 open_db(p, 0);
7060 }
7061 }else
7062
drh13c20932018-01-10 21:41:55 +00007063 if( (c=='o'
7064 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
7065 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
drh2ce15c32017-07-11 13:34:40 +00007066 ){
7067 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
drha92a01a2018-01-10 22:15:37 +00007068 int bTxtMode = 0;
drh13c20932018-01-10 21:41:55 +00007069 if( azArg[0][0]=='e' ){
7070 /* Transform the ".excel" command into ".once -x" */
7071 nArg = 2;
7072 azArg[0] = "once";
7073 zFile = azArg[1] = "-x";
7074 n = 4;
7075 }
drh2ce15c32017-07-11 13:34:40 +00007076 if( nArg>2 ){
drh13c20932018-01-10 21:41:55 +00007077 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00007078 rc = 1;
7079 goto meta_command_exit;
7080 }
7081 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
7082 if( nArg<2 ){
drh13c20932018-01-10 21:41:55 +00007083 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
drh2ce15c32017-07-11 13:34:40 +00007084 rc = 1;
7085 goto meta_command_exit;
7086 }
7087 p->outCount = 2;
7088 }else{
7089 p->outCount = 0;
7090 }
7091 output_reset(p);
drh13c20932018-01-10 21:41:55 +00007092 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
drh04a28c32018-01-31 01:38:44 +00007093#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00007094 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
drh3c484e82018-01-10 22:27:21 +00007095 p->doXdgOpen = 1;
7096 outputModePush(p);
drh13c20932018-01-10 21:41:55 +00007097 if( zFile[1]=='x' ){
7098 newTempFile(p, "csv");
7099 p->mode = MODE_Csv;
7100 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
7101 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
7102 }else{
7103 newTempFile(p, "txt");
drha92a01a2018-01-10 22:15:37 +00007104 bTxtMode = 1;
drh13c20932018-01-10 21:41:55 +00007105 }
7106 zFile = p->zTempFile;
7107 }
drh04a28c32018-01-31 01:38:44 +00007108#endif /* SQLITE_NOHAVE_SYSTEM */
drh2ce15c32017-07-11 13:34:40 +00007109 if( zFile[0]=='|' ){
7110#ifdef SQLITE_OMIT_POPEN
7111 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7112 rc = 1;
7113 p->out = stdout;
7114#else
7115 p->out = popen(zFile + 1, "w");
7116 if( p->out==0 ){
7117 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
7118 p->out = stdout;
7119 rc = 1;
7120 }else{
7121 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7122 }
7123#endif
7124 }else{
drha92a01a2018-01-10 22:15:37 +00007125 p->out = output_file_open(zFile, bTxtMode);
drh2ce15c32017-07-11 13:34:40 +00007126 if( p->out==0 ){
7127 if( strcmp(zFile,"off")!=0 ){
7128 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
7129 }
7130 p->out = stdout;
7131 rc = 1;
7132 } else {
7133 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7134 }
7135 }
7136 }else
7137
drh9cb02642019-02-28 20:10:52 +00007138 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
7139 open_db(p,0);
7140 if( nArg<=1 ) goto parameter_syntax_error;
7141
7142 /* .parameter clear
7143 ** Clear all bind parameters by dropping the TEMP table that holds them.
7144 */
7145 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
drh346f4e22019-03-25 21:35:41 +00007146 int wrSchema = 0;
7147 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
7148 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
drh65c29fd2019-03-25 21:56:26 +00007149 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
drh9cb02642019-02-28 20:10:52 +00007150 0, 0, 0);
drh346f4e22019-03-25 21:35:41 +00007151 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
drh9cb02642019-02-28 20:10:52 +00007152 }else
7153
7154 /* .parameter list
7155 ** List all bind parameters.
7156 */
7157 if( nArg==2 && strcmp(azArg[1],"list")==0 ){
7158 sqlite3_stmt *pStmt = 0;
7159 int rx;
7160 int len = 0;
7161 rx = sqlite3_prepare_v2(p->db,
7162 "SELECT max(length(key)) "
drh65c29fd2019-03-25 21:56:26 +00007163 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
drh9cb02642019-02-28 20:10:52 +00007164 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
7165 len = sqlite3_column_int(pStmt, 0);
7166 if( len>40 ) len = 40;
7167 }
7168 sqlite3_finalize(pStmt);
7169 pStmt = 0;
7170 if( len ){
7171 rx = sqlite3_prepare_v2(p->db,
7172 "SELECT key, quote(value) "
drh65c29fd2019-03-25 21:56:26 +00007173 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
drh9cb02642019-02-28 20:10:52 +00007174 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7175 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
7176 sqlite3_column_text(pStmt,1));
7177 }
7178 sqlite3_finalize(pStmt);
7179 }
7180 }else
7181
7182 /* .parameter init
7183 ** Make sure the TEMP table used to hold bind parameters exists.
7184 ** Create it if necessary.
7185 */
7186 if( nArg==2 && strcmp(azArg[1],"init")==0 ){
7187 bind_table_init(p);
7188 }else
7189
7190 /* .parameter set NAME VALUE
7191 ** Set or reset a bind parameter. NAME should be the full parameter
7192 ** name exactly as it appears in the query. (ex: $abc, @def). The
7193 ** VALUE can be in either SQL literal notation, or if not it will be
7194 ** understood to be a text string.
7195 */
7196 if( nArg==4 && strcmp(azArg[1],"set")==0 ){
7197 int rx;
7198 char *zSql;
7199 sqlite3_stmt *pStmt;
7200 const char *zKey = azArg[2];
7201 const char *zValue = azArg[3];
7202 bind_table_init(p);
7203 zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007204 "REPLACE INTO temp.sqlite_parameters(key,value)"
drh9cb02642019-02-28 20:10:52 +00007205 "VALUES(%Q,%s);", zKey, zValue);
7206 if( zSql==0 ) shell_out_of_memory();
7207 pStmt = 0;
7208 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7209 sqlite3_free(zSql);
7210 if( rx!=SQLITE_OK ){
7211 sqlite3_finalize(pStmt);
7212 pStmt = 0;
7213 zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007214 "REPLACE INTO temp.sqlite_parameters(key,value)"
drh9cb02642019-02-28 20:10:52 +00007215 "VALUES(%Q,%Q);", zKey, zValue);
7216 if( zSql==0 ) shell_out_of_memory();
7217 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7218 sqlite3_free(zSql);
7219 if( rx!=SQLITE_OK ){
7220 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
7221 sqlite3_finalize(pStmt);
7222 pStmt = 0;
7223 rc = 1;
7224 }
7225 }
7226 sqlite3_step(pStmt);
7227 sqlite3_finalize(pStmt);
7228 }else
7229
7230 /* .parameter unset NAME
7231 ** Remove the NAME binding from the parameter binding table, if it
7232 ** exists.
7233 */
7234 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
7235 char *zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007236 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
drh9cb02642019-02-28 20:10:52 +00007237 if( zSql==0 ) shell_out_of_memory();
7238 sqlite3_exec(p->db, zSql, 0, 0, 0);
7239 sqlite3_free(zSql);
7240 }else
7241 /* If no command name matches, show a syntax error */
7242 parameter_syntax_error:
7243 showHelp(p->out, "parameter");
7244 }else
7245
drh2ce15c32017-07-11 13:34:40 +00007246 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
7247 int i;
7248 for(i=1; i<nArg; i++){
7249 if( i>1 ) raw_printf(p->out, " ");
7250 utf8_printf(p->out, "%s", azArg[i]);
7251 }
7252 raw_printf(p->out, "\n");
7253 }else
7254
drh569b1d92019-02-05 20:51:41 +00007255#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00007256 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
7257 int i;
drhfc4eeef2019-02-05 19:48:46 +00007258 int nn = 0;
drh3f83f592019-02-04 14:53:18 +00007259 p->flgProgress = 0;
7260 p->mxProgress = 0;
7261 p->nProgress = 0;
7262 for(i=1; i<nArg; i++){
7263 const char *z = azArg[i];
7264 if( z[0]=='-' ){
7265 z++;
7266 if( z[0]=='-' ) z++;
7267 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007268 p->flgProgress |= SHELL_PROGRESS_QUIET;
drh3f83f592019-02-04 14:53:18 +00007269 continue;
7270 }
7271 if( strcmp(z,"reset")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007272 p->flgProgress |= SHELL_PROGRESS_RESET;
drh3f83f592019-02-04 14:53:18 +00007273 continue;
7274 }
7275 if( strcmp(z,"once")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007276 p->flgProgress |= SHELL_PROGRESS_ONCE;
drh3f83f592019-02-04 14:53:18 +00007277 continue;
7278 }
7279 if( strcmp(z,"limit")==0 ){
7280 if( i+1>=nArg ){
7281 utf8_printf(stderr, "Error: missing argument on --limit\n");
7282 rc = 1;
7283 goto meta_command_exit;
7284 }else{
7285 p->mxProgress = (int)integerValue(azArg[++i]);
7286 }
7287 continue;
7288 }
7289 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
7290 rc = 1;
7291 goto meta_command_exit;
7292 }else{
drhfc4eeef2019-02-05 19:48:46 +00007293 nn = (int)integerValue(z);
drh3f83f592019-02-04 14:53:18 +00007294 }
7295 }
7296 open_db(p, 0);
drhfc4eeef2019-02-05 19:48:46 +00007297 sqlite3_progress_handler(p->db, nn, progress_handler, p);
drh3f83f592019-02-04 14:53:18 +00007298 }else
drh569b1d92019-02-05 20:51:41 +00007299#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00007300
drh2ce15c32017-07-11 13:34:40 +00007301 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
7302 if( nArg >= 2) {
7303 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
7304 }
7305 if( nArg >= 3) {
7306 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
7307 }
7308 }else
7309
7310 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
7311 rc = 2;
7312 }else
7313
7314 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
drh60379d42018-12-13 18:30:01 +00007315 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00007316 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00007317 if( nArg!=2 ){
7318 raw_printf(stderr, "Usage: .read FILE\n");
7319 rc = 1;
7320 goto meta_command_exit;
7321 }
drh60379d42018-12-13 18:30:01 +00007322 p->in = fopen(azArg[1], "rb");
7323 if( p->in==0 ){
drh2ce15c32017-07-11 13:34:40 +00007324 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
7325 rc = 1;
7326 }else{
drh60379d42018-12-13 18:30:01 +00007327 rc = process_input(p);
7328 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00007329 }
drh60379d42018-12-13 18:30:01 +00007330 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00007331 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00007332 }else
7333
7334 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
7335 const char *zSrcFile;
7336 const char *zDb;
7337 sqlite3 *pSrc;
7338 sqlite3_backup *pBackup;
7339 int nTimeout = 0;
7340
7341 if( nArg==2 ){
7342 zSrcFile = azArg[1];
7343 zDb = "main";
7344 }else if( nArg==3 ){
7345 zSrcFile = azArg[2];
7346 zDb = azArg[1];
7347 }else{
7348 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
7349 rc = 1;
7350 goto meta_command_exit;
7351 }
7352 rc = sqlite3_open(zSrcFile, &pSrc);
7353 if( rc!=SQLITE_OK ){
7354 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9e804032018-05-18 17:11:50 +00007355 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00007356 return 1;
7357 }
7358 open_db(p, 0);
7359 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
7360 if( pBackup==0 ){
7361 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9e804032018-05-18 17:11:50 +00007362 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00007363 return 1;
7364 }
7365 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
7366 || rc==SQLITE_BUSY ){
7367 if( rc==SQLITE_BUSY ){
7368 if( nTimeout++ >= 3 ) break;
7369 sqlite3_sleep(100);
7370 }
7371 }
7372 sqlite3_backup_finish(pBackup);
7373 if( rc==SQLITE_DONE ){
7374 rc = 0;
7375 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
7376 raw_printf(stderr, "Error: source database is busy\n");
7377 rc = 1;
7378 }else{
7379 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7380 rc = 1;
7381 }
drh9e804032018-05-18 17:11:50 +00007382 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00007383 }else
7384
drh2ce15c32017-07-11 13:34:40 +00007385 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
7386 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00007387 p->scanstatsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007388#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
7389 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
7390#endif
7391 }else{
7392 raw_printf(stderr, "Usage: .scanstats on|off\n");
7393 rc = 1;
7394 }
7395 }else
7396
7397 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
7398 ShellText sSelect;
7399 ShellState data;
7400 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00007401 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00007402 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00007403 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00007404 int bDebug = 0;
7405 int ii;
drh2ce15c32017-07-11 13:34:40 +00007406
7407 open_db(p, 0);
7408 memcpy(&data, p, sizeof(data));
7409 data.showHeader = 0;
7410 data.cMode = data.mode = MODE_Semi;
7411 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00007412 for(ii=1; ii<nArg; ii++){
7413 if( optionMatch(azArg[ii],"indent") ){
7414 data.cMode = data.mode = MODE_Pretty;
7415 }else if( optionMatch(azArg[ii],"debug") ){
7416 bDebug = 1;
7417 }else if( zName==0 ){
7418 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00007419 }else{
drhceba7922018-01-01 21:28:25 +00007420 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
7421 rc = 1;
7422 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00007423 }
drh2ce15c32017-07-11 13:34:40 +00007424 }
drhceba7922018-01-01 21:28:25 +00007425 if( zName!=0 ){
mistachkin9d107262018-03-23 14:24:34 +00007426 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
7427 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
drh2ce15c32017-07-11 13:34:40 +00007428 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00007429 new_argv[0] = sqlite3_mprintf(
7430 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00007431 " type text,\n"
7432 " name text,\n"
7433 " tbl_name text,\n"
7434 " rootpage integer,\n"
7435 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00007436 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00007437 new_argv[1] = 0;
7438 new_colv[0] = "sql";
7439 new_colv[1] = 0;
7440 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00007441 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00007442 }
drh2ce15c32017-07-11 13:34:40 +00007443 }
7444 if( zDiv ){
7445 sqlite3_stmt *pStmt = 0;
7446 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
7447 -1, &pStmt, 0);
7448 if( rc ){
7449 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7450 sqlite3_finalize(pStmt);
7451 rc = 1;
7452 goto meta_command_exit;
7453 }
7454 appendText(&sSelect, "SELECT sql FROM", 0);
7455 iSchema = 0;
7456 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7457 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
7458 char zScNum[30];
7459 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
7460 appendText(&sSelect, zDiv, 0);
7461 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00007462 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
7463 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00007464 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00007465 }else{
drhceba7922018-01-01 21:28:25 +00007466 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00007467 }
drhceba7922018-01-01 21:28:25 +00007468 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
7469 appendText(&sSelect, zScNum, 0);
7470 appendText(&sSelect, " AS snum, ", 0);
7471 appendText(&sSelect, zDb, '\'');
7472 appendText(&sSelect, " AS sname FROM ", 0);
7473 appendText(&sSelect, zDb, '"');
7474 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00007475 }
7476 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00007477#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00007478 if( zName ){
7479 appendText(&sSelect,
7480 " UNION ALL SELECT shell_module_schema(name),"
7481 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
7482 }
drhcde7b772018-01-02 12:50:40 +00007483#endif
drh2ce15c32017-07-11 13:34:40 +00007484 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00007485 if( zName ){
7486 char *zQarg = sqlite3_mprintf("%Q", zName);
mistachkin9d107262018-03-23 14:24:34 +00007487 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
7488 strchr(zName, '[') != 0;
drhceba7922018-01-01 21:28:25 +00007489 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00007490 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
7491 }else{
7492 appendText(&sSelect, "lower(tbl_name)", 0);
7493 }
mistachkin9d107262018-03-23 14:24:34 +00007494 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00007495 appendText(&sSelect, zQarg, 0);
mistachkin9d107262018-03-23 14:24:34 +00007496 if( !bGlob ){
7497 appendText(&sSelect, " ESCAPE '\\' ", 0);
7498 }
drh2ce15c32017-07-11 13:34:40 +00007499 appendText(&sSelect, " AND ", 0);
7500 sqlite3_free(zQarg);
7501 }
7502 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
7503 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00007504 if( bDebug ){
7505 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
7506 }else{
7507 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
7508 }
drh2ce15c32017-07-11 13:34:40 +00007509 freeText(&sSelect);
7510 }
7511 if( zErrMsg ){
7512 utf8_printf(stderr,"Error: %s\n", zErrMsg);
7513 sqlite3_free(zErrMsg);
7514 rc = 1;
7515 }else if( rc != SQLITE_OK ){
7516 raw_printf(stderr,"Error: querying schema information\n");
7517 rc = 1;
7518 }else{
7519 rc = 0;
7520 }
7521 }else
7522
7523#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
7524 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
7525 sqlite3SelectTrace = (int)integerValue(azArg[1]);
7526 }else
7527#endif
7528
7529#if defined(SQLITE_ENABLE_SESSION)
7530 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
7531 OpenSession *pSession = &p->aSession[0];
7532 char **azCmd = &azArg[1];
7533 int iSes = 0;
7534 int nCmd = nArg - 1;
7535 int i;
7536 if( nArg<=1 ) goto session_syntax_error;
7537 open_db(p, 0);
7538 if( nArg>=3 ){
7539 for(iSes=0; iSes<p->nSession; iSes++){
7540 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
7541 }
7542 if( iSes<p->nSession ){
7543 pSession = &p->aSession[iSes];
7544 azCmd++;
7545 nCmd--;
7546 }else{
7547 pSession = &p->aSession[0];
7548 iSes = 0;
7549 }
7550 }
7551
7552 /* .session attach TABLE
7553 ** Invoke the sqlite3session_attach() interface to attach a particular
7554 ** table so that it is never filtered.
7555 */
7556 if( strcmp(azCmd[0],"attach")==0 ){
7557 if( nCmd!=2 ) goto session_syntax_error;
7558 if( pSession->p==0 ){
7559 session_not_open:
7560 raw_printf(stderr, "ERROR: No sessions are open\n");
7561 }else{
7562 rc = sqlite3session_attach(pSession->p, azCmd[1]);
7563 if( rc ){
7564 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
7565 rc = 0;
7566 }
7567 }
7568 }else
7569
7570 /* .session changeset FILE
7571 ** .session patchset FILE
7572 ** Write a changeset or patchset into a file. The file is overwritten.
7573 */
7574 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
7575 FILE *out = 0;
7576 if( nCmd!=2 ) goto session_syntax_error;
7577 if( pSession->p==0 ) goto session_not_open;
7578 out = fopen(azCmd[1], "wb");
7579 if( out==0 ){
7580 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
7581 }else{
7582 int szChng;
7583 void *pChng;
7584 if( azCmd[0][0]=='c' ){
7585 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
7586 }else{
7587 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
7588 }
7589 if( rc ){
7590 printf("Error: error code %d\n", rc);
7591 rc = 0;
7592 }
7593 if( pChng
7594 && fwrite(pChng, szChng, 1, out)!=1 ){
7595 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
7596 szChng);
7597 }
7598 sqlite3_free(pChng);
7599 fclose(out);
7600 }
7601 }else
7602
7603 /* .session close
7604 ** Close the identified session
7605 */
7606 if( strcmp(azCmd[0], "close")==0 ){
7607 if( nCmd!=1 ) goto session_syntax_error;
7608 if( p->nSession ){
7609 session_close(pSession);
7610 p->aSession[iSes] = p->aSession[--p->nSession];
7611 }
7612 }else
7613
7614 /* .session enable ?BOOLEAN?
7615 ** Query or set the enable flag
7616 */
7617 if( strcmp(azCmd[0], "enable")==0 ){
7618 int ii;
7619 if( nCmd>2 ) goto session_syntax_error;
7620 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7621 if( p->nSession ){
7622 ii = sqlite3session_enable(pSession->p, ii);
7623 utf8_printf(p->out, "session %s enable flag = %d\n",
7624 pSession->zName, ii);
7625 }
7626 }else
7627
7628 /* .session filter GLOB ....
7629 ** Set a list of GLOB patterns of table names to be excluded.
7630 */
7631 if( strcmp(azCmd[0], "filter")==0 ){
7632 int ii, nByte;
7633 if( nCmd<2 ) goto session_syntax_error;
7634 if( p->nSession ){
7635 for(ii=0; ii<pSession->nFilter; ii++){
7636 sqlite3_free(pSession->azFilter[ii]);
7637 }
7638 sqlite3_free(pSession->azFilter);
7639 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
7640 pSession->azFilter = sqlite3_malloc( nByte );
7641 if( pSession->azFilter==0 ){
7642 raw_printf(stderr, "Error: out or memory\n");
7643 exit(1);
7644 }
7645 for(ii=1; ii<nCmd; ii++){
7646 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
7647 }
7648 pSession->nFilter = ii-1;
7649 }
7650 }else
7651
7652 /* .session indirect ?BOOLEAN?
7653 ** Query or set the indirect flag
7654 */
7655 if( strcmp(azCmd[0], "indirect")==0 ){
7656 int ii;
7657 if( nCmd>2 ) goto session_syntax_error;
7658 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
7659 if( p->nSession ){
7660 ii = sqlite3session_indirect(pSession->p, ii);
7661 utf8_printf(p->out, "session %s indirect flag = %d\n",
7662 pSession->zName, ii);
7663 }
7664 }else
7665
7666 /* .session isempty
7667 ** Determine if the session is empty
7668 */
7669 if( strcmp(azCmd[0], "isempty")==0 ){
7670 int ii;
7671 if( nCmd!=1 ) goto session_syntax_error;
7672 if( p->nSession ){
7673 ii = sqlite3session_isempty(pSession->p);
7674 utf8_printf(p->out, "session %s isempty flag = %d\n",
7675 pSession->zName, ii);
7676 }
7677 }else
7678
7679 /* .session list
7680 ** List all currently open sessions
7681 */
7682 if( strcmp(azCmd[0],"list")==0 ){
7683 for(i=0; i<p->nSession; i++){
7684 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
7685 }
7686 }else
7687
7688 /* .session open DB NAME
7689 ** Open a new session called NAME on the attached database DB.
7690 ** DB is normally "main".
7691 */
7692 if( strcmp(azCmd[0],"open")==0 ){
7693 char *zName;
7694 if( nCmd!=3 ) goto session_syntax_error;
7695 zName = azCmd[2];
7696 if( zName[0]==0 ) goto session_syntax_error;
7697 for(i=0; i<p->nSession; i++){
7698 if( strcmp(p->aSession[i].zName,zName)==0 ){
7699 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
7700 goto meta_command_exit;
7701 }
7702 }
7703 if( p->nSession>=ArraySize(p->aSession) ){
7704 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
7705 goto meta_command_exit;
7706 }
7707 pSession = &p->aSession[p->nSession];
7708 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
7709 if( rc ){
7710 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
7711 rc = 0;
7712 goto meta_command_exit;
7713 }
7714 pSession->nFilter = 0;
7715 sqlite3session_table_filter(pSession->p, session_filter, pSession);
7716 p->nSession++;
7717 pSession->zName = sqlite3_mprintf("%s", zName);
7718 }else
7719 /* If no command name matches, show a syntax error */
7720 session_syntax_error:
drheb7f2a02018-09-26 18:02:32 +00007721 showHelp(p->out, "session");
drh2ce15c32017-07-11 13:34:40 +00007722 }else
7723#endif
7724
7725#ifdef SQLITE_DEBUG
7726 /* Undocumented commands for internal testing. Subject to change
7727 ** without notice. */
7728 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
7729 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
7730 int i, v;
7731 for(i=1; i<nArg; i++){
7732 v = booleanValue(azArg[i]);
7733 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
7734 }
7735 }
7736 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
7737 int i; sqlite3_int64 v;
7738 for(i=1; i<nArg; i++){
7739 char zBuf[200];
7740 v = integerValue(azArg[i]);
7741 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
7742 utf8_printf(p->out, "%s", zBuf);
7743 }
7744 }
7745 }else
7746#endif
7747
7748 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
7749 int bIsInit = 0; /* True to initialize the SELFTEST table */
7750 int bVerbose = 0; /* Verbose output */
7751 int bSelftestExists; /* True if SELFTEST already exists */
7752 int i, k; /* Loop counters */
7753 int nTest = 0; /* Number of tests runs */
7754 int nErr = 0; /* Number of errors seen */
7755 ShellText str; /* Answer for a query */
7756 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
7757
7758 open_db(p,0);
7759 for(i=1; i<nArg; i++){
7760 const char *z = azArg[i];
7761 if( z[0]=='-' && z[1]=='-' ) z++;
7762 if( strcmp(z,"-init")==0 ){
7763 bIsInit = 1;
7764 }else
7765 if( strcmp(z,"-v")==0 ){
7766 bVerbose++;
7767 }else
7768 {
7769 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7770 azArg[i], azArg[0]);
7771 raw_printf(stderr, "Should be one of: --init -v\n");
7772 rc = 1;
7773 goto meta_command_exit;
7774 }
7775 }
7776 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
7777 != SQLITE_OK ){
7778 bSelftestExists = 0;
7779 }else{
7780 bSelftestExists = 1;
7781 }
7782 if( bIsInit ){
7783 createSelftestTable(p);
7784 bSelftestExists = 1;
7785 }
7786 initText(&str);
7787 appendText(&str, "x", 0);
7788 for(k=bSelftestExists; k>=0; k--){
7789 if( k==1 ){
7790 rc = sqlite3_prepare_v2(p->db,
7791 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
7792 -1, &pStmt, 0);
7793 }else{
7794 rc = sqlite3_prepare_v2(p->db,
7795 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
7796 " (1,'run','PRAGMA integrity_check','ok')",
7797 -1, &pStmt, 0);
7798 }
7799 if( rc ){
7800 raw_printf(stderr, "Error querying the selftest table\n");
7801 rc = 1;
7802 sqlite3_finalize(pStmt);
7803 goto meta_command_exit;
7804 }
7805 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
7806 int tno = sqlite3_column_int(pStmt, 0);
7807 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
7808 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
7809 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
7810
7811 k = 0;
7812 if( bVerbose>0 ){
7813 char *zQuote = sqlite3_mprintf("%q", zSql);
7814 printf("%d: %s %s\n", tno, zOp, zSql);
7815 sqlite3_free(zQuote);
7816 }
7817 if( strcmp(zOp,"memo")==0 ){
7818 utf8_printf(p->out, "%s\n", zSql);
7819 }else
7820 if( strcmp(zOp,"run")==0 ){
7821 char *zErrMsg = 0;
7822 str.n = 0;
7823 str.z[0] = 0;
7824 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
7825 nTest++;
7826 if( bVerbose ){
7827 utf8_printf(p->out, "Result: %s\n", str.z);
7828 }
7829 if( rc || zErrMsg ){
7830 nErr++;
7831 rc = 1;
7832 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
7833 sqlite3_free(zErrMsg);
7834 }else if( strcmp(zAns,str.z)!=0 ){
7835 nErr++;
7836 rc = 1;
7837 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
7838 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
7839 }
7840 }else
7841 {
7842 utf8_printf(stderr,
7843 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
7844 rc = 1;
7845 break;
7846 }
7847 } /* End loop over rows of content from SELFTEST */
7848 sqlite3_finalize(pStmt);
7849 } /* End loop over k */
7850 freeText(&str);
7851 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
7852 }else
7853
7854 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
7855 if( nArg<2 || nArg>3 ){
7856 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
7857 rc = 1;
7858 }
7859 if( nArg>=2 ){
7860 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
7861 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
7862 }
7863 if( nArg>=3 ){
7864 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
7865 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
7866 }
7867 }else
7868
7869 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
7870 const char *zLike = 0; /* Which table to checksum. 0 means everything */
7871 int i; /* Loop counter */
7872 int bSchema = 0; /* Also hash the schema */
7873 int bSeparate = 0; /* Hash each table separately */
7874 int iSize = 224; /* Hash algorithm to use */
7875 int bDebug = 0; /* Only show the query that would have run */
7876 sqlite3_stmt *pStmt; /* For querying tables names */
7877 char *zSql; /* SQL to be run */
7878 char *zSep; /* Separator */
7879 ShellText sSql; /* Complete SQL for the query to run the hash */
7880 ShellText sQuery; /* Set of queries used to read all content */
7881 open_db(p, 0);
7882 for(i=1; i<nArg; i++){
7883 const char *z = azArg[i];
7884 if( z[0]=='-' ){
7885 z++;
7886 if( z[0]=='-' ) z++;
7887 if( strcmp(z,"schema")==0 ){
7888 bSchema = 1;
7889 }else
7890 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
7891 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
7892 ){
7893 iSize = atoi(&z[5]);
7894 }else
7895 if( strcmp(z,"debug")==0 ){
7896 bDebug = 1;
7897 }else
7898 {
7899 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
7900 azArg[i], azArg[0]);
7901 raw_printf(stderr, "Should be one of: --schema"
drh003edba2018-05-11 15:10:43 +00007902 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
drh2ce15c32017-07-11 13:34:40 +00007903 rc = 1;
7904 goto meta_command_exit;
7905 }
7906 }else if( zLike ){
7907 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7908 rc = 1;
7909 goto meta_command_exit;
7910 }else{
7911 zLike = z;
7912 bSeparate = 1;
drhcedfecf2018-03-23 12:59:10 +00007913 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
drh2ce15c32017-07-11 13:34:40 +00007914 }
7915 }
7916 if( bSchema ){
7917 zSql = "SELECT lower(name) FROM sqlite_master"
7918 " WHERE type='table' AND coalesce(rootpage,0)>1"
7919 " UNION ALL SELECT 'sqlite_master'"
7920 " ORDER BY 1 collate nocase";
7921 }else{
7922 zSql = "SELECT lower(name) FROM sqlite_master"
7923 " WHERE type='table' AND coalesce(rootpage,0)>1"
7924 " AND name NOT LIKE 'sqlite_%'"
7925 " ORDER BY 1 collate nocase";
7926 }
7927 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7928 initText(&sQuery);
7929 initText(&sSql);
7930 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
7931 zSep = "VALUES(";
7932 while( SQLITE_ROW==sqlite3_step(pStmt) ){
7933 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
7934 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
7935 if( strncmp(zTab, "sqlite_",7)!=0 ){
7936 appendText(&sQuery,"SELECT * FROM ", 0);
7937 appendText(&sQuery,zTab,'"');
7938 appendText(&sQuery," NOT INDEXED;", 0);
7939 }else if( strcmp(zTab, "sqlite_master")==0 ){
7940 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7941 " ORDER BY name;", 0);
7942 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
7943 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
7944 " ORDER BY name;", 0);
7945 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
7946 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
7947 " ORDER BY tbl,idx;", 0);
7948 }else if( strcmp(zTab, "sqlite_stat3")==0
7949 || strcmp(zTab, "sqlite_stat4")==0 ){
7950 appendText(&sQuery, "SELECT * FROM ", 0);
7951 appendText(&sQuery, zTab, 0);
7952 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
7953 }
7954 appendText(&sSql, zSep, 0);
7955 appendText(&sSql, sQuery.z, '\'');
7956 sQuery.n = 0;
7957 appendText(&sSql, ",", 0);
7958 appendText(&sSql, zTab, '\'');
7959 zSep = "),(";
7960 }
7961 sqlite3_finalize(pStmt);
7962 if( bSeparate ){
7963 zSql = sqlite3_mprintf(
7964 "%s))"
7965 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7966 " FROM [sha3sum$query]",
7967 sSql.z, iSize);
7968 }else{
7969 zSql = sqlite3_mprintf(
7970 "%s))"
7971 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7972 " FROM [sha3sum$query]",
7973 sSql.z, iSize);
7974 }
7975 freeText(&sQuery);
7976 freeText(&sSql);
7977 if( bDebug ){
7978 utf8_printf(p->out, "%s\n", zSql);
7979 }else{
drha10b9992018-03-09 15:24:33 +00007980 shell_exec(p, zSql, 0);
drh2ce15c32017-07-11 13:34:40 +00007981 }
7982 sqlite3_free(zSql);
7983 }else
7984
drh04a28c32018-01-31 01:38:44 +00007985#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00007986 if( c=='s'
7987 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
7988 ){
7989 char *zCmd;
7990 int i, x;
7991 if( nArg<2 ){
7992 raw_printf(stderr, "Usage: .system COMMAND\n");
7993 rc = 1;
7994 goto meta_command_exit;
7995 }
7996 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
7997 for(i=2; i<nArg; i++){
7998 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
7999 zCmd, azArg[i]);
8000 }
8001 x = system(zCmd);
8002 sqlite3_free(zCmd);
8003 if( x ) raw_printf(stderr, "System command returns %d\n", x);
8004 }else
drh04a28c32018-01-31 01:38:44 +00008005#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00008006
8007 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00008008 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00008009 int i;
8010 if( nArg!=1 ){
8011 raw_printf(stderr, "Usage: .show\n");
8012 rc = 1;
8013 goto meta_command_exit;
8014 }
8015 utf8_printf(p->out, "%12.12s: %s\n","echo",
8016 azBool[ShellHasFlag(p, SHFLG_Echo)]);
8017 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
8018 utf8_printf(p->out, "%12.12s: %s\n","explain",
8019 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
8020 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
8021 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
8022 utf8_printf(p->out, "%12.12s: ", "nullvalue");
8023 output_c_string(p->out, p->nullValue);
8024 raw_printf(p->out, "\n");
8025 utf8_printf(p->out,"%12.12s: %s\n","output",
8026 strlen30(p->outfile) ? p->outfile : "stdout");
8027 utf8_printf(p->out,"%12.12s: ", "colseparator");
8028 output_c_string(p->out, p->colSeparator);
8029 raw_printf(p->out, "\n");
8030 utf8_printf(p->out,"%12.12s: ", "rowseparator");
8031 output_c_string(p->out, p->rowSeparator);
8032 raw_printf(p->out, "\n");
8033 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
8034 utf8_printf(p->out, "%12.12s: ", "width");
8035 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
8036 raw_printf(p->out, "%d ", p->colWidth[i]);
8037 }
8038 raw_printf(p->out, "\n");
8039 utf8_printf(p->out, "%12.12s: %s\n", "filename",
8040 p->zDbFilename ? p->zDbFilename : "");
8041 }else
8042
8043 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
8044 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00008045 p->statsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00008046 }else if( nArg==1 ){
8047 display_stats(p->db, p, 0);
8048 }else{
8049 raw_printf(stderr, "Usage: .stats ?on|off?\n");
8050 rc = 1;
8051 }
8052 }else
8053
8054 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
8055 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
8056 || strncmp(azArg[0], "indexes", n)==0) )
8057 ){
8058 sqlite3_stmt *pStmt;
8059 char **azResult;
8060 int nRow, nAlloc;
8061 int ii;
8062 ShellText s;
8063 initText(&s);
8064 open_db(p, 0);
8065 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
drh9e804032018-05-18 17:11:50 +00008066 if( rc ){
8067 sqlite3_finalize(pStmt);
8068 return shellDatabaseError(p->db);
8069 }
drh2ce15c32017-07-11 13:34:40 +00008070
8071 if( nArg>2 && c=='i' ){
8072 /* It is an historical accident that the .indexes command shows an error
8073 ** when called with the wrong number of arguments whereas the .tables
8074 ** command does not. */
8075 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
8076 rc = 1;
drh9e804032018-05-18 17:11:50 +00008077 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00008078 goto meta_command_exit;
8079 }
8080 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
8081 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
8082 if( zDbName==0 ) continue;
8083 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
8084 if( sqlite3_stricmp(zDbName, "main")==0 ){
8085 appendText(&s, "SELECT name FROM ", 0);
8086 }else{
8087 appendText(&s, "SELECT ", 0);
8088 appendText(&s, zDbName, '\'');
8089 appendText(&s, "||'.'||name FROM ", 0);
8090 }
8091 appendText(&s, zDbName, '"');
8092 appendText(&s, ".sqlite_master ", 0);
8093 if( c=='t' ){
8094 appendText(&s," WHERE type IN ('table','view')"
8095 " AND name NOT LIKE 'sqlite_%'"
8096 " AND name LIKE ?1", 0);
8097 }else{
8098 appendText(&s," WHERE type='index'"
8099 " AND tbl_name LIKE ?1", 0);
8100 }
8101 }
8102 rc = sqlite3_finalize(pStmt);
8103 appendText(&s, " ORDER BY 1", 0);
8104 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
8105 freeText(&s);
8106 if( rc ) return shellDatabaseError(p->db);
8107
8108 /* Run the SQL statement prepared by the above block. Store the results
8109 ** as an array of nul-terminated strings in azResult[]. */
8110 nRow = nAlloc = 0;
8111 azResult = 0;
8112 if( nArg>1 ){
8113 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
8114 }else{
8115 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
8116 }
8117 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8118 if( nRow>=nAlloc ){
8119 char **azNew;
8120 int n2 = nAlloc*2 + 10;
8121 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh4b5345c2018-04-24 13:07:40 +00008122 if( azNew==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008123 nAlloc = n2;
8124 azResult = azNew;
8125 }
8126 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
drh4b5345c2018-04-24 13:07:40 +00008127 if( 0==azResult[nRow] ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008128 nRow++;
8129 }
8130 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
8131 rc = shellDatabaseError(p->db);
8132 }
8133
8134 /* Pretty-print the contents of array azResult[] to the output */
8135 if( rc==0 && nRow>0 ){
8136 int len, maxlen = 0;
8137 int i, j;
8138 int nPrintCol, nPrintRow;
8139 for(i=0; i<nRow; i++){
8140 len = strlen30(azResult[i]);
8141 if( len>maxlen ) maxlen = len;
8142 }
8143 nPrintCol = 80/(maxlen+2);
8144 if( nPrintCol<1 ) nPrintCol = 1;
8145 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
8146 for(i=0; i<nPrintRow; i++){
8147 for(j=i; j<nRow; j+=nPrintRow){
8148 char *zSp = j<nPrintRow ? "" : " ";
8149 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
8150 azResult[j] ? azResult[j]:"");
8151 }
8152 raw_printf(p->out, "\n");
8153 }
8154 }
8155
8156 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
8157 sqlite3_free(azResult);
8158 }else
8159
8160 /* Begin redirecting output to the file "testcase-out.txt" */
8161 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
8162 output_reset(p);
drha92a01a2018-01-10 22:15:37 +00008163 p->out = output_file_open("testcase-out.txt", 0);
drh2ce15c32017-07-11 13:34:40 +00008164 if( p->out==0 ){
8165 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
8166 }
8167 if( nArg>=2 ){
8168 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
8169 }else{
8170 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
8171 }
8172 }else
8173
8174#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00008175 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00008176 static const struct {
8177 const char *zCtrlName; /* Name of a test-control option */
8178 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00008179 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00008180 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00008181 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
8182 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
8183 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
8184 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
8185 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
8186 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
8187 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
drheea8eb62018-11-26 18:09:15 +00008188 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" },
drhef302e82017-11-15 19:14:08 +00008189 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
8190 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
8191 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00008192#ifdef YYCOVERAGE
8193 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
8194#endif
drhef302e82017-11-15 19:14:08 +00008195 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
8196 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
8197 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
8198 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
8199 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00008200 };
8201 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00008202 int iCtrl = -1;
8203 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
8204 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00008205 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00008206 const char *zCmd = 0;
8207
drh2ce15c32017-07-11 13:34:40 +00008208 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00008209 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00008210
8211 /* The argument can optionally begin with "-" or "--" */
8212 if( zCmd[0]=='-' && zCmd[1] ){
8213 zCmd++;
8214 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8215 }
8216
8217 /* --help lists all test-controls */
8218 if( strcmp(zCmd,"help")==0 ){
8219 utf8_printf(p->out, "Available test-controls:\n");
8220 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00008221 utf8_printf(p->out, " .testctrl %s %s\n",
8222 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00008223 }
8224 rc = 1;
8225 goto meta_command_exit;
8226 }
drh2ce15c32017-07-11 13:34:40 +00008227
8228 /* convert testctrl text option to value. allow any unique prefix
8229 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00008230 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00008231 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00008232 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00008233 if( testctrl<0 ){
8234 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00008235 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00008236 }else{
drh35f51a42017-11-15 17:07:22 +00008237 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
8238 "Use \".testctrl --help\" for help\n", zCmd);
8239 rc = 1;
8240 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00008241 }
8242 }
8243 }
drhef302e82017-11-15 19:14:08 +00008244 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00008245 utf8_printf(stderr,"Error: unknown test-control: %s\n"
8246 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00008247 }else{
8248 switch(testctrl){
8249
8250 /* sqlite3_test_control(int, db, int) */
8251 case SQLITE_TESTCTRL_OPTIMIZATIONS:
8252 case SQLITE_TESTCTRL_RESERVE:
8253 if( nArg==3 ){
8254 int opt = (int)strtol(azArg[2], 0, 0);
8255 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00008256 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008257 }
8258 break;
8259
8260 /* sqlite3_test_control(int) */
8261 case SQLITE_TESTCTRL_PRNG_SAVE:
8262 case SQLITE_TESTCTRL_PRNG_RESTORE:
8263 case SQLITE_TESTCTRL_PRNG_RESET:
8264 case SQLITE_TESTCTRL_BYTEORDER:
8265 if( nArg==2 ){
8266 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00008267 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00008268 }
8269 break;
8270
8271 /* sqlite3_test_control(int, uint) */
8272 case SQLITE_TESTCTRL_PENDING_BYTE:
8273 if( nArg==3 ){
8274 unsigned int opt = (unsigned int)integerValue(azArg[2]);
8275 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00008276 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008277 }
8278 break;
8279
8280 /* sqlite3_test_control(int, int) */
8281 case SQLITE_TESTCTRL_ASSERT:
8282 case SQLITE_TESTCTRL_ALWAYS:
drheea8eb62018-11-26 18:09:15 +00008283 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
drhef302e82017-11-15 19:14:08 +00008284 if( nArg==3 ){
8285 int opt = booleanValue(azArg[2]);
8286 rc2 = sqlite3_test_control(testctrl, opt);
8287 isOk = 1;
8288 }
8289 break;
8290
8291 /* sqlite3_test_control(int, int) */
8292 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00008293 case SQLITE_TESTCTRL_NEVER_CORRUPT:
8294 if( nArg==3 ){
8295 int opt = booleanValue(azArg[2]);
8296 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00008297 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008298 }
8299 break;
8300
drh2ce15c32017-07-11 13:34:40 +00008301 case SQLITE_TESTCTRL_IMPOSTER:
8302 if( nArg==5 ){
8303 rc2 = sqlite3_test_control(testctrl, p->db,
8304 azArg[2],
8305 integerValue(azArg[3]),
8306 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00008307 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008308 }
8309 break;
drh0d9de992017-12-26 18:04:23 +00008310
8311#ifdef YYCOVERAGE
8312 case SQLITE_TESTCTRL_PARSER_COVERAGE:
8313 if( nArg==2 ){
8314 sqlite3_test_control(testctrl, p->out);
8315 isOk = 3;
8316 }
8317#endif
drh2ce15c32017-07-11 13:34:40 +00008318 }
8319 }
drhef302e82017-11-15 19:14:08 +00008320 if( isOk==0 && iCtrl>=0 ){
8321 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
8322 rc = 1;
8323 }else if( isOk==1 ){
8324 raw_printf(p->out, "%d\n", rc2);
8325 }else if( isOk==2 ){
8326 raw_printf(p->out, "0x%08x\n", rc2);
8327 }
drh2ce15c32017-07-11 13:34:40 +00008328 }else
8329#endif /* !defined(SQLITE_UNTESTABLE) */
8330
8331 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
8332 open_db(p, 0);
8333 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
8334 }else
8335
8336 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
8337 if( nArg==2 ){
8338 enableTimer = booleanValue(azArg[1]);
8339 if( enableTimer && !HAS_TIMER ){
8340 raw_printf(stderr, "Error: timer not available on this system.\n");
8341 enableTimer = 0;
8342 }
8343 }else{
8344 raw_printf(stderr, "Usage: .timer on|off\n");
8345 rc = 1;
8346 }
8347 }else
8348
drh707821f2018-12-05 13:39:06 +00008349#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00008350 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh707821f2018-12-05 13:39:06 +00008351 int mType = 0;
8352 int jj;
drh2ce15c32017-07-11 13:34:40 +00008353 open_db(p, 0);
drh707821f2018-12-05 13:39:06 +00008354 for(jj=1; jj<nArg; jj++){
8355 const char *z = azArg[jj];
8356 if( z[0]=='-' ){
8357 if( optionMatch(z, "expanded") ){
8358 p->eTraceType = SHELL_TRACE_EXPANDED;
8359 }
8360#ifdef SQLITE_ENABLE_NORMALIZE
8361 else if( optionMatch(z, "normalized") ){
8362 p->eTraceType = SHELL_TRACE_NORMALIZED;
8363 }
8364#endif
8365 else if( optionMatch(z, "plain") ){
8366 p->eTraceType = SHELL_TRACE_PLAIN;
8367 }
8368 else if( optionMatch(z, "profile") ){
8369 mType |= SQLITE_TRACE_PROFILE;
8370 }
8371 else if( optionMatch(z, "row") ){
8372 mType |= SQLITE_TRACE_ROW;
8373 }
8374 else if( optionMatch(z, "stmt") ){
8375 mType |= SQLITE_TRACE_STMT;
8376 }
8377 else if( optionMatch(z, "close") ){
8378 mType |= SQLITE_TRACE_CLOSE;
8379 }
8380 else {
8381 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
8382 rc = 1;
8383 goto meta_command_exit;
8384 }
8385 }else{
8386 output_file_close(p->traceOut);
8387 p->traceOut = output_file_open(azArg[1], 0);
8388 }
drh2ce15c32017-07-11 13:34:40 +00008389 }
drh2ce15c32017-07-11 13:34:40 +00008390 if( p->traceOut==0 ){
8391 sqlite3_trace_v2(p->db, 0, 0, 0);
8392 }else{
drh707821f2018-12-05 13:39:06 +00008393 if( mType==0 ) mType = SQLITE_TRACE_STMT;
8394 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
drh2ce15c32017-07-11 13:34:40 +00008395 }
drh2ce15c32017-07-11 13:34:40 +00008396 }else
drh707821f2018-12-05 13:39:06 +00008397#endif /* !defined(SQLITE_OMIT_TRACE) */
drh2ce15c32017-07-11 13:34:40 +00008398
8399#if SQLITE_USER_AUTHENTICATION
8400 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
8401 if( nArg<2 ){
8402 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
8403 rc = 1;
8404 goto meta_command_exit;
8405 }
8406 open_db(p, 0);
8407 if( strcmp(azArg[1],"login")==0 ){
8408 if( nArg!=4 ){
8409 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
8410 rc = 1;
8411 goto meta_command_exit;
8412 }
drhaf2770f2018-01-05 14:55:43 +00008413 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00008414 if( rc ){
8415 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
8416 rc = 1;
8417 }
8418 }else if( strcmp(azArg[1],"add")==0 ){
8419 if( nArg!=5 ){
8420 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
8421 rc = 1;
8422 goto meta_command_exit;
8423 }
drhaf2770f2018-01-05 14:55:43 +00008424 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00008425 booleanValue(azArg[4]));
8426 if( rc ){
8427 raw_printf(stderr, "User-Add failed: %d\n", rc);
8428 rc = 1;
8429 }
8430 }else if( strcmp(azArg[1],"edit")==0 ){
8431 if( nArg!=5 ){
8432 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
8433 rc = 1;
8434 goto meta_command_exit;
8435 }
drhaf2770f2018-01-05 14:55:43 +00008436 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00008437 booleanValue(azArg[4]));
8438 if( rc ){
8439 raw_printf(stderr, "User-Edit failed: %d\n", rc);
8440 rc = 1;
8441 }
8442 }else if( strcmp(azArg[1],"delete")==0 ){
8443 if( nArg!=3 ){
8444 raw_printf(stderr, "Usage: .user delete USER\n");
8445 rc = 1;
8446 goto meta_command_exit;
8447 }
8448 rc = sqlite3_user_delete(p->db, azArg[2]);
8449 if( rc ){
8450 raw_printf(stderr, "User-Delete failed: %d\n", rc);
8451 rc = 1;
8452 }
8453 }else{
8454 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
8455 rc = 1;
8456 goto meta_command_exit;
8457 }
8458 }else
8459#endif /* SQLITE_USER_AUTHENTICATION */
8460
8461 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
8462 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
8463 sqlite3_libversion(), sqlite3_sourceid());
drh0ed2fd82018-01-16 20:05:27 +00008464#if SQLITE_HAVE_ZLIB
8465 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
8466#endif
8467#define CTIMEOPT_VAL_(opt) #opt
8468#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
8469#if defined(__clang__) && defined(__clang_major__)
8470 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
8471 CTIMEOPT_VAL(__clang_minor__) "."
8472 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
8473#elif defined(_MSC_VER)
8474 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
8475#elif defined(__GNUC__) && defined(__VERSION__)
8476 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
8477#endif
drh2ce15c32017-07-11 13:34:40 +00008478 }else
8479
8480 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
8481 const char *zDbName = nArg==2 ? azArg[1] : "main";
8482 sqlite3_vfs *pVfs = 0;
8483 if( p->db ){
8484 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
8485 if( pVfs ){
8486 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
8487 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
8488 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
8489 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
8490 }
8491 }
8492 }else
8493
8494 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
8495 sqlite3_vfs *pVfs;
8496 sqlite3_vfs *pCurrent = 0;
8497 if( p->db ){
8498 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
8499 }
8500 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
8501 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
8502 pVfs==pCurrent ? " <--- CURRENT" : "");
8503 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
8504 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
8505 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
8506 if( pVfs->pNext ){
8507 raw_printf(p->out, "-----------------------------------\n");
8508 }
8509 }
8510 }else
8511
8512 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
8513 const char *zDbName = nArg==2 ? azArg[1] : "main";
8514 char *zVfsName = 0;
8515 if( p->db ){
8516 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
8517 if( zVfsName ){
8518 utf8_printf(p->out, "%s\n", zVfsName);
8519 sqlite3_free(zVfsName);
8520 }
8521 }
8522 }else
8523
8524#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
8525 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
8526 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
8527 }else
8528#endif
8529
8530 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
8531 int j;
8532 assert( nArg<=ArraySize(azArg) );
8533 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
8534 p->colWidth[j-1] = (int)integerValue(azArg[j]);
8535 }
8536 }else
8537
8538 {
8539 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
8540 " \"%s\". Enter \".help\" for help\n", azArg[0]);
8541 rc = 1;
8542 }
8543
8544meta_command_exit:
8545 if( p->outCount ){
8546 p->outCount--;
8547 if( p->outCount==0 ) output_reset(p);
8548 }
8549 return rc;
8550}
8551
8552/*
8553** Return TRUE if a semicolon occurs anywhere in the first N characters
8554** of string z[].
8555*/
8556static int line_contains_semicolon(const char *z, int N){
8557 int i;
8558 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
8559 return 0;
8560}
8561
8562/*
8563** Test to see if a line consists entirely of whitespace.
8564*/
8565static int _all_whitespace(const char *z){
8566 for(; *z; z++){
8567 if( IsSpace(z[0]) ) continue;
8568 if( *z=='/' && z[1]=='*' ){
8569 z += 2;
8570 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
8571 if( *z==0 ) return 0;
8572 z++;
8573 continue;
8574 }
8575 if( *z=='-' && z[1]=='-' ){
8576 z += 2;
8577 while( *z && *z!='\n' ){ z++; }
8578 if( *z==0 ) return 1;
8579 continue;
8580 }
8581 return 0;
8582 }
8583 return 1;
8584}
8585
8586/*
8587** Return TRUE if the line typed in is an SQL command terminator other
8588** than a semi-colon. The SQL Server style "go" command is understood
8589** as is the Oracle "/".
8590*/
8591static int line_is_command_terminator(const char *zLine){
8592 while( IsSpace(zLine[0]) ){ zLine++; };
8593 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
8594 return 1; /* Oracle */
8595 }
8596 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
8597 && _all_whitespace(&zLine[2]) ){
8598 return 1; /* SQL Server */
8599 }
8600 return 0;
8601}
8602
8603/*
drh56f17742018-01-24 01:58:49 +00008604** We need a default sqlite3_complete() implementation to use in case
8605** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
8606** any arbitrary text is a complete SQL statement. This is not very
8607** user-friendly, but it does seem to work.
8608*/
8609#ifdef SQLITE_OMIT_COMPLETE
danc86b23b2018-11-16 14:36:42 +00008610#define sqlite3_complete(x) 1
drh56f17742018-01-24 01:58:49 +00008611#endif
8612
8613/*
drh2ce15c32017-07-11 13:34:40 +00008614** Return true if zSql is a complete SQL statement. Return false if it
8615** ends in the middle of a string literal or C-style comment.
8616*/
8617static int line_is_complete(char *zSql, int nSql){
8618 int rc;
8619 if( zSql==0 ) return 1;
8620 zSql[nSql] = ';';
8621 zSql[nSql+1] = 0;
8622 rc = sqlite3_complete(zSql);
8623 zSql[nSql] = 0;
8624 return rc;
8625}
8626
8627/*
drhfc29a862018-05-11 19:11:18 +00008628** Run a single line of SQL. Return the number of errors.
drh2ce15c32017-07-11 13:34:40 +00008629*/
8630static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
8631 int rc;
8632 char *zErrMsg = 0;
8633
8634 open_db(p, 0);
8635 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drhfc4eeef2019-02-05 19:48:46 +00008636 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
drh2ce15c32017-07-11 13:34:40 +00008637 BEGIN_TIMER;
drha10b9992018-03-09 15:24:33 +00008638 rc = shell_exec(p, zSql, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00008639 END_TIMER;
8640 if( rc || zErrMsg ){
8641 char zPrefix[100];
8642 if( in!=0 || !stdin_is_interactive ){
8643 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
8644 "Error: near line %d:", startline);
8645 }else{
8646 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
8647 }
8648 if( zErrMsg!=0 ){
8649 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
8650 sqlite3_free(zErrMsg);
8651 zErrMsg = 0;
8652 }else{
8653 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
8654 }
8655 return 1;
8656 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
8657 raw_printf(p->out, "changes: %3d total_changes: %d\n",
8658 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
8659 }
8660 return 0;
8661}
8662
8663
8664/*
8665** Read input from *in and process it. If *in==0 then input
8666** is interactive - the user is typing it it. Otherwise, input
8667** is coming from a file or device. A prompt is issued and history
8668** is saved only if input is interactive. An interrupt signal will
8669** cause this routine to exit immediately, unless input is interactive.
8670**
8671** Return the number of errors.
8672*/
drh60379d42018-12-13 18:30:01 +00008673static int process_input(ShellState *p){
drh2ce15c32017-07-11 13:34:40 +00008674 char *zLine = 0; /* A single input line */
8675 char *zSql = 0; /* Accumulated SQL text */
8676 int nLine; /* Length of current line */
8677 int nSql = 0; /* Bytes of zSql[] used */
8678 int nAlloc = 0; /* Allocated zSql[] space */
8679 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
8680 int rc; /* Error code */
8681 int errCnt = 0; /* Number of errors seen */
drh2ce15c32017-07-11 13:34:40 +00008682 int startline = 0; /* Line number for start of current input */
8683
drh2c8ee022018-12-13 18:59:30 +00008684 p->lineno = 0;
drh60379d42018-12-13 18:30:01 +00008685 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
drh2ce15c32017-07-11 13:34:40 +00008686 fflush(p->out);
drh60379d42018-12-13 18:30:01 +00008687 zLine = one_input_line(p->in, zLine, nSql>0);
drh2ce15c32017-07-11 13:34:40 +00008688 if( zLine==0 ){
8689 /* End of input */
drh60379d42018-12-13 18:30:01 +00008690 if( p->in==0 && stdin_is_interactive ) printf("\n");
drh2ce15c32017-07-11 13:34:40 +00008691 break;
8692 }
8693 if( seenInterrupt ){
drh60379d42018-12-13 18:30:01 +00008694 if( p->in!=0 ) break;
drh2ce15c32017-07-11 13:34:40 +00008695 seenInterrupt = 0;
8696 }
drh2c8ee022018-12-13 18:59:30 +00008697 p->lineno++;
drh2ce15c32017-07-11 13:34:40 +00008698 if( nSql==0 && _all_whitespace(zLine) ){
8699 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
8700 continue;
8701 }
drh1615c372018-05-12 23:56:22 +00008702 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00008703 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh1615c372018-05-12 23:56:22 +00008704 if( zLine[0]=='.' ){
8705 rc = do_meta_command(zLine, p);
8706 if( rc==2 ){ /* exit requested */
8707 break;
8708 }else if( rc ){
8709 errCnt++;
8710 }
drh2ce15c32017-07-11 13:34:40 +00008711 }
8712 continue;
8713 }
8714 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
8715 memcpy(zLine,";",2);
8716 }
8717 nLine = strlen30(zLine);
8718 if( nSql+nLine+2>=nAlloc ){
8719 nAlloc = nSql+nLine+100;
8720 zSql = realloc(zSql, nAlloc);
drh4b5345c2018-04-24 13:07:40 +00008721 if( zSql==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008722 }
8723 nSqlPrior = nSql;
8724 if( nSql==0 ){
8725 int i;
8726 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
8727 assert( nAlloc>0 && zSql!=0 );
8728 memcpy(zSql, zLine+i, nLine+1-i);
drh2c8ee022018-12-13 18:59:30 +00008729 startline = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00008730 nSql = nLine-i;
8731 }else{
8732 zSql[nSql++] = '\n';
8733 memcpy(zSql+nSql, zLine, nLine+1);
8734 nSql += nLine;
8735 }
8736 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
8737 && sqlite3_complete(zSql) ){
drh60379d42018-12-13 18:30:01 +00008738 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00008739 nSql = 0;
8740 if( p->outCount ){
8741 output_reset(p);
8742 p->outCount = 0;
drh13c20932018-01-10 21:41:55 +00008743 }else{
8744 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00008745 }
8746 }else if( nSql && _all_whitespace(zSql) ){
8747 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
8748 nSql = 0;
8749 }
8750 }
8751 if( nSql && !_all_whitespace(zSql) ){
drh60379d42018-12-13 18:30:01 +00008752 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00008753 }
8754 free(zSql);
8755 free(zLine);
8756 return errCnt>0;
8757}
8758
8759/*
8760** Return a pathname which is the user's home directory. A
8761** 0 return indicates an error of some kind.
8762*/
8763static char *find_home_dir(int clearFlag){
8764 static char *home_dir = NULL;
8765 if( clearFlag ){
8766 free(home_dir);
8767 home_dir = 0;
8768 return 0;
8769 }
8770 if( home_dir ) return home_dir;
8771
8772#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
8773 && !defined(__RTP__) && !defined(_WRS_KERNEL)
8774 {
8775 struct passwd *pwent;
8776 uid_t uid = getuid();
8777 if( (pwent=getpwuid(uid)) != NULL) {
8778 home_dir = pwent->pw_dir;
8779 }
8780 }
8781#endif
8782
8783#if defined(_WIN32_WCE)
8784 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
8785 */
8786 home_dir = "/";
8787#else
8788
8789#if defined(_WIN32) || defined(WIN32)
8790 if (!home_dir) {
8791 home_dir = getenv("USERPROFILE");
8792 }
8793#endif
8794
8795 if (!home_dir) {
8796 home_dir = getenv("HOME");
8797 }
8798
8799#if defined(_WIN32) || defined(WIN32)
8800 if (!home_dir) {
8801 char *zDrive, *zPath;
8802 int n;
8803 zDrive = getenv("HOMEDRIVE");
8804 zPath = getenv("HOMEPATH");
8805 if( zDrive && zPath ){
8806 n = strlen30(zDrive) + strlen30(zPath) + 1;
8807 home_dir = malloc( n );
8808 if( home_dir==0 ) return 0;
8809 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
8810 return home_dir;
8811 }
8812 home_dir = "c:\\";
8813 }
8814#endif
8815
8816#endif /* !_WIN32_WCE */
8817
8818 if( home_dir ){
8819 int n = strlen30(home_dir) + 1;
8820 char *z = malloc( n );
8821 if( z ) memcpy(z, home_dir, n);
8822 home_dir = z;
8823 }
8824
8825 return home_dir;
8826}
8827
8828/*
8829** Read input from the file given by sqliterc_override. Or if that
8830** parameter is NULL, take input from ~/.sqliterc
8831**
8832** Returns the number of errors.
8833*/
8834static void process_sqliterc(
8835 ShellState *p, /* Configuration data */
8836 const char *sqliterc_override /* Name of config file. NULL to use default */
8837){
8838 char *home_dir = NULL;
8839 const char *sqliterc = sqliterc_override;
8840 char *zBuf = 0;
drh60379d42018-12-13 18:30:01 +00008841 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00008842 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00008843
8844 if (sqliterc == NULL) {
8845 home_dir = find_home_dir(0);
8846 if( home_dir==0 ){
8847 raw_printf(stderr, "-- warning: cannot find home directory;"
8848 " cannot read ~/.sqliterc\n");
8849 return;
8850 }
drh2ce15c32017-07-11 13:34:40 +00008851 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
8852 sqliterc = zBuf;
8853 }
drh60379d42018-12-13 18:30:01 +00008854 p->in = fopen(sqliterc,"rb");
8855 if( p->in ){
drh2ce15c32017-07-11 13:34:40 +00008856 if( stdin_is_interactive ){
8857 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
8858 }
drh60379d42018-12-13 18:30:01 +00008859 process_input(p);
8860 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00008861 }
drh60379d42018-12-13 18:30:01 +00008862 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00008863 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00008864 sqlite3_free(zBuf);
8865}
8866
8867/*
8868** Show available command line options
8869*/
8870static const char zOptions[] =
drhda57d962018-03-05 19:34:05 +00008871#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhad7fd5d2018-03-05 20:21:50 +00008872 " -A ARGS... run \".archive ARGS\" and exit\n"
drhda57d962018-03-05 19:34:05 +00008873#endif
drh3baed312018-03-08 18:14:41 +00008874 " -append append the database to the end of the file\n"
drh2ce15c32017-07-11 13:34:40 +00008875 " -ascii set output mode to 'ascii'\n"
8876 " -bail stop after hitting an error\n"
8877 " -batch force batch I/O\n"
8878 " -column set output mode to 'column'\n"
8879 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
8880 " -csv set output mode to 'csv'\n"
drh6ca64482019-01-22 16:06:20 +00008881#if defined(SQLITE_ENABLE_DESERIALIZE)
8882 " -deserialize open the database using sqlite3_deserialize()\n"
8883#endif
drh2ce15c32017-07-11 13:34:40 +00008884 " -echo print commands before execution\n"
8885 " -init FILENAME read/process named file\n"
8886 " -[no]header turn headers on or off\n"
8887#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8888 " -heap SIZE Size of heap for memsys3 or memsys5\n"
8889#endif
8890 " -help show this message\n"
8891 " -html set output mode to HTML\n"
8892 " -interactive force interactive I/O\n"
8893 " -line set output mode to 'line'\n"
8894 " -list set output mode to 'list'\n"
8895 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh6ca64482019-01-22 16:06:20 +00008896#if defined(SQLITE_ENABLE_DESERIALIZE)
8897 " -maxsize N maximum size for a --deserialize database\n"
8898#endif
drhaf482572019-02-04 19:52:39 +00008899 " -memtrace trace all memory allocations and deallocations\n"
drh2ce15c32017-07-11 13:34:40 +00008900 " -mmap N default mmap size set to N\n"
8901#ifdef SQLITE_ENABLE_MULTIPLEX
8902 " -multiplex enable the multiplexor VFS\n"
8903#endif
8904 " -newline SEP set output row separator. Default: '\\n'\n"
8905 " -nullvalue TEXT set text string for NULL values. Default ''\n"
8906 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
8907 " -quote set output mode to 'quote'\n"
drhee269a62018-02-14 23:27:43 +00008908 " -readonly open the database read-only\n"
drh2ce15c32017-07-11 13:34:40 +00008909 " -separator SEP set output column separator. Default: '|'\n"
drha90d84f2018-04-18 15:21:13 +00008910#ifdef SQLITE_ENABLE_SORTER_REFERENCES
8911 " -sorterref SIZE sorter references threshold size\n"
8912#endif
drh2ce15c32017-07-11 13:34:40 +00008913 " -stats print memory stats before each finalize\n"
8914 " -version show SQLite version\n"
8915 " -vfs NAME use NAME as the default VFS\n"
8916#ifdef SQLITE_ENABLE_VFSTRACE
8917 " -vfstrace enable tracing of all VFS calls\n"
8918#endif
drh3baed312018-03-08 18:14:41 +00008919#ifdef SQLITE_HAVE_ZLIB
8920 " -zip open the file as a ZIP Archive\n"
8921#endif
drh2ce15c32017-07-11 13:34:40 +00008922;
8923static void usage(int showDetail){
8924 utf8_printf(stderr,
8925 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8926 "FILENAME is the name of an SQLite database. A new database is created\n"
8927 "if the file does not previously exist.\n", Argv0);
8928 if( showDetail ){
8929 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
8930 }else{
8931 raw_printf(stderr, "Use the -help option for additional information\n");
8932 }
8933 exit(1);
8934}
8935
8936/*
drhe7df8922018-04-18 10:44:58 +00008937** Internal check: Verify that the SQLite is uninitialized. Print a
8938** error message if it is initialized.
8939*/
8940static void verify_uninitialized(void){
8941 if( sqlite3_config(-1)==SQLITE_MISUSE ){
drh8e02a182018-05-30 07:24:41 +00008942 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
drhe7df8922018-04-18 10:44:58 +00008943 " initialization.\n");
8944 }
8945}
8946
8947/*
drh2ce15c32017-07-11 13:34:40 +00008948** Initialize the state information in data
8949*/
8950static void main_init(ShellState *data) {
8951 memset(data, 0, sizeof(*data));
8952 data->normalMode = data->cMode = data->mode = MODE_List;
8953 data->autoExplain = 1;
8954 memcpy(data->colSeparator,SEP_Column, 2);
8955 memcpy(data->rowSeparator,SEP_Row, 2);
8956 data->showHeader = 0;
8957 data->shellFlgs = SHFLG_Lookaside;
drhe7df8922018-04-18 10:44:58 +00008958 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00008959 sqlite3_config(SQLITE_CONFIG_URI, 1);
8960 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
8961 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
8962 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
8963 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
8964}
8965
8966/*
8967** Output text to the console in a font that attracts extra attention.
8968*/
8969#ifdef _WIN32
8970static void printBold(const char *zText){
8971 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
8972 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
8973 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
8974 SetConsoleTextAttribute(out,
8975 FOREGROUND_RED|FOREGROUND_INTENSITY
8976 );
8977 printf("%s", zText);
8978 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
8979}
8980#else
8981static void printBold(const char *zText){
8982 printf("\033[1m%s\033[0m", zText);
8983}
8984#endif
8985
8986/*
8987** Get the argument to an --option. Throw an error and die if no argument
8988** is available.
8989*/
8990static char *cmdline_option_value(int argc, char **argv, int i){
8991 if( i==argc ){
8992 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
8993 argv[0], argv[argc-1]);
8994 exit(1);
8995 }
8996 return argv[i];
8997}
8998
8999#ifndef SQLITE_SHELL_IS_UTF8
9000# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
9001# define SQLITE_SHELL_IS_UTF8 (0)
9002# else
9003# define SQLITE_SHELL_IS_UTF8 (1)
9004# endif
9005#endif
9006
9007#if SQLITE_SHELL_IS_UTF8
9008int SQLITE_CDECL main(int argc, char **argv){
9009#else
9010int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
9011 char **argv;
9012#endif
9013 char *zErrMsg = 0;
9014 ShellState data;
9015 const char *zInitFile = 0;
9016 int i;
9017 int rc = 0;
9018 int warnInmemoryDb = 0;
9019 int readStdin = 1;
9020 int nCmd = 0;
9021 char **azCmd = 0;
dan16a47422018-04-18 09:16:11 +00009022 const char *zVfs = 0; /* Value of -vfs command-line option */
drh1f22f622018-05-17 13:29:14 +00009023#if !SQLITE_SHELL_IS_UTF8
9024 char **argvToFree = 0;
9025 int argcToFree = 0;
9026#endif
drh2ce15c32017-07-11 13:34:40 +00009027
9028 setBinaryMode(stdin, 0);
9029 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
9030 stdin_is_interactive = isatty(0);
9031 stdout_is_console = isatty(1);
9032
mistachkin1e8487d2018-07-22 06:25:35 +00009033#if !defined(_WIN32_WCE)
9034 if( getenv("SQLITE_DEBUG_BREAK") ){
9035 if( isatty(0) && isatty(2) ){
9036 fprintf(stderr,
9037 "attach debugger to process %d and press any key to continue.\n",
9038 GETPID());
9039 fgetc(stdin);
9040 }else{
9041#if defined(_WIN32) || defined(WIN32)
9042 DebugBreak();
9043#elif defined(SIGTRAP)
9044 raise(SIGTRAP);
9045#endif
9046 }
9047 }
9048#endif
9049
drh2ce15c32017-07-11 13:34:40 +00009050#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00009051 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00009052 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
9053 sqlite3_sourceid(), SQLITE_SOURCE_ID);
9054 exit(1);
9055 }
9056#endif
9057 main_init(&data);
drh501ea052018-02-15 01:03:37 +00009058
9059 /* On Windows, we must translate command-line arguments into UTF-8.
9060 ** The SQLite memory allocator subsystem has to be enabled in order to
9061 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
9062 ** subsequent sqlite3_config() calls will work. So copy all results into
9063 ** memory that does not come from the SQLite memory allocator.
9064 */
drh4b18c1d2018-02-04 20:33:13 +00009065#if !SQLITE_SHELL_IS_UTF8
drh501ea052018-02-15 01:03:37 +00009066 sqlite3_initialize();
drh1f22f622018-05-17 13:29:14 +00009067 argvToFree = malloc(sizeof(argv[0])*argc*2);
9068 argcToFree = argc;
9069 argv = argvToFree + argc;
drh4b5345c2018-04-24 13:07:40 +00009070 if( argv==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009071 for(i=0; i<argc; i++){
drh501ea052018-02-15 01:03:37 +00009072 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
9073 int n;
drh4b5345c2018-04-24 13:07:40 +00009074 if( z==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00009075 n = (int)strlen(z);
9076 argv[i] = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00009077 if( argv[i]==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00009078 memcpy(argv[i], z, n+1);
drh1f22f622018-05-17 13:29:14 +00009079 argvToFree[i] = argv[i];
drh501ea052018-02-15 01:03:37 +00009080 sqlite3_free(z);
drh2ce15c32017-07-11 13:34:40 +00009081 }
drh501ea052018-02-15 01:03:37 +00009082 sqlite3_shutdown();
drh2ce15c32017-07-11 13:34:40 +00009083#endif
drh501ea052018-02-15 01:03:37 +00009084
drh2ce15c32017-07-11 13:34:40 +00009085 assert( argc>=1 && argv && argv[0] );
9086 Argv0 = argv[0];
9087
9088 /* Make sure we have a valid signal handler early, before anything
9089 ** else is done.
9090 */
9091#ifdef SIGINT
9092 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00009093#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
9094 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00009095#endif
9096
9097#ifdef SQLITE_SHELL_DBNAME_PROC
9098 {
9099 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
9100 ** of a C-function that will provide the name of the database file. Use
9101 ** this compile-time option to embed this shell program in larger
9102 ** applications. */
9103 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
9104 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
9105 warnInmemoryDb = 0;
9106 }
9107#endif
9108
9109 /* Do an initial pass through the command-line argument to locate
9110 ** the name of the database file, the name of the initialization file,
9111 ** the size of the alternative malloc heap,
9112 ** and the first command to execute.
9113 */
drhe7df8922018-04-18 10:44:58 +00009114 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00009115 for(i=1; i<argc; i++){
9116 char *z;
9117 z = argv[i];
9118 if( z[0]!='-' ){
9119 if( data.zDbFilename==0 ){
9120 data.zDbFilename = z;
9121 }else{
9122 /* Excesss arguments are interpreted as SQL (or dot-commands) and
9123 ** mean that nothing is read from stdin */
9124 readStdin = 0;
9125 nCmd++;
9126 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
drh4b5345c2018-04-24 13:07:40 +00009127 if( azCmd==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009128 azCmd[nCmd-1] = z;
9129 }
9130 }
9131 if( z[1]=='-' ) z++;
9132 if( strcmp(z,"-separator")==0
9133 || strcmp(z,"-nullvalue")==0
9134 || strcmp(z,"-newline")==0
9135 || strcmp(z,"-cmd")==0
9136 ){
9137 (void)cmdline_option_value(argc, argv, ++i);
9138 }else if( strcmp(z,"-init")==0 ){
9139 zInitFile = cmdline_option_value(argc, argv, ++i);
9140 }else if( strcmp(z,"-batch")==0 ){
9141 /* Need to check for batch mode here to so we can avoid printing
9142 ** informational messages (like from process_sqliterc) before
9143 ** we do the actual processing of arguments later in a second pass.
9144 */
9145 stdin_is_interactive = 0;
9146 }else if( strcmp(z,"-heap")==0 ){
9147#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
9148 const char *zSize;
9149 sqlite3_int64 szHeap;
9150
9151 zSize = cmdline_option_value(argc, argv, ++i);
9152 szHeap = integerValue(zSize);
9153 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
9154 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
9155#else
9156 (void)cmdline_option_value(argc, argv, ++i);
9157#endif
drh2ce15c32017-07-11 13:34:40 +00009158 }else if( strcmp(z,"-pagecache")==0 ){
9159 int n, sz;
9160 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
9161 if( sz>70000 ) sz = 70000;
9162 if( sz<0 ) sz = 0;
9163 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
9164 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
9165 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
9166 data.shellFlgs |= SHFLG_Pagecache;
9167 }else if( strcmp(z,"-lookaside")==0 ){
9168 int n, sz;
9169 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
9170 if( sz<0 ) sz = 0;
9171 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
9172 if( n<0 ) n = 0;
9173 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
9174 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
9175#ifdef SQLITE_ENABLE_VFSTRACE
9176 }else if( strcmp(z,"-vfstrace")==0 ){
9177 extern int vfstrace_register(
9178 const char *zTraceName,
9179 const char *zOldVfsName,
9180 int (*xOut)(const char*,void*),
9181 void *pOutArg,
9182 int makeDefault
9183 );
9184 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
9185#endif
9186#ifdef SQLITE_ENABLE_MULTIPLEX
9187 }else if( strcmp(z,"-multiplex")==0 ){
9188 extern int sqlite3_multiple_initialize(const char*,int);
9189 sqlite3_multiplex_initialize(0, 1);
9190#endif
9191 }else if( strcmp(z,"-mmap")==0 ){
9192 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
9193 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drha90d84f2018-04-18 15:21:13 +00009194#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9195 }else if( strcmp(z,"-sorterref")==0 ){
9196 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
9197 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
9198#endif
drh2ce15c32017-07-11 13:34:40 +00009199 }else if( strcmp(z,"-vfs")==0 ){
dan16a47422018-04-18 09:16:11 +00009200 zVfs = cmdline_option_value(argc, argv, ++i);
drh3baed312018-03-08 18:14:41 +00009201#ifdef SQLITE_HAVE_ZLIB
drh8682e122018-01-07 20:38:10 +00009202 }else if( strcmp(z,"-zip")==0 ){
9203 data.openMode = SHELL_OPEN_ZIPFILE;
9204#endif
9205 }else if( strcmp(z,"-append")==0 ){
9206 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +00009207#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00009208 }else if( strcmp(z,"-deserialize")==0 ){
9209 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +00009210 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
9211 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +00009212#endif
drhee269a62018-02-14 23:27:43 +00009213 }else if( strcmp(z,"-readonly")==0 ){
9214 data.openMode = SHELL_OPEN_READONLY;
drhda57d962018-03-05 19:34:05 +00009215#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00009216 }else if( strncmp(z, "-A",2)==0 ){
drhda57d962018-03-05 19:34:05 +00009217 /* All remaining command-line arguments are passed to the ".archive"
9218 ** command, so ignore them */
9219 break;
9220#endif
drh50b910a2019-01-21 14:55:03 +00009221 }else if( strcmp(z, "-memtrace")==0 ){
9222 sqlite3MemTraceActivate(stderr);
drh2ce15c32017-07-11 13:34:40 +00009223 }
9224 }
drhe7df8922018-04-18 10:44:58 +00009225 verify_uninitialized();
9226
dan16a47422018-04-18 09:16:11 +00009227
drhd11b8f62018-04-25 13:27:07 +00009228#ifdef SQLITE_SHELL_INIT_PROC
9229 {
9230 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
9231 ** of a C-function that will perform initialization actions on SQLite that
9232 ** occur just before or after sqlite3_initialize(). Use this compile-time
9233 ** option to embed this shell program in larger applications. */
9234 extern void SQLITE_SHELL_INIT_PROC(void);
9235 SQLITE_SHELL_INIT_PROC();
9236 }
9237#else
dan16a47422018-04-18 09:16:11 +00009238 /* All the sqlite3_config() calls have now been made. So it is safe
9239 ** to call sqlite3_initialize() and process any command line -vfs option. */
9240 sqlite3_initialize();
drhd11b8f62018-04-25 13:27:07 +00009241#endif
9242
dan16a47422018-04-18 09:16:11 +00009243 if( zVfs ){
9244 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
9245 if( pVfs ){
9246 sqlite3_vfs_register(pVfs, 1);
9247 }else{
9248 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
9249 exit(1);
9250 }
9251 }
9252
drh2ce15c32017-07-11 13:34:40 +00009253 if( data.zDbFilename==0 ){
9254#ifndef SQLITE_OMIT_MEMORYDB
9255 data.zDbFilename = ":memory:";
9256 warnInmemoryDb = argc==1;
9257#else
9258 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
9259 return 1;
9260#endif
9261 }
9262 data.out = stdout;
drh8682e122018-01-07 20:38:10 +00009263 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +00009264
9265 /* Go ahead and open the database file if it already exists. If the
9266 ** file does not exist, delay opening it. This prevents empty database
9267 ** files from being created if a user mistypes the database name argument
9268 ** to the sqlite command-line tool.
9269 */
9270 if( access(data.zDbFilename, 0)==0 ){
9271 open_db(&data, 0);
9272 }
9273
9274 /* Process the initialization file if there is one. If no -init option
9275 ** is given on the command line, look for a file named ~/.sqliterc and
9276 ** try to process it.
9277 */
9278 process_sqliterc(&data,zInitFile);
9279
9280 /* Make a second pass through the command-line argument and set
9281 ** options. This second pass is delayed until after the initialization
9282 ** file is processed so that the command-line arguments will override
9283 ** settings in the initialization file.
9284 */
9285 for(i=1; i<argc; i++){
9286 char *z = argv[i];
9287 if( z[0]!='-' ) continue;
9288 if( z[1]=='-' ){ z++; }
9289 if( strcmp(z,"-init")==0 ){
9290 i++;
9291 }else if( strcmp(z,"-html")==0 ){
9292 data.mode = MODE_Html;
9293 }else if( strcmp(z,"-list")==0 ){
9294 data.mode = MODE_List;
9295 }else if( strcmp(z,"-quote")==0 ){
9296 data.mode = MODE_Quote;
9297 }else if( strcmp(z,"-line")==0 ){
9298 data.mode = MODE_Line;
9299 }else if( strcmp(z,"-column")==0 ){
9300 data.mode = MODE_Column;
9301 }else if( strcmp(z,"-csv")==0 ){
9302 data.mode = MODE_Csv;
9303 memcpy(data.colSeparator,",",2);
drh3baed312018-03-08 18:14:41 +00009304#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00009305 }else if( strcmp(z,"-zip")==0 ){
9306 data.openMode = SHELL_OPEN_ZIPFILE;
9307#endif
9308 }else if( strcmp(z,"-append")==0 ){
9309 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +00009310#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00009311 }else if( strcmp(z,"-deserialize")==0 ){
9312 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +00009313 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
9314 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +00009315#endif
drh4aafe592018-03-23 16:08:30 +00009316 }else if( strcmp(z,"-readonly")==0 ){
9317 data.openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +00009318 }else if( strcmp(z,"-ascii")==0 ){
9319 data.mode = MODE_Ascii;
9320 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
9321 SEP_Unit);
9322 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
9323 SEP_Record);
9324 }else if( strcmp(z,"-separator")==0 ){
9325 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
9326 "%s",cmdline_option_value(argc,argv,++i));
9327 }else if( strcmp(z,"-newline")==0 ){
9328 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
9329 "%s",cmdline_option_value(argc,argv,++i));
9330 }else if( strcmp(z,"-nullvalue")==0 ){
9331 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
9332 "%s",cmdline_option_value(argc,argv,++i));
9333 }else if( strcmp(z,"-header")==0 ){
9334 data.showHeader = 1;
9335 }else if( strcmp(z,"-noheader")==0 ){
9336 data.showHeader = 0;
9337 }else if( strcmp(z,"-echo")==0 ){
9338 ShellSetFlag(&data, SHFLG_Echo);
9339 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +00009340 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +00009341 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +00009342 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +00009343 }else if( strcmp(z,"-stats")==0 ){
9344 data.statsOn = 1;
9345 }else if( strcmp(z,"-scanstats")==0 ){
9346 data.scanstatsOn = 1;
9347 }else if( strcmp(z,"-backslash")==0 ){
9348 /* Undocumented command-line option: -backslash
9349 ** Causes C-style backslash escapes to be evaluated in SQL statements
9350 ** prior to sending the SQL into SQLite. Useful for injecting
9351 ** crazy bytes in the middle of SQL statements for testing and debugging.
9352 */
9353 ShellSetFlag(&data, SHFLG_Backslash);
9354 }else if( strcmp(z,"-bail")==0 ){
9355 bail_on_error = 1;
9356 }else if( strcmp(z,"-version")==0 ){
9357 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
9358 return 0;
9359 }else if( strcmp(z,"-interactive")==0 ){
9360 stdin_is_interactive = 1;
9361 }else if( strcmp(z,"-batch")==0 ){
9362 stdin_is_interactive = 0;
9363 }else if( strcmp(z,"-heap")==0 ){
9364 i++;
drh2ce15c32017-07-11 13:34:40 +00009365 }else if( strcmp(z,"-pagecache")==0 ){
9366 i+=2;
9367 }else if( strcmp(z,"-lookaside")==0 ){
9368 i+=2;
9369 }else if( strcmp(z,"-mmap")==0 ){
9370 i++;
drh50b910a2019-01-21 14:55:03 +00009371 }else if( strcmp(z,"-memtrace")==0 ){
9372 i++;
drha90d84f2018-04-18 15:21:13 +00009373#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9374 }else if( strcmp(z,"-sorterref")==0 ){
9375 i++;
9376#endif
drh2ce15c32017-07-11 13:34:40 +00009377 }else if( strcmp(z,"-vfs")==0 ){
9378 i++;
9379#ifdef SQLITE_ENABLE_VFSTRACE
9380 }else if( strcmp(z,"-vfstrace")==0 ){
9381 i++;
9382#endif
9383#ifdef SQLITE_ENABLE_MULTIPLEX
9384 }else if( strcmp(z,"-multiplex")==0 ){
9385 i++;
9386#endif
9387 }else if( strcmp(z,"-help")==0 ){
9388 usage(1);
9389 }else if( strcmp(z,"-cmd")==0 ){
9390 /* Run commands that follow -cmd first and separately from commands
9391 ** that simply appear on the command-line. This seems goofy. It would
9392 ** be better if all commands ran in the order that they appear. But
9393 ** we retain the goofy behavior for historical compatibility. */
9394 if( i==argc-1 ) break;
9395 z = cmdline_option_value(argc,argv,++i);
9396 if( z[0]=='.' ){
9397 rc = do_meta_command(z, &data);
9398 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
9399 }else{
9400 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00009401 rc = shell_exec(&data, z, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00009402 if( zErrMsg!=0 ){
9403 utf8_printf(stderr,"Error: %s\n", zErrMsg);
9404 if( bail_on_error ) return rc!=0 ? rc : 1;
9405 }else if( rc!=0 ){
9406 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
9407 if( bail_on_error ) return rc;
9408 }
9409 }
drhda57d962018-03-05 19:34:05 +00009410#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00009411 }else if( strncmp(z, "-A", 2)==0 ){
drhda57d962018-03-05 19:34:05 +00009412 if( nCmd>0 ){
9413 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
9414 " with \"%s\"\n", z);
9415 return 1;
9416 }
drhbe4ccb22018-05-17 20:04:24 +00009417 open_db(&data, OPEN_DB_ZIPFILE);
drh93b77312018-03-05 20:20:22 +00009418 if( z[2] ){
9419 argv[i] = &z[2];
drhd0f9cdc2018-05-17 14:09:06 +00009420 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
drh93b77312018-03-05 20:20:22 +00009421 }else{
drhd0f9cdc2018-05-17 14:09:06 +00009422 arDotCommand(&data, 1, argv+i, argc-i);
drh93b77312018-03-05 20:20:22 +00009423 }
drhda57d962018-03-05 19:34:05 +00009424 readStdin = 0;
9425 break;
9426#endif
drh2ce15c32017-07-11 13:34:40 +00009427 }else{
9428 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
9429 raw_printf(stderr,"Use -help for a list of options.\n");
9430 return 1;
9431 }
9432 data.cMode = data.mode;
9433 }
9434
9435 if( !readStdin ){
9436 /* Run all arguments that do not begin with '-' as if they were separate
9437 ** command-line inputs, except for the argToSkip argument which contains
9438 ** the database filename.
9439 */
9440 for(i=0; i<nCmd; i++){
9441 if( azCmd[i][0]=='.' ){
9442 rc = do_meta_command(azCmd[i], &data);
9443 if( rc ) return rc==2 ? 0 : rc;
9444 }else{
9445 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +00009446 rc = shell_exec(&data, azCmd[i], &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00009447 if( zErrMsg!=0 ){
9448 utf8_printf(stderr,"Error: %s\n", zErrMsg);
9449 return rc!=0 ? rc : 1;
9450 }else if( rc!=0 ){
9451 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
9452 return rc;
9453 }
9454 }
9455 }
9456 free(azCmd);
9457 }else{
9458 /* Run commands received from standard input
9459 */
9460 if( stdin_is_interactive ){
9461 char *zHome;
drha9e4be32018-10-10 18:56:40 +00009462 char *zHistory;
drh2ce15c32017-07-11 13:34:40 +00009463 int nHistory;
9464 printf(
9465 "SQLite version %s %.19s\n" /*extra-version-info*/
9466 "Enter \".help\" for usage hints.\n",
9467 sqlite3_libversion(), sqlite3_sourceid()
9468 );
9469 if( warnInmemoryDb ){
9470 printf("Connected to a ");
9471 printBold("transient in-memory database");
9472 printf(".\nUse \".open FILENAME\" to reopen on a "
9473 "persistent database.\n");
9474 }
drha9e4be32018-10-10 18:56:40 +00009475 zHistory = getenv("SQLITE_HISTORY");
9476 if( zHistory ){
9477 zHistory = strdup(zHistory);
9478 }else if( (zHome = find_home_dir(0))!=0 ){
drh2ce15c32017-07-11 13:34:40 +00009479 nHistory = strlen30(zHome) + 20;
9480 if( (zHistory = malloc(nHistory))!=0 ){
9481 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
9482 }
9483 }
9484 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +00009485#if HAVE_READLINE || HAVE_EDITLINE
9486 rl_attempted_completion_function = readline_completion;
9487#elif HAVE_LINENOISE
9488 linenoiseSetCompletionCallback(linenoise_completion);
9489#endif
drh60379d42018-12-13 18:30:01 +00009490 data.in = 0;
9491 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +00009492 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +00009493 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +00009494 shell_write_history(zHistory);
9495 free(zHistory);
9496 }
9497 }else{
drh60379d42018-12-13 18:30:01 +00009498 data.in = stdin;
9499 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +00009500 }
9501 }
9502 set_table_name(&data, 0);
9503 if( data.db ){
9504 session_close_all(&data);
drh9e804032018-05-18 17:11:50 +00009505 close_db(data.db);
drh2ce15c32017-07-11 13:34:40 +00009506 }
9507 sqlite3_free(data.zFreeOnClose);
9508 find_home_dir(1);
drh536c3452018-01-11 00:38:39 +00009509 output_reset(&data);
9510 data.doXdgOpen = 0;
drh13c20932018-01-10 21:41:55 +00009511 clearTempFile(&data);
drh2ce15c32017-07-11 13:34:40 +00009512#if !SQLITE_SHELL_IS_UTF8
drh1f22f622018-05-17 13:29:14 +00009513 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
9514 free(argvToFree);
drh2ce15c32017-07-11 13:34:40 +00009515#endif
drh9e804032018-05-18 17:11:50 +00009516 /* Clear the global data structure so that valgrind will detect memory
9517 ** leaks */
9518 memset(&data, 0, sizeof(data));
drh2ce15c32017-07-11 13:34:40 +00009519 return rc;
9520}