blob: f906205bffbbcb18474fcabc2e370493ee0e5e82 [file] [log] [blame]
drh2ce15c32017-07-11 13:34:40 +00001/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Warning pragmas copied from msvc.h in the core.
22*/
23#if defined(_MSC_VER)
24#pragma warning(disable : 4054)
25#pragma warning(disable : 4055)
26#pragma warning(disable : 4100)
27#pragma warning(disable : 4127)
28#pragma warning(disable : 4130)
29#pragma warning(disable : 4152)
30#pragma warning(disable : 4189)
31#pragma warning(disable : 4206)
32#pragma warning(disable : 4210)
33#pragma warning(disable : 4232)
34#pragma warning(disable : 4244)
35#pragma warning(disable : 4305)
36#pragma warning(disable : 4306)
37#pragma warning(disable : 4702)
38#pragma warning(disable : 4706)
39#endif /* defined(_MSC_VER) */
40
41/*
42** No support for loadable extensions in VxWorks.
43*/
44#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45# define SQLITE_OMIT_LOAD_EXTENSION 1
46#endif
47
48/*
49** Enable large-file support for fopen() and friends on unix.
50*/
51#ifndef SQLITE_DISABLE_LFS
52# define _LARGE_FILE 1
53# ifndef _FILE_OFFSET_BITS
54# define _FILE_OFFSET_BITS 64
55# endif
56# define _LARGEFILE_SOURCE 1
57#endif
58
59#include <stdlib.h>
60#include <string.h>
61#include <stdio.h>
62#include <assert.h>
63#include "sqlite3.h"
drh1e506b52018-01-05 21:01:37 +000064typedef sqlite3_int64 i64;
65typedef sqlite3_uint64 u64;
drh1fa6d9f2018-01-06 21:46:01 +000066typedef unsigned char u8;
drh2ce15c32017-07-11 13:34:40 +000067#if SQLITE_USER_AUTHENTICATION
68# include "sqlite3userauth.h"
69#endif
70#include <ctype.h>
71#include <stdarg.h>
72
73#if !defined(_WIN32) && !defined(WIN32)
74# include <signal.h>
75# if !defined(__RTP__) && !defined(_WRS_KERNEL)
76# include <pwd.h>
77# endif
mistachkinacae8c32018-01-05 20:08:46 +000078#endif
mistachkin562f0c82018-01-09 00:28:24 +000079#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
drh2ce15c32017-07-11 13:34:40 +000080# include <unistd.h>
mistachkinacae8c32018-01-05 20:08:46 +000081# include <dirent.h>
mistachkin1e8487d2018-07-22 06:25:35 +000082# define GETPID getpid
mistachkin562f0c82018-01-09 00:28:24 +000083# if defined(__MINGW32__)
mistachkinacae8c32018-01-05 20:08:46 +000084# define DIRENT dirent
mistachkin2f74b3c2018-01-05 20:26:06 +000085# ifndef S_ISLNK
86# define S_ISLNK(mode) (0)
87# endif
mistachkinacae8c32018-01-05 20:08:46 +000088# endif
mistachkin1e8487d2018-07-22 06:25:35 +000089#else
90# define GETPID (int)GetCurrentProcessId
drh2ce15c32017-07-11 13:34:40 +000091#endif
mistachkindfdfd8c2018-01-04 22:46:08 +000092#include <sys/types.h>
93#include <sys/stat.h>
drh2ce15c32017-07-11 13:34:40 +000094
95#if HAVE_READLINE
96# include <readline/readline.h>
97# include <readline/history.h>
98#endif
99
100#if HAVE_EDITLINE
101# include <editline/readline.h>
102#endif
103
104#if HAVE_EDITLINE || HAVE_READLINE
105
106# define shell_add_history(X) add_history(X)
107# define shell_read_history(X) read_history(X)
108# define shell_write_history(X) write_history(X)
109# define shell_stifle_history(X) stifle_history(X)
110# define shell_readline(X) readline(X)
111
112#elif HAVE_LINENOISE
113
114# include "linenoise.h"
115# define shell_add_history(X) linenoiseHistoryAdd(X)
116# define shell_read_history(X) linenoiseHistoryLoad(X)
117# define shell_write_history(X) linenoiseHistorySave(X)
118# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
119# define shell_readline(X) linenoise(X)
120
121#else
122
123# define shell_read_history(X)
124# define shell_write_history(X)
125# define shell_stifle_history(X)
126
127# define SHELL_USE_LOCAL_GETLINE 1
128#endif
129
130
131#if defined(_WIN32) || defined(WIN32)
132# include <io.h>
133# include <fcntl.h>
134# define isatty(h) _isatty(h)
135# ifndef access
136# define access(f,m) _access((f),(m))
137# endif
mistachkince2052b2018-03-23 00:31:53 +0000138# ifndef unlink
139# define unlink _unlink
140# endif
drhc5ea2d42019-01-22 16:44:59 +0000141# ifndef strdup
142# define strdup _strdup
143# endif
drh2ce15c32017-07-11 13:34:40 +0000144# undef popen
145# define popen _popen
146# undef pclose
147# define pclose _pclose
148#else
149 /* Make sure isatty() has a prototype. */
150 extern int isatty(int);
151
152# if !defined(__RTP__) && !defined(_WRS_KERNEL)
153 /* popen and pclose are not C89 functions and so are
154 ** sometimes omitted from the <stdio.h> header */
155 extern FILE *popen(const char*,const char*);
156 extern int pclose(FILE*);
157# else
158# define SQLITE_OMIT_POPEN 1
159# endif
160#endif
161
162#if defined(_WIN32_WCE)
163/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
164 * thus we always assume that we have a console. That can be
165 * overridden with the -batch command line option.
166 */
167#define isatty(x) 1
168#endif
169
170/* ctype macros that work with signed characters */
171#define IsSpace(X) isspace((unsigned char)X)
172#define IsDigit(X) isdigit((unsigned char)X)
173#define ToLower(X) (char)tolower((unsigned char)X)
174
175#if defined(_WIN32) || defined(WIN32)
176#include <windows.h>
177
178/* string conversion routines only needed on Win32 */
179extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
180extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
181extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
182extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
183#endif
184
185/* On Windows, we normally run with output mode of TEXT so that \n characters
186** are automatically translated into \r\n. However, this behavior needs
187** to be disabled in some cases (ex: when generating CSV output and when
188** rendering quoted strings that contain \n characters). The following
189** routines take care of that.
190*/
191#if defined(_WIN32) || defined(WIN32)
192static void setBinaryMode(FILE *file, int isOutput){
193 if( isOutput ) fflush(file);
194 _setmode(_fileno(file), _O_BINARY);
195}
196static void setTextMode(FILE *file, int isOutput){
197 if( isOutput ) fflush(file);
198 _setmode(_fileno(file), _O_TEXT);
199}
200#else
201# define setBinaryMode(X,Y)
202# define setTextMode(X,Y)
203#endif
204
205
206/* True if the timer is enabled */
207static int enableTimer = 0;
208
209/* Return the current wall-clock time */
210static sqlite3_int64 timeOfDay(void){
211 static sqlite3_vfs *clockVfs = 0;
212 sqlite3_int64 t;
213 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
214 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
215 clockVfs->xCurrentTimeInt64(clockVfs, &t);
216 }else{
217 double r;
218 clockVfs->xCurrentTime(clockVfs, &r);
219 t = (sqlite3_int64)(r*86400000.0);
220 }
221 return t;
222}
223
224#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
225#include <sys/time.h>
226#include <sys/resource.h>
227
228/* VxWorks does not support getrusage() as far as we can determine */
229#if defined(_WRS_KERNEL) || defined(__RTP__)
230struct rusage {
231 struct timeval ru_utime; /* user CPU time used */
232 struct timeval ru_stime; /* system CPU time used */
233};
234#define getrusage(A,B) memset(B,0,sizeof(*B))
235#endif
236
237/* Saved resource information for the beginning of an operation */
238static struct rusage sBegin; /* CPU time at start */
239static sqlite3_int64 iBegin; /* Wall-clock time at start */
240
241/*
242** Begin timing an operation
243*/
244static void beginTimer(void){
245 if( enableTimer ){
246 getrusage(RUSAGE_SELF, &sBegin);
247 iBegin = timeOfDay();
248 }
249}
250
251/* Return the difference of two time_structs in seconds */
252static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
253 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
254 (double)(pEnd->tv_sec - pStart->tv_sec);
255}
256
257/*
258** Print the timing results.
259*/
260static void endTimer(void){
261 if( enableTimer ){
262 sqlite3_int64 iEnd = timeOfDay();
263 struct rusage sEnd;
264 getrusage(RUSAGE_SELF, &sEnd);
265 printf("Run Time: real %.3f user %f sys %f\n",
266 (iEnd - iBegin)*0.001,
267 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
268 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
269 }
270}
271
272#define BEGIN_TIMER beginTimer()
273#define END_TIMER endTimer()
274#define HAS_TIMER 1
275
276#elif (defined(_WIN32) || defined(WIN32))
277
278/* Saved resource information for the beginning of an operation */
279static HANDLE hProcess;
280static FILETIME ftKernelBegin;
281static FILETIME ftUserBegin;
282static sqlite3_int64 ftWallBegin;
283typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
284 LPFILETIME, LPFILETIME);
285static GETPROCTIMES getProcessTimesAddr = NULL;
286
287/*
288** Check to see if we have timer support. Return 1 if necessary
289** support found (or found previously).
290*/
291static int hasTimer(void){
292 if( getProcessTimesAddr ){
293 return 1;
294 } else {
295 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
296 ** versions. See if the version we are running on has it, and if it
297 ** does, save off a pointer to it and the current process handle.
298 */
299 hProcess = GetCurrentProcess();
300 if( hProcess ){
301 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
302 if( NULL != hinstLib ){
303 getProcessTimesAddr =
304 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
305 if( NULL != getProcessTimesAddr ){
306 return 1;
307 }
308 FreeLibrary(hinstLib);
309 }
310 }
311 }
312 return 0;
313}
314
315/*
316** Begin timing an operation
317*/
318static void beginTimer(void){
319 if( enableTimer && getProcessTimesAddr ){
320 FILETIME ftCreation, ftExit;
321 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
322 &ftKernelBegin,&ftUserBegin);
323 ftWallBegin = timeOfDay();
324 }
325}
326
327/* Return the difference of two FILETIME structs in seconds */
328static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
329 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
330 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
331 return (double) ((i64End - i64Start) / 10000000.0);
332}
333
334/*
335** Print the timing results.
336*/
337static void endTimer(void){
338 if( enableTimer && getProcessTimesAddr){
339 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
340 sqlite3_int64 ftWallEnd = timeOfDay();
341 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
342 printf("Run Time: real %.3f user %f sys %f\n",
343 (ftWallEnd - ftWallBegin)*0.001,
344 timeDiff(&ftUserBegin, &ftUserEnd),
345 timeDiff(&ftKernelBegin, &ftKernelEnd));
346 }
347}
348
349#define BEGIN_TIMER beginTimer()
350#define END_TIMER endTimer()
351#define HAS_TIMER hasTimer()
352
353#else
354#define BEGIN_TIMER
355#define END_TIMER
356#define HAS_TIMER 0
357#endif
358
359/*
360** Used to prevent warnings about unused parameters
361*/
362#define UNUSED_PARAMETER(x) (void)(x)
363
364/*
drh5af06982018-01-10 00:53:55 +0000365** Number of elements in an array
366*/
367#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
368
369/*
drh2ce15c32017-07-11 13:34:40 +0000370** If the following flag is set, then command execution stops
371** at an error if we are not interactive.
372*/
373static int bail_on_error = 0;
374
375/*
376** Threat stdin as an interactive input if the following variable
377** is true. Otherwise, assume stdin is connected to a file or pipe.
378*/
379static int stdin_is_interactive = 1;
380
381/*
382** On Windows systems we have to know if standard output is a console
383** in order to translate UTF-8 into MBCS. The following variable is
384** true if translation is required.
385*/
386static int stdout_is_console = 1;
387
388/*
389** The following is the open SQLite database. We make a pointer
390** to this database a static variable so that it can be accessed
391** by the SIGINT handler to interrupt database processing.
392*/
393static sqlite3 *globalDb = 0;
394
395/*
396** True if an interrupt (Control-C) has been received.
397*/
398static volatile int seenInterrupt = 0;
399
400/*
401** This is the name of our program. It is set in main(), used
402** in a number of other places, mostly for error messages.
403*/
404static char *Argv0;
405
406/*
407** Prompt strings. Initialized in main. Settable with
408** .prompt main continue
409*/
410static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
411static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
412
413/*
414** Render output like fprintf(). Except, if the output is going to the
415** console and if this is running on a Windows machine, translate the
416** output from UTF-8 into MBCS.
417*/
418#if defined(_WIN32) || defined(WIN32)
419void utf8_printf(FILE *out, const char *zFormat, ...){
420 va_list ap;
421 va_start(ap, zFormat);
422 if( stdout_is_console && (out==stdout || out==stderr) ){
423 char *z1 = sqlite3_vmprintf(zFormat, ap);
424 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
425 sqlite3_free(z1);
426 fputs(z2, out);
427 sqlite3_free(z2);
428 }else{
429 vfprintf(out, zFormat, ap);
430 }
431 va_end(ap);
432}
433#elif !defined(utf8_printf)
434# define utf8_printf fprintf
435#endif
436
437/*
438** Render output like fprintf(). This should not be used on anything that
439** includes string formatting (e.g. "%s").
440*/
441#if !defined(raw_printf)
442# define raw_printf fprintf
443#endif
444
drh4b5345c2018-04-24 13:07:40 +0000445/* Indicate out-of-memory and exit. */
446static void shell_out_of_memory(void){
447 raw_printf(stderr,"Error: out of memory\n");
448 exit(1);
449}
450
drh2ce15c32017-07-11 13:34:40 +0000451/*
452** Write I/O traces to the following stream.
453*/
454#ifdef SQLITE_ENABLE_IOTRACE
455static FILE *iotrace = 0;
456#endif
457
458/*
459** This routine works like printf in that its first argument is a
460** format string and subsequent arguments are values to be substituted
461** in place of % fields. The result of formatting this string
462** is written to iotrace.
463*/
464#ifdef SQLITE_ENABLE_IOTRACE
465static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
466 va_list ap;
467 char *z;
468 if( iotrace==0 ) return;
469 va_start(ap, zFormat);
470 z = sqlite3_vmprintf(zFormat, ap);
471 va_end(ap);
472 utf8_printf(iotrace, "%s", z);
473 sqlite3_free(z);
474}
475#endif
476
477/*
478** Output string zUtf to stream pOut as w characters. If w is negative,
479** then right-justify the text. W is the width in UTF-8 characters, not
480** in bytes. This is different from the %*.*s specification in printf
481** since with %*.*s the width is measured in bytes, not characters.
482*/
483static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
484 int i;
485 int n;
486 int aw = w<0 ? -w : w;
487 char zBuf[1000];
488 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
489 for(i=n=0; zUtf[i]; i++){
490 if( (zUtf[i]&0xc0)!=0x80 ){
491 n++;
492 if( n==aw ){
493 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
494 break;
495 }
496 }
497 }
498 if( n>=aw ){
499 utf8_printf(pOut, "%.*s", i, zUtf);
500 }else if( w<0 ){
501 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
502 }else{
503 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
504 }
505}
506
507
508/*
509** Determines if a string is a number of not.
510*/
511static int isNumber(const char *z, int *realnum){
512 if( *z=='-' || *z=='+' ) z++;
513 if( !IsDigit(*z) ){
514 return 0;
515 }
516 z++;
517 if( realnum ) *realnum = 0;
518 while( IsDigit(*z) ){ z++; }
519 if( *z=='.' ){
520 z++;
521 if( !IsDigit(*z) ) return 0;
522 while( IsDigit(*z) ){ z++; }
523 if( realnum ) *realnum = 1;
524 }
525 if( *z=='e' || *z=='E' ){
526 z++;
527 if( *z=='+' || *z=='-' ) z++;
528 if( !IsDigit(*z) ) return 0;
529 while( IsDigit(*z) ){ z++; }
530 if( realnum ) *realnum = 1;
531 }
532 return *z==0;
533}
534
535/*
536** Compute a string length that is limited to what can be stored in
537** lower 30 bits of a 32-bit signed integer.
538*/
539static int strlen30(const char *z){
540 const char *z2 = z;
541 while( *z2 ){ z2++; }
542 return 0x3fffffff & (int)(z2 - z);
543}
544
545/*
546** Return the length of a string in characters. Multibyte UTF8 characters
547** count as a single character.
548*/
549static int strlenChar(const char *z){
550 int n = 0;
551 while( *z ){
552 if( (0xc0&*(z++))!=0x80 ) n++;
553 }
554 return n;
555}
556
557/*
558** This routine reads a line of text from FILE in, stores
559** the text in memory obtained from malloc() and returns a pointer
560** to the text. NULL is returned at end of file, or if malloc()
561** fails.
562**
563** If zLine is not NULL then it is a malloced buffer returned from
564** a previous call to this routine that may be reused.
565*/
566static char *local_getline(char *zLine, FILE *in){
567 int nLine = zLine==0 ? 0 : 100;
568 int n = 0;
569
570 while( 1 ){
571 if( n+100>nLine ){
572 nLine = nLine*2 + 100;
573 zLine = realloc(zLine, nLine);
drh884406b2018-07-29 18:56:35 +0000574 if( zLine==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000575 }
576 if( fgets(&zLine[n], nLine - n, in)==0 ){
577 if( n==0 ){
578 free(zLine);
579 return 0;
580 }
581 zLine[n] = 0;
582 break;
583 }
584 while( zLine[n] ) n++;
585 if( n>0 && zLine[n-1]=='\n' ){
586 n--;
587 if( n>0 && zLine[n-1]=='\r' ) n--;
588 zLine[n] = 0;
589 break;
590 }
591 }
592#if defined(_WIN32) || defined(WIN32)
593 /* For interactive input on Windows systems, translate the
594 ** multi-byte characterset characters into UTF-8. */
595 if( stdin_is_interactive && in==stdin ){
596 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
597 if( zTrans ){
598 int nTrans = strlen30(zTrans)+1;
599 if( nTrans>nLine ){
600 zLine = realloc(zLine, nTrans);
drh884406b2018-07-29 18:56:35 +0000601 if( zLine==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000602 }
603 memcpy(zLine, zTrans, nTrans);
604 sqlite3_free(zTrans);
605 }
606 }
607#endif /* defined(_WIN32) || defined(WIN32) */
608 return zLine;
609}
610
611/*
612** Retrieve a single line of input text.
613**
614** If in==0 then read from standard input and prompt before each line.
615** If isContinuation is true, then a continuation prompt is appropriate.
616** If isContinuation is zero, then the main prompt should be used.
617**
618** If zPrior is not NULL then it is a buffer from a prior call to this
619** routine that can be reused.
620**
621** The result is stored in space obtained from malloc() and must either
622** be freed by the caller or else passed back into this routine via the
623** zPrior argument for reuse.
624*/
625static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
626 char *zPrompt;
627 char *zResult;
628 if( in!=0 ){
629 zResult = local_getline(zPrior, in);
630 }else{
631 zPrompt = isContinuation ? continuePrompt : mainPrompt;
632#if SHELL_USE_LOCAL_GETLINE
633 printf("%s", zPrompt);
634 fflush(stdout);
635 zResult = local_getline(zPrior, stdin);
636#else
637 free(zPrior);
638 zResult = shell_readline(zPrompt);
639 if( zResult && *zResult ) shell_add_history(zResult);
640#endif
641 }
642 return zResult;
643}
drh5af06982018-01-10 00:53:55 +0000644
645
646/*
647** Return the value of a hexadecimal digit. Return -1 if the input
648** is not a hex digit.
649*/
650static int hexDigitValue(char c){
651 if( c>='0' && c<='9' ) return c - '0';
652 if( c>='a' && c<='f' ) return c - 'a' + 10;
653 if( c>='A' && c<='F' ) return c - 'A' + 10;
654 return -1;
655}
656
657/*
658** Interpret zArg as an integer value, possibly with suffixes.
659*/
660static sqlite3_int64 integerValue(const char *zArg){
661 sqlite3_int64 v = 0;
662 static const struct { char *zSuffix; int iMult; } aMult[] = {
663 { "KiB", 1024 },
664 { "MiB", 1024*1024 },
665 { "GiB", 1024*1024*1024 },
666 { "KB", 1000 },
667 { "MB", 1000000 },
668 { "GB", 1000000000 },
669 { "K", 1000 },
670 { "M", 1000000 },
671 { "G", 1000000000 },
672 };
673 int i;
674 int isNeg = 0;
675 if( zArg[0]=='-' ){
676 isNeg = 1;
677 zArg++;
678 }else if( zArg[0]=='+' ){
679 zArg++;
680 }
681 if( zArg[0]=='0' && zArg[1]=='x' ){
682 int x;
683 zArg += 2;
684 while( (x = hexDigitValue(zArg[0]))>=0 ){
685 v = (v<<4) + x;
686 zArg++;
687 }
688 }else{
689 while( IsDigit(zArg[0]) ){
690 v = v*10 + zArg[0] - '0';
691 zArg++;
692 }
693 }
694 for(i=0; i<ArraySize(aMult); i++){
695 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
696 v *= aMult[i].iMult;
697 break;
698 }
699 }
700 return isNeg? -v : v;
701}
702
drh2ce15c32017-07-11 13:34:40 +0000703/*
704** A variable length string to which one can append text.
705*/
706typedef struct ShellText ShellText;
707struct ShellText {
708 char *z;
709 int n;
710 int nAlloc;
711};
712
713/*
714** Initialize and destroy a ShellText object
715*/
716static void initText(ShellText *p){
717 memset(p, 0, sizeof(*p));
718}
719static void freeText(ShellText *p){
720 free(p->z);
721 initText(p);
722}
723
724/* zIn is either a pointer to a NULL-terminated string in memory obtained
725** from malloc(), or a NULL pointer. The string pointed to by zAppend is
726** added to zIn, and the result returned in memory obtained from malloc().
727** zIn, if it was not NULL, is freed.
728**
729** If the third argument, quote, is not '\0', then it is used as a
730** quote character for zAppend.
731*/
732static void appendText(ShellText *p, char const *zAppend, char quote){
733 int len;
734 int i;
735 int nAppend = strlen30(zAppend);
736
737 len = nAppend+p->n+1;
738 if( quote ){
739 len += 2;
740 for(i=0; i<nAppend; i++){
741 if( zAppend[i]==quote ) len++;
742 }
743 }
744
745 if( p->n+len>=p->nAlloc ){
746 p->nAlloc = p->nAlloc*2 + len + 20;
747 p->z = realloc(p->z, p->nAlloc);
drh884406b2018-07-29 18:56:35 +0000748 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000749 }
750
751 if( quote ){
752 char *zCsr = p->z+p->n;
753 *zCsr++ = quote;
754 for(i=0; i<nAppend; i++){
755 *zCsr++ = zAppend[i];
756 if( zAppend[i]==quote ) *zCsr++ = quote;
757 }
758 *zCsr++ = quote;
759 p->n = (int)(zCsr - p->z);
760 *zCsr = '\0';
761 }else{
762 memcpy(p->z+p->n, zAppend, nAppend);
763 p->n += nAppend;
764 p->z[p->n] = '\0';
765 }
766}
767
768/*
769** Attempt to determine if identifier zName needs to be quoted, either
770** because it contains non-alphanumeric characters, or because it is an
771** SQLite keyword. Be conservative in this estimate: When in doubt assume
772** that quoting is required.
773**
774** Return '"' if quoting is required. Return 0 if no quoting is required.
775*/
776static char quoteChar(const char *zName){
drhfc0ec3e2018-04-25 19:02:48 +0000777 int i;
drh2ce15c32017-07-11 13:34:40 +0000778 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
779 for(i=0; zName[i]; i++){
780 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
781 }
drhfc0ec3e2018-04-25 19:02:48 +0000782 return sqlite3_keyword_check(zName, i) ? '"' : 0;
drh2ce15c32017-07-11 13:34:40 +0000783}
784
785/*
drh667a2a22018-01-02 00:04:37 +0000786** Construct a fake object name and column list to describe the structure
787** of the view, virtual table, or table valued function zSchema.zName.
drhceba7922018-01-01 21:28:25 +0000788*/
drh667a2a22018-01-02 00:04:37 +0000789static char *shellFakeSchema(
drhceba7922018-01-01 21:28:25 +0000790 sqlite3 *db, /* The database connection containing the vtab */
791 const char *zSchema, /* Schema of the database holding the vtab */
792 const char *zName /* The name of the virtual table */
793){
794 sqlite3_stmt *pStmt = 0;
795 char *zSql;
drh1d315cf2018-01-01 21:49:43 +0000796 ShellText s;
797 char cQuote;
798 char *zDiv = "(";
drh667a2a22018-01-02 00:04:37 +0000799 int nRow = 0;
drhceba7922018-01-01 21:28:25 +0000800
drh1d315cf2018-01-01 21:49:43 +0000801 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
802 zSchema ? zSchema : "main", zName);
drhceba7922018-01-01 21:28:25 +0000803 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
804 sqlite3_free(zSql);
drh1d315cf2018-01-01 21:49:43 +0000805 initText(&s);
806 if( zSchema ){
807 cQuote = quoteChar(zSchema);
808 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
809 appendText(&s, zSchema, cQuote);
810 appendText(&s, ".", 0);
drhceba7922018-01-01 21:28:25 +0000811 }
drh1d315cf2018-01-01 21:49:43 +0000812 cQuote = quoteChar(zName);
813 appendText(&s, zName, cQuote);
814 while( sqlite3_step(pStmt)==SQLITE_ROW ){
815 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
drh667a2a22018-01-02 00:04:37 +0000816 nRow++;
drh1d315cf2018-01-01 21:49:43 +0000817 appendText(&s, zDiv, 0);
818 zDiv = ",";
819 cQuote = quoteChar(zCol);
820 appendText(&s, zCol, cQuote);
821 }
822 appendText(&s, ")", 0);
drhceba7922018-01-01 21:28:25 +0000823 sqlite3_finalize(pStmt);
drh667a2a22018-01-02 00:04:37 +0000824 if( nRow==0 ){
825 freeText(&s);
826 s.z = 0;
827 }
drh1d315cf2018-01-01 21:49:43 +0000828 return s.z;
drhceba7922018-01-01 21:28:25 +0000829}
830
831/*
drh667a2a22018-01-02 00:04:37 +0000832** SQL function: shell_module_schema(X)
833**
834** Return a fake schema for the table-valued function or eponymous virtual
835** table X.
836*/
837static void shellModuleSchema(
838 sqlite3_context *pCtx,
839 int nVal,
840 sqlite3_value **apVal
841){
842 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
843 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
drhb9685182018-01-17 13:15:23 +0000844 UNUSED_PARAMETER(nVal);
drh667a2a22018-01-02 00:04:37 +0000845 if( zFake ){
dandcfbff92018-01-08 17:05:32 +0000846 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
drh667a2a22018-01-02 00:04:37 +0000847 -1, sqlite3_free);
dandcfbff92018-01-08 17:05:32 +0000848 free(zFake);
drh667a2a22018-01-02 00:04:37 +0000849 }
850}
851
852/*
drh2ce15c32017-07-11 13:34:40 +0000853** SQL function: shell_add_schema(S,X)
854**
855** Add the schema name X to the CREATE statement in S and return the result.
856** Examples:
857**
858** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
859**
860** Also works on
861**
862** CREATE INDEX
863** CREATE UNIQUE INDEX
864** CREATE VIEW
865** CREATE TRIGGER
866** CREATE VIRTUAL TABLE
867**
868** This UDF is used by the .schema command to insert the schema name of
869** attached databases into the middle of the sqlite_master.sql field.
870*/
871static void shellAddSchemaName(
872 sqlite3_context *pCtx,
873 int nVal,
874 sqlite3_value **apVal
875){
876 static const char *aPrefix[] = {
877 "TABLE",
878 "INDEX",
879 "UNIQUE INDEX",
880 "VIEW",
881 "TRIGGER",
882 "VIRTUAL TABLE"
883 };
884 int i = 0;
885 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
886 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
drh667a2a22018-01-02 00:04:37 +0000887 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
drhceba7922018-01-01 21:28:25 +0000888 sqlite3 *db = sqlite3_context_db_handle(pCtx);
drhb9685182018-01-17 13:15:23 +0000889 UNUSED_PARAMETER(nVal);
drh2ce15c32017-07-11 13:34:40 +0000890 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
drh89997982017-07-11 18:11:33 +0000891 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
drh2ce15c32017-07-11 13:34:40 +0000892 int n = strlen30(aPrefix[i]);
893 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
drhceba7922018-01-01 21:28:25 +0000894 char *z = 0;
drh667a2a22018-01-02 00:04:37 +0000895 char *zFake = 0;
drhceba7922018-01-01 21:28:25 +0000896 if( zSchema ){
897 char cQuote = quoteChar(zSchema);
898 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
899 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
900 }else{
901 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
902 }
drh2ce15c32017-07-11 13:34:40 +0000903 }
drh667a2a22018-01-02 00:04:37 +0000904 if( zName
905 && aPrefix[i][0]=='V'
906 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
907 ){
908 if( z==0 ){
dandcfbff92018-01-08 17:05:32 +0000909 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
drh667a2a22018-01-02 00:04:37 +0000910 }else{
dandcfbff92018-01-08 17:05:32 +0000911 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
drh667a2a22018-01-02 00:04:37 +0000912 }
dandcfbff92018-01-08 17:05:32 +0000913 free(zFake);
drhceba7922018-01-01 21:28:25 +0000914 }
915 if( z ){
916 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
917 return;
918 }
drh2ce15c32017-07-11 13:34:40 +0000919 }
920 }
921 }
922 sqlite3_result_value(pCtx, apVal[0]);
923}
924
925/*
926** The source code for several run-time loadable extensions is inserted
927** below by the ../tool/mkshellc.tcl script. Before processing that included
928** code, we need to override some macros to make the included program code
929** work here in the middle of this regular program.
930*/
931#define SQLITE_EXTENSION_INIT1
drh89997982017-07-11 18:11:33 +0000932#define SQLITE_EXTENSION_INIT2(X) (void)(X)
drh2ce15c32017-07-11 13:34:40 +0000933
mistachkinacae8c32018-01-05 20:08:46 +0000934#if defined(_WIN32) && defined(_MSC_VER)
drh03491a12018-01-07 21:58:17 +0000935INCLUDE test_windirent.h
mistachkindfdfd8c2018-01-04 22:46:08 +0000936INCLUDE test_windirent.c
937#define dirent DIRENT
mistachkindfdfd8c2018-01-04 22:46:08 +0000938#endif
drh2ce15c32017-07-11 13:34:40 +0000939INCLUDE ../ext/misc/shathree.c
940INCLUDE ../ext/misc/fileio.c
drh56eb09b2017-07-11 13:59:07 +0000941INCLUDE ../ext/misc/completion.c
drh8682e122018-01-07 20:38:10 +0000942INCLUDE ../ext/misc/appendvfs.c
drh50b910a2019-01-21 14:55:03 +0000943INCLUDE ../ext/misc/memtrace.c
dan72afc3c2017-12-05 18:32:40 +0000944#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +0000945INCLUDE ../ext/misc/zipfile.c
dand1b51d42017-12-16 19:11:26 +0000946INCLUDE ../ext/misc/sqlar.c
dan72afc3c2017-12-05 18:32:40 +0000947#endif
dan43efc182017-12-19 17:42:13 +0000948INCLUDE ../ext/expert/sqlite3expert.h
949INCLUDE ../ext/expert/sqlite3expert.c
drh2ce15c32017-07-11 13:34:40 +0000950
dan68cb86e2019-04-20 20:57:28 +0000951INCLUDE ../ext/misc/dbdata.c
952
drh2ce15c32017-07-11 13:34:40 +0000953#if defined(SQLITE_ENABLE_SESSION)
954/*
955** State information for a single open session
956*/
957typedef struct OpenSession OpenSession;
958struct OpenSession {
959 char *zName; /* Symbolic name for this session */
960 int nFilter; /* Number of xFilter rejection GLOB patterns */
961 char **azFilter; /* Array of xFilter rejection GLOB patterns */
962 sqlite3_session *p; /* The open session */
963};
964#endif
965
966/*
967** Shell output mode information from before ".explain on",
968** saved so that it can be restored by ".explain off"
969*/
970typedef struct SavedModeInfo SavedModeInfo;
971struct SavedModeInfo {
972 int valid; /* Is there legit data in here? */
973 int mode; /* Mode prior to ".explain on" */
974 int showHeader; /* The ".header" setting prior to ".explain on" */
975 int colWidth[100]; /* Column widths prior to ".explain on" */
976};
977
dan43efc182017-12-19 17:42:13 +0000978typedef struct ExpertInfo ExpertInfo;
979struct ExpertInfo {
980 sqlite3expert *pExpert;
981 int bVerbose;
982};
983
drh4b5345c2018-04-24 13:07:40 +0000984/* A single line in the EQP output */
985typedef struct EQPGraphRow EQPGraphRow;
986struct EQPGraphRow {
drhe2ca99c2018-05-02 00:33:43 +0000987 int iEqpId; /* ID for this row */
988 int iParentId; /* ID of the parent row */
drh4b5345c2018-04-24 13:07:40 +0000989 EQPGraphRow *pNext; /* Next row in sequence */
990 char zText[1]; /* Text to display for this row */
991};
992
993/* All EQP output is collected into an instance of the following */
994typedef struct EQPGraph EQPGraph;
995struct EQPGraph {
996 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
997 EQPGraphRow *pLast; /* Last element of the pRow list */
998 char zPrefix[100]; /* Graph prefix */
999};
1000
drh2ce15c32017-07-11 13:34:40 +00001001/*
1002** State information about the database connection is contained in an
1003** instance of the following structure.
1004*/
1005typedef struct ShellState ShellState;
1006struct ShellState {
1007 sqlite3 *db; /* The database */
drh1fa6d9f2018-01-06 21:46:01 +00001008 u8 autoExplain; /* Automatically turn on .explain mode */
1009 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
drhe2ca99c2018-05-02 00:33:43 +00001010 u8 autoEQPtest; /* autoEQP is in test mode */
drhb4e50392019-01-26 15:40:04 +00001011 u8 autoEQPtrace; /* autoEQP is in trace mode */
drh1fa6d9f2018-01-06 21:46:01 +00001012 u8 statsOn; /* True to display memory stats before each finalize */
1013 u8 scanstatsOn; /* True to display scan stats before each finalize */
1014 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
drh13c20932018-01-10 21:41:55 +00001015 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
drh4b5345c2018-04-24 13:07:40 +00001016 u8 nEqpLevel; /* Depth of the EQP output graph */
drh707821f2018-12-05 13:39:06 +00001017 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
drh4b5345c2018-04-24 13:07:40 +00001018 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
drh2ce15c32017-07-11 13:34:40 +00001019 int outCount; /* Revert to stdout when reaching zero */
1020 int cnt; /* Number of records displayed so far */
drh2c8ee022018-12-13 18:59:30 +00001021 int lineno; /* Line number of last line read from in */
drh60379d42018-12-13 18:30:01 +00001022 FILE *in; /* Read commands from this stream */
drh2ce15c32017-07-11 13:34:40 +00001023 FILE *out; /* Write results here */
1024 FILE *traceOut; /* Output for sqlite3_trace() */
1025 int nErr; /* Number of errors seen */
1026 int mode; /* An output mode setting */
drh3c484e82018-01-10 22:27:21 +00001027 int modePrior; /* Saved mode */
drh2ce15c32017-07-11 13:34:40 +00001028 int cMode; /* temporary output mode for the current query */
1029 int normalMode; /* Output mode before ".explain on" */
1030 int writableSchema; /* True if PRAGMA writable_schema=ON */
1031 int showHeader; /* True to show column names in List or Column mode */
1032 int nCheck; /* Number of ".check" commands run */
drh3f83f592019-02-04 14:53:18 +00001033 unsigned nProgress; /* Number of progress callbacks encountered */
1034 unsigned mxProgress; /* Maximum progress callbacks before failing */
1035 unsigned flgProgress; /* Flags for the progress callback */
drh2ce15c32017-07-11 13:34:40 +00001036 unsigned shellFlgs; /* Various flags */
drh6ca64482019-01-22 16:06:20 +00001037 sqlite3_int64 szMax; /* --maxsize argument to .open */
drh2ce15c32017-07-11 13:34:40 +00001038 char *zDestTable; /* Name of destination table when MODE_Insert */
drh13c20932018-01-10 21:41:55 +00001039 char *zTempFile; /* Temporary file that might need deleting */
drh2ce15c32017-07-11 13:34:40 +00001040 char zTestcase[30]; /* Name of current test case */
1041 char colSeparator[20]; /* Column separator character for several modes */
1042 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drh3c484e82018-01-10 22:27:21 +00001043 char colSepPrior[20]; /* Saved column separator */
1044 char rowSepPrior[20]; /* Saved row separator */
drh2ce15c32017-07-11 13:34:40 +00001045 int colWidth[100]; /* Requested width of each column when in column mode*/
1046 int actualWidth[100]; /* Actual width of each column */
1047 char nullValue[20]; /* The text to print when a NULL comes back from
1048 ** the database */
1049 char outfile[FILENAME_MAX]; /* Filename for *out */
1050 const char *zDbFilename; /* name of the database file */
1051 char *zFreeOnClose; /* Filename to free when closing */
1052 const char *zVfs; /* Name of VFS to use */
1053 sqlite3_stmt *pStmt; /* Current statement if any. */
1054 FILE *pLog; /* Write log output here */
1055 int *aiIndent; /* Array of indents used in MODE_Explain */
1056 int nIndent; /* Size of array aiIndent[] */
1057 int iIndent; /* Index of current op in aiIndent[] */
drh4b5345c2018-04-24 13:07:40 +00001058 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
drh2ce15c32017-07-11 13:34:40 +00001059#if defined(SQLITE_ENABLE_SESSION)
1060 int nSession; /* Number of active sessions */
1061 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1062#endif
dan43efc182017-12-19 17:42:13 +00001063 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
drh2ce15c32017-07-11 13:34:40 +00001064};
1065
drh1fa6d9f2018-01-06 21:46:01 +00001066
drhada70452017-12-21 21:02:27 +00001067/* Allowed values for ShellState.autoEQP
1068*/
drhe2ca99c2018-05-02 00:33:43 +00001069#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1070#define AUTOEQP_on 1 /* Automatic EQP is on */
1071#define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1072#define AUTOEQP_full 3 /* Show full EXPLAIN */
drhada70452017-12-21 21:02:27 +00001073
drh1fa6d9f2018-01-06 21:46:01 +00001074/* Allowed values for ShellState.openMode
1075*/
drh60f34ae2018-10-30 13:19:49 +00001076#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1077#define SHELL_OPEN_NORMAL 1 /* Normal database file */
1078#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1079#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1080#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1081#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
drh33746482018-12-13 15:06:26 +00001082#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
drh1fa6d9f2018-01-06 21:46:01 +00001083
drh707821f2018-12-05 13:39:06 +00001084/* Allowed values for ShellState.eTraceType
1085*/
1086#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1087#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1088#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1089
drh3f83f592019-02-04 14:53:18 +00001090/* Bits in the ShellState.flgProgress variable */
drhfc4eeef2019-02-05 19:48:46 +00001091#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1092#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1093 ** callback limit is reached, and for each
1094 ** top-level SQL statement */
1095#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
drh3f83f592019-02-04 14:53:18 +00001096
drh2ce15c32017-07-11 13:34:40 +00001097/*
1098** These are the allowed shellFlgs values
1099*/
drhb2a0f752017-08-28 15:51:35 +00001100#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1101#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1102#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1103#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1104#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1105#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1106#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
dan68cb86e2019-04-20 20:57:28 +00001107#define SHFLG_Recover 0x00000080 /* .dump is --recover */
drh2ce15c32017-07-11 13:34:40 +00001108
1109/*
1110** Macros for testing and setting shellFlgs
1111*/
1112#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1113#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1114#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1115
1116/*
1117** These are the allowed modes.
1118*/
1119#define MODE_Line 0 /* One column per line. Blank line between records */
1120#define MODE_Column 1 /* One record per line in neat columns */
1121#define MODE_List 2 /* One record per line with a separator */
1122#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1123#define MODE_Html 4 /* Generate an XHTML table */
1124#define MODE_Insert 5 /* Generate SQL "insert" statements */
1125#define MODE_Quote 6 /* Quote values as for SQL */
1126#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1127#define MODE_Csv 8 /* Quote strings, numbers are plain */
1128#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1129#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1130#define MODE_Pretty 11 /* Pretty-print schemas */
drh4b5345c2018-04-24 13:07:40 +00001131#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
drh2ce15c32017-07-11 13:34:40 +00001132
1133static const char *modeDescr[] = {
1134 "line",
1135 "column",
1136 "list",
1137 "semi",
1138 "html",
1139 "insert",
1140 "quote",
1141 "tcl",
1142 "csv",
1143 "explain",
1144 "ascii",
1145 "prettyprint",
drh4b5345c2018-04-24 13:07:40 +00001146 "eqp"
drh2ce15c32017-07-11 13:34:40 +00001147};
1148
1149/*
1150** These are the column/row/line separators used by the various
1151** import/export modes.
1152*/
1153#define SEP_Column "|"
1154#define SEP_Row "\n"
1155#define SEP_Tab "\t"
1156#define SEP_Space " "
1157#define SEP_Comma ","
1158#define SEP_CrLf "\r\n"
1159#define SEP_Unit "\x1F"
1160#define SEP_Record "\x1E"
1161
1162/*
drh2ce15c32017-07-11 13:34:40 +00001163** A callback for the sqlite3_log() interface.
1164*/
1165static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1166 ShellState *p = (ShellState*)pArg;
1167 if( p->pLog==0 ) return;
1168 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1169 fflush(p->pLog);
1170}
1171
1172/*
drh634c70f2018-01-10 16:50:18 +00001173** SQL function: shell_putsnl(X)
1174**
1175** Write the text X to the screen (or whatever output is being directed)
1176** adding a newline at the end, and then return X.
1177*/
1178static void shellPutsFunc(
1179 sqlite3_context *pCtx,
1180 int nVal,
1181 sqlite3_value **apVal
1182){
1183 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
drhb9685182018-01-17 13:15:23 +00001184 (void)nVal;
drh634c70f2018-01-10 16:50:18 +00001185 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1186 sqlite3_result_value(pCtx, apVal[0]);
1187}
1188
1189/*
drh97913132018-01-11 00:04:00 +00001190** SQL function: edit(VALUE)
1191** edit(VALUE,EDITOR)
1192**
1193** These steps:
1194**
1195** (1) Write VALUE into a temporary file.
1196** (2) Run program EDITOR on that temporary file.
1197** (3) Read the temporary file back and return its content as the result.
1198** (4) Delete the temporary file
1199**
1200** If the EDITOR argument is omitted, use the value in the VISUAL
1201** environment variable. If still there is no EDITOR, through an error.
1202**
1203** Also throw an error if the EDITOR program returns a non-zero exit code.
1204*/
drh04a28c32018-01-31 01:38:44 +00001205#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00001206static void editFunc(
1207 sqlite3_context *context,
1208 int argc,
1209 sqlite3_value **argv
1210){
1211 const char *zEditor;
1212 char *zTempFile = 0;
1213 sqlite3 *db;
1214 char *zCmd = 0;
1215 int bBin;
1216 int rc;
drhf018fd52018-08-06 02:08:53 +00001217 int hasCRNL = 0;
drh97913132018-01-11 00:04:00 +00001218 FILE *f = 0;
1219 sqlite3_int64 sz;
1220 sqlite3_int64 x;
1221 unsigned char *p = 0;
1222
1223 if( argc==2 ){
1224 zEditor = (const char*)sqlite3_value_text(argv[1]);
1225 }else{
1226 zEditor = getenv("VISUAL");
1227 }
1228 if( zEditor==0 ){
1229 sqlite3_result_error(context, "no editor for edit()", -1);
1230 return;
1231 }
1232 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1233 sqlite3_result_error(context, "NULL input to edit()", -1);
1234 return;
1235 }
1236 db = sqlite3_context_db_handle(context);
1237 zTempFile = 0;
1238 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1239 if( zTempFile==0 ){
1240 sqlite3_uint64 r = 0;
1241 sqlite3_randomness(sizeof(r), &r);
1242 zTempFile = sqlite3_mprintf("temp%llx", r);
1243 if( zTempFile==0 ){
1244 sqlite3_result_error_nomem(context);
1245 return;
1246 }
1247 }
1248 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
drhf018fd52018-08-06 02:08:53 +00001249 /* When writing the file to be edited, do \n to \r\n conversions on systems
1250 ** that want \r\n line endings */
drh97913132018-01-11 00:04:00 +00001251 f = fopen(zTempFile, bBin ? "wb" : "w");
1252 if( f==0 ){
1253 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1254 goto edit_func_end;
1255 }
1256 sz = sqlite3_value_bytes(argv[0]);
1257 if( bBin ){
1258 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
1259 }else{
drhf018fd52018-08-06 02:08:53 +00001260 const char *z = (const char*)sqlite3_value_text(argv[0]);
1261 /* Remember whether or not the value originally contained \r\n */
1262 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
drh97913132018-01-11 00:04:00 +00001263 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
1264 }
1265 fclose(f);
1266 f = 0;
1267 if( x!=sz ){
1268 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1269 goto edit_func_end;
1270 }
1271 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1272 if( zCmd==0 ){
1273 sqlite3_result_error_nomem(context);
1274 goto edit_func_end;
1275 }
1276 rc = system(zCmd);
1277 sqlite3_free(zCmd);
1278 if( rc ){
1279 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1280 goto edit_func_end;
1281 }
drhf018fd52018-08-06 02:08:53 +00001282 f = fopen(zTempFile, "rb");
drh97913132018-01-11 00:04:00 +00001283 if( f==0 ){
1284 sqlite3_result_error(context,
1285 "edit() cannot reopen temp file after edit", -1);
1286 goto edit_func_end;
1287 }
1288 fseek(f, 0, SEEK_END);
1289 sz = ftell(f);
1290 rewind(f);
1291 p = sqlite3_malloc64( sz+(bBin==0) );
1292 if( p==0 ){
1293 sqlite3_result_error_nomem(context);
1294 goto edit_func_end;
1295 }
drhf018fd52018-08-06 02:08:53 +00001296 x = fread(p, 1, sz, f);
drh97913132018-01-11 00:04:00 +00001297 fclose(f);
1298 f = 0;
1299 if( x!=sz ){
1300 sqlite3_result_error(context, "could not read back the whole file", -1);
1301 goto edit_func_end;
1302 }
1303 if( bBin ){
mistachkinb71aa092018-01-23 00:05:18 +00001304 sqlite3_result_blob64(context, p, sz, sqlite3_free);
drh97913132018-01-11 00:04:00 +00001305 }else{
dan60bdcf52018-10-03 11:13:30 +00001306 sqlite3_int64 i, j;
drhf018fd52018-08-06 02:08:53 +00001307 if( hasCRNL ){
1308 /* If the original contains \r\n then do no conversions back to \n */
1309 j = sz;
1310 }else{
1311 /* If the file did not originally contain \r\n then convert any new
1312 ** \r\n back into \n */
1313 for(i=j=0; i<sz; i++){
1314 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1315 p[j++] = p[i];
1316 }
1317 sz = j;
1318 p[sz] = 0;
1319 }
mistachkinb71aa092018-01-23 00:05:18 +00001320 sqlite3_result_text64(context, (const char*)p, sz,
1321 sqlite3_free, SQLITE_UTF8);
drh97913132018-01-11 00:04:00 +00001322 }
1323 p = 0;
1324
1325edit_func_end:
1326 if( f ) fclose(f);
1327 unlink(zTempFile);
1328 sqlite3_free(zTempFile);
1329 sqlite3_free(p);
1330}
drh04a28c32018-01-31 01:38:44 +00001331#endif /* SQLITE_NOHAVE_SYSTEM */
drh97913132018-01-11 00:04:00 +00001332
1333/*
drh3c484e82018-01-10 22:27:21 +00001334** Save or restore the current output mode
1335*/
1336static void outputModePush(ShellState *p){
1337 p->modePrior = p->mode;
1338 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1339 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1340}
1341static void outputModePop(ShellState *p){
1342 p->mode = p->modePrior;
1343 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1344 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1345}
1346
1347/*
drh2ce15c32017-07-11 13:34:40 +00001348** Output the given string as a hex-encoded blob (eg. X'1234' )
1349*/
1350static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1351 int i;
1352 char *zBlob = (char *)pBlob;
1353 raw_printf(out,"X'");
1354 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1355 raw_printf(out,"'");
1356}
1357
1358/*
1359** Find a string that is not found anywhere in z[]. Return a pointer
1360** to that string.
1361**
1362** Try to use zA and zB first. If both of those are already found in z[]
1363** then make up some string and store it in the buffer zBuf.
1364*/
1365static const char *unused_string(
1366 const char *z, /* Result must not appear anywhere in z */
1367 const char *zA, const char *zB, /* Try these first */
1368 char *zBuf /* Space to store a generated string */
1369){
1370 unsigned i = 0;
1371 if( strstr(z, zA)==0 ) return zA;
1372 if( strstr(z, zB)==0 ) return zB;
1373 do{
1374 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1375 }while( strstr(z,zBuf)!=0 );
1376 return zBuf;
1377}
1378
1379/*
1380** Output the given string as a quoted string using SQL quoting conventions.
1381**
1382** See also: output_quoted_escaped_string()
1383*/
1384static void output_quoted_string(FILE *out, const char *z){
1385 int i;
1386 char c;
1387 setBinaryMode(out, 1);
1388 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1389 if( c==0 ){
1390 utf8_printf(out,"'%s'",z);
1391 }else{
1392 raw_printf(out, "'");
1393 while( *z ){
1394 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1395 if( c=='\'' ) i++;
1396 if( i ){
1397 utf8_printf(out, "%.*s", i, z);
1398 z += i;
1399 }
1400 if( c=='\'' ){
1401 raw_printf(out, "'");
1402 continue;
1403 }
1404 if( c==0 ){
1405 break;
1406 }
1407 z++;
1408 }
1409 raw_printf(out, "'");
1410 }
1411 setTextMode(out, 1);
1412}
1413
1414/*
1415** Output the given string as a quoted string using SQL quoting conventions.
1416** Additionallly , escape the "\n" and "\r" characters so that they do not
1417** get corrupted by end-of-line translation facilities in some operating
1418** systems.
1419**
1420** This is like output_quoted_string() but with the addition of the \r\n
1421** escape mechanism.
1422*/
1423static void output_quoted_escaped_string(FILE *out, const char *z){
1424 int i;
1425 char c;
1426 setBinaryMode(out, 1);
1427 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1428 if( c==0 ){
1429 utf8_printf(out,"'%s'",z);
1430 }else{
1431 const char *zNL = 0;
1432 const char *zCR = 0;
1433 int nNL = 0;
1434 int nCR = 0;
1435 char zBuf1[20], zBuf2[20];
1436 for(i=0; z[i]; i++){
1437 if( z[i]=='\n' ) nNL++;
1438 if( z[i]=='\r' ) nCR++;
1439 }
1440 if( nNL ){
1441 raw_printf(out, "replace(");
1442 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1443 }
1444 if( nCR ){
1445 raw_printf(out, "replace(");
1446 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1447 }
1448 raw_printf(out, "'");
1449 while( *z ){
1450 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1451 if( c=='\'' ) i++;
1452 if( i ){
1453 utf8_printf(out, "%.*s", i, z);
1454 z += i;
1455 }
1456 if( c=='\'' ){
1457 raw_printf(out, "'");
1458 continue;
1459 }
1460 if( c==0 ){
1461 break;
1462 }
1463 z++;
1464 if( c=='\n' ){
1465 raw_printf(out, "%s", zNL);
1466 continue;
1467 }
1468 raw_printf(out, "%s", zCR);
1469 }
1470 raw_printf(out, "'");
1471 if( nCR ){
1472 raw_printf(out, ",'%s',char(13))", zCR);
1473 }
1474 if( nNL ){
1475 raw_printf(out, ",'%s',char(10))", zNL);
1476 }
1477 }
1478 setTextMode(out, 1);
1479}
1480
1481/*
1482** Output the given string as a quoted according to C or TCL quoting rules.
1483*/
1484static void output_c_string(FILE *out, const char *z){
1485 unsigned int c;
1486 fputc('"', out);
1487 while( (c = *(z++))!=0 ){
1488 if( c=='\\' ){
1489 fputc(c, out);
1490 fputc(c, out);
1491 }else if( c=='"' ){
1492 fputc('\\', out);
1493 fputc('"', out);
1494 }else if( c=='\t' ){
1495 fputc('\\', out);
1496 fputc('t', out);
1497 }else if( c=='\n' ){
1498 fputc('\\', out);
1499 fputc('n', out);
1500 }else if( c=='\r' ){
1501 fputc('\\', out);
1502 fputc('r', out);
1503 }else if( !isprint(c&0xff) ){
1504 raw_printf(out, "\\%03o", c&0xff);
1505 }else{
1506 fputc(c, out);
1507 }
1508 }
1509 fputc('"', out);
1510}
1511
1512/*
1513** Output the given string with characters that are special to
1514** HTML escaped.
1515*/
1516static void output_html_string(FILE *out, const char *z){
1517 int i;
1518 if( z==0 ) z = "";
1519 while( *z ){
1520 for(i=0; z[i]
1521 && z[i]!='<'
1522 && z[i]!='&'
1523 && z[i]!='>'
1524 && z[i]!='\"'
1525 && z[i]!='\'';
1526 i++){}
1527 if( i>0 ){
1528 utf8_printf(out,"%.*s",i,z);
1529 }
1530 if( z[i]=='<' ){
1531 raw_printf(out,"&lt;");
1532 }else if( z[i]=='&' ){
1533 raw_printf(out,"&amp;");
1534 }else if( z[i]=='>' ){
1535 raw_printf(out,"&gt;");
1536 }else if( z[i]=='\"' ){
1537 raw_printf(out,"&quot;");
1538 }else if( z[i]=='\'' ){
1539 raw_printf(out,"&#39;");
1540 }else{
1541 break;
1542 }
1543 z += i + 1;
1544 }
1545}
1546
1547/*
1548** If a field contains any character identified by a 1 in the following
1549** array, then the string must be quoted for CSV.
1550*/
1551static const char needCsvQuote[] = {
1552 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1553 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1554 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1555 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1556 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1557 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1558 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1559 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1560 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1561 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1562 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1563 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1564 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1565 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1566 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1567 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1568};
1569
1570/*
1571** Output a single term of CSV. Actually, p->colSeparator is used for
1572** the separator, which may or may not be a comma. p->nullValue is
1573** the null value. Strings are quoted if necessary. The separator
1574** is only issued if bSep is true.
1575*/
1576static void output_csv(ShellState *p, const char *z, int bSep){
1577 FILE *out = p->out;
1578 if( z==0 ){
1579 utf8_printf(out,"%s",p->nullValue);
1580 }else{
1581 int i;
1582 int nSep = strlen30(p->colSeparator);
1583 for(i=0; z[i]; i++){
1584 if( needCsvQuote[((unsigned char*)z)[i]]
1585 || (z[i]==p->colSeparator[0] &&
1586 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1587 i = 0;
1588 break;
1589 }
1590 }
1591 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001592 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1593 utf8_printf(out, "%s", zQuoted);
1594 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001595 }else{
1596 utf8_printf(out, "%s", z);
1597 }
1598 }
1599 if( bSep ){
1600 utf8_printf(p->out, "%s", p->colSeparator);
1601 }
1602}
1603
drh2ce15c32017-07-11 13:34:40 +00001604/*
1605** This routine runs when the user presses Ctrl-C
1606*/
1607static void interrupt_handler(int NotUsed){
1608 UNUSED_PARAMETER(NotUsed);
1609 seenInterrupt++;
1610 if( seenInterrupt>2 ) exit(1);
1611 if( globalDb ) sqlite3_interrupt(globalDb);
1612}
mistachkinb4bab902017-10-27 17:09:44 +00001613
1614#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1615/*
1616** This routine runs for console events (e.g. Ctrl-C) on Win32
1617*/
1618static BOOL WINAPI ConsoleCtrlHandler(
1619 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1620){
1621 if( dwCtrlType==CTRL_C_EVENT ){
1622 interrupt_handler(0);
1623 return TRUE;
1624 }
1625 return FALSE;
1626}
drh2ce15c32017-07-11 13:34:40 +00001627#endif
1628
1629#ifndef SQLITE_OMIT_AUTHORIZATION
1630/*
1631** When the ".auth ON" is set, the following authorizer callback is
1632** invoked. It always returns SQLITE_OK.
1633*/
1634static int shellAuth(
1635 void *pClientData,
1636 int op,
1637 const char *zA1,
1638 const char *zA2,
1639 const char *zA3,
1640 const char *zA4
1641){
1642 ShellState *p = (ShellState*)pClientData;
1643 static const char *azAction[] = { 0,
1644 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1645 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1646 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1647 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1648 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1649 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1650 "PRAGMA", "READ", "SELECT",
1651 "TRANSACTION", "UPDATE", "ATTACH",
1652 "DETACH", "ALTER_TABLE", "REINDEX",
1653 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1654 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1655 };
1656 int i;
1657 const char *az[4];
1658 az[0] = zA1;
1659 az[1] = zA2;
1660 az[2] = zA3;
1661 az[3] = zA4;
1662 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1663 for(i=0; i<4; i++){
1664 raw_printf(p->out, " ");
1665 if( az[i] ){
1666 output_c_string(p->out, az[i]);
1667 }else{
1668 raw_printf(p->out, "NULL");
1669 }
1670 }
1671 raw_printf(p->out, "\n");
1672 return SQLITE_OK;
1673}
1674#endif
1675
1676/*
1677** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1678**
1679** This routine converts some CREATE TABLE statements for shadow tables
1680** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1681*/
1682static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1683 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1684 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1685 }else{
1686 utf8_printf(out, "%s%s", z, zTail);
1687 }
1688}
1689static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1690 char c = z[n];
1691 z[n] = 0;
1692 printSchemaLine(out, z, zTail);
1693 z[n] = c;
1694}
1695
1696/*
drh11be81d2018-01-06 15:46:20 +00001697** Return true if string z[] has nothing but whitespace and comments to the
1698** end of the first line.
1699*/
1700static int wsToEol(const char *z){
1701 int i;
1702 for(i=0; z[i]; i++){
1703 if( z[i]=='\n' ) return 1;
1704 if( IsSpace(z[i]) ) continue;
1705 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1706 return 0;
1707 }
1708 return 1;
1709}
drh4b5345c2018-04-24 13:07:40 +00001710
1711/*
1712** Add a new entry to the EXPLAIN QUERY PLAN data
1713*/
drhe2ca99c2018-05-02 00:33:43 +00001714static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
drh4b5345c2018-04-24 13:07:40 +00001715 EQPGraphRow *pNew;
1716 int nText = strlen30(zText);
drhe2ca99c2018-05-02 00:33:43 +00001717 if( p->autoEQPtest ){
1718 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1719 }
drh4b5345c2018-04-24 13:07:40 +00001720 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1721 if( pNew==0 ) shell_out_of_memory();
drhe2ca99c2018-05-02 00:33:43 +00001722 pNew->iEqpId = iEqpId;
1723 pNew->iParentId = p2;
drh4b5345c2018-04-24 13:07:40 +00001724 memcpy(pNew->zText, zText, nText+1);
1725 pNew->pNext = 0;
1726 if( p->sGraph.pLast ){
1727 p->sGraph.pLast->pNext = pNew;
1728 }else{
1729 p->sGraph.pRow = pNew;
1730 }
1731 p->sGraph.pLast = pNew;
1732}
1733
1734/*
1735** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1736** in p->sGraph.
1737*/
1738static void eqp_reset(ShellState *p){
1739 EQPGraphRow *pRow, *pNext;
1740 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1741 pNext = pRow->pNext;
1742 sqlite3_free(pRow);
1743 }
1744 memset(&p->sGraph, 0, sizeof(p->sGraph));
1745}
1746
drhe2ca99c2018-05-02 00:33:43 +00001747/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
drh4b5345c2018-04-24 13:07:40 +00001748** pOld, or return the first such line if pOld is NULL
1749*/
drhe2ca99c2018-05-02 00:33:43 +00001750static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
drh4b5345c2018-04-24 13:07:40 +00001751 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
drhe2ca99c2018-05-02 00:33:43 +00001752 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
drh4b5345c2018-04-24 13:07:40 +00001753 return pRow;
1754}
1755
drhe2ca99c2018-05-02 00:33:43 +00001756/* Render a single level of the graph that has iEqpId as its parent. Called
drh4b5345c2018-04-24 13:07:40 +00001757** recursively to render sublevels.
1758*/
drhe2ca99c2018-05-02 00:33:43 +00001759static void eqp_render_level(ShellState *p, int iEqpId){
drh4b5345c2018-04-24 13:07:40 +00001760 EQPGraphRow *pRow, *pNext;
drh4b5345c2018-04-24 13:07:40 +00001761 int n = strlen30(p->sGraph.zPrefix);
1762 char *z;
drhe2ca99c2018-05-02 00:33:43 +00001763 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1764 pNext = eqp_next_row(p, iEqpId, pRow);
drh4b5345c2018-04-24 13:07:40 +00001765 z = pRow->zText;
1766 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
drhe2188f02018-05-07 11:37:34 +00001767 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
drh4b5345c2018-04-24 13:07:40 +00001768 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
drhe2ca99c2018-05-02 00:33:43 +00001769 eqp_render_level(p, pRow->iEqpId);
drh4b5345c2018-04-24 13:07:40 +00001770 p->sGraph.zPrefix[n] = 0;
1771 }
1772 }
1773}
1774
1775/*
1776** Display and reset the EXPLAIN QUERY PLAN data
1777*/
1778static void eqp_render(ShellState *p){
1779 EQPGraphRow *pRow = p->sGraph.pRow;
1780 if( pRow ){
1781 if( pRow->zText[0]=='-' ){
1782 if( pRow->pNext==0 ){
1783 eqp_reset(p);
1784 return;
1785 }
1786 utf8_printf(p->out, "%s\n", pRow->zText+3);
1787 p->sGraph.pRow = pRow->pNext;
1788 sqlite3_free(pRow);
1789 }else{
1790 utf8_printf(p->out, "QUERY PLAN\n");
1791 }
1792 p->sGraph.zPrefix[0] = 0;
1793 eqp_render_level(p, 0);
1794 eqp_reset(p);
1795 }
1796}
drh11be81d2018-01-06 15:46:20 +00001797
drh569b1d92019-02-05 20:51:41 +00001798#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh11be81d2018-01-06 15:46:20 +00001799/*
drh3f83f592019-02-04 14:53:18 +00001800** Progress handler callback.
1801*/
1802static int progress_handler(void *pClientData) {
1803 ShellState *p = (ShellState*)pClientData;
1804 p->nProgress++;
1805 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1806 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
drhfc4eeef2019-02-05 19:48:46 +00001807 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
1808 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
drh3f83f592019-02-04 14:53:18 +00001809 return 1;
1810 }
drhfc4eeef2019-02-05 19:48:46 +00001811 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
drh3f83f592019-02-04 14:53:18 +00001812 raw_printf(p->out, "Progress %u\n", p->nProgress);
1813 }
1814 return 0;
1815}
drh569b1d92019-02-05 20:51:41 +00001816#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00001817
1818/*
drh2ce15c32017-07-11 13:34:40 +00001819** This is the callback routine that the shell
1820** invokes for each row of a query result.
1821*/
1822static int shell_callback(
1823 void *pArg,
1824 int nArg, /* Number of result columns */
1825 char **azArg, /* Text of each result column */
1826 char **azCol, /* Column names */
1827 int *aiType /* Column types */
1828){
1829 int i;
1830 ShellState *p = (ShellState*)pArg;
1831
drhb3c45232017-08-28 14:33:27 +00001832 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001833 switch( p->cMode ){
1834 case MODE_Line: {
1835 int w = 5;
1836 if( azArg==0 ) break;
1837 for(i=0; i<nArg; i++){
1838 int len = strlen30(azCol[i] ? azCol[i] : "");
1839 if( len>w ) w = len;
1840 }
1841 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1842 for(i=0; i<nArg; i++){
1843 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1844 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1845 }
1846 break;
1847 }
1848 case MODE_Explain:
1849 case MODE_Column: {
1850 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1851 const int *colWidth;
1852 int showHdr;
1853 char *rowSep;
1854 if( p->cMode==MODE_Column ){
1855 colWidth = p->colWidth;
1856 showHdr = p->showHeader;
1857 rowSep = p->rowSeparator;
1858 }else{
1859 colWidth = aExplainWidths;
1860 showHdr = 1;
1861 rowSep = SEP_Row;
1862 }
1863 if( p->cnt++==0 ){
1864 for(i=0; i<nArg; i++){
1865 int w, n;
1866 if( i<ArraySize(p->colWidth) ){
1867 w = colWidth[i];
1868 }else{
1869 w = 0;
1870 }
1871 if( w==0 ){
1872 w = strlenChar(azCol[i] ? azCol[i] : "");
1873 if( w<10 ) w = 10;
1874 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1875 if( w<n ) w = n;
1876 }
1877 if( i<ArraySize(p->actualWidth) ){
1878 p->actualWidth[i] = w;
1879 }
1880 if( showHdr ){
1881 utf8_width_print(p->out, w, azCol[i]);
1882 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1883 }
1884 }
1885 if( showHdr ){
1886 for(i=0; i<nArg; i++){
1887 int w;
1888 if( i<ArraySize(p->actualWidth) ){
1889 w = p->actualWidth[i];
1890 if( w<0 ) w = -w;
1891 }else{
1892 w = 10;
1893 }
1894 utf8_printf(p->out,"%-*.*s%s",w,w,
1895 "----------------------------------------------------------"
1896 "----------------------------------------------------------",
1897 i==nArg-1 ? rowSep : " ");
1898 }
1899 }
1900 }
1901 if( azArg==0 ) break;
1902 for(i=0; i<nArg; i++){
1903 int w;
1904 if( i<ArraySize(p->actualWidth) ){
1905 w = p->actualWidth[i];
1906 }else{
1907 w = 10;
1908 }
1909 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1910 w = strlenChar(azArg[i]);
1911 }
1912 if( i==1 && p->aiIndent && p->pStmt ){
1913 if( p->iIndent<p->nIndent ){
1914 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1915 }
1916 p->iIndent++;
1917 }
1918 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1919 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1920 }
1921 break;
1922 }
1923 case MODE_Semi: { /* .schema and .fullschema output */
1924 printSchemaLine(p->out, azArg[0], ";\n");
1925 break;
1926 }
1927 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1928 char *z;
1929 int j;
1930 int nParen = 0;
1931 char cEnd = 0;
1932 char c;
1933 int nLine = 0;
1934 assert( nArg==1 );
1935 if( azArg[0]==0 ) break;
1936 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1937 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1938 ){
1939 utf8_printf(p->out, "%s;\n", azArg[0]);
1940 break;
1941 }
1942 z = sqlite3_mprintf("%s", azArg[0]);
1943 j = 0;
1944 for(i=0; IsSpace(z[i]); i++){}
1945 for(; (c = z[i])!=0; i++){
1946 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001947 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001948 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1949 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1950 j--;
1951 }
1952 z[j++] = c;
1953 }
1954 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1955 z[j] = 0;
1956 if( strlen30(z)>=79 ){
drh11be81d2018-01-06 15:46:20 +00001957 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001958 if( c==cEnd ){
1959 cEnd = 0;
1960 }else if( c=='"' || c=='\'' || c=='`' ){
1961 cEnd = c;
1962 }else if( c=='[' ){
1963 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001964 }else if( c=='-' && z[i+1]=='-' ){
1965 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001966 }else if( c=='(' ){
1967 nParen++;
1968 }else if( c==')' ){
1969 nParen--;
1970 if( nLine>0 && nParen==0 && j>0 ){
1971 printSchemaLineN(p->out, z, j, "\n");
1972 j = 0;
1973 }
1974 }
1975 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001976 if( nParen==1 && cEnd==0
1977 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1978 ){
drh2ce15c32017-07-11 13:34:40 +00001979 if( c=='\n' ) j--;
1980 printSchemaLineN(p->out, z, j, "\n ");
1981 j = 0;
1982 nLine++;
1983 while( IsSpace(z[i+1]) ){ i++; }
1984 }
1985 }
1986 z[j] = 0;
1987 }
1988 printSchemaLine(p->out, z, ";\n");
1989 sqlite3_free(z);
1990 break;
1991 }
1992 case MODE_List: {
1993 if( p->cnt++==0 && p->showHeader ){
1994 for(i=0; i<nArg; i++){
1995 utf8_printf(p->out,"%s%s",azCol[i],
1996 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1997 }
1998 }
1999 if( azArg==0 ) break;
2000 for(i=0; i<nArg; i++){
2001 char *z = azArg[i];
2002 if( z==0 ) z = p->nullValue;
2003 utf8_printf(p->out, "%s", z);
2004 if( i<nArg-1 ){
2005 utf8_printf(p->out, "%s", p->colSeparator);
2006 }else{
2007 utf8_printf(p->out, "%s", p->rowSeparator);
2008 }
2009 }
2010 break;
2011 }
2012 case MODE_Html: {
2013 if( p->cnt++==0 && p->showHeader ){
2014 raw_printf(p->out,"<TR>");
2015 for(i=0; i<nArg; i++){
2016 raw_printf(p->out,"<TH>");
2017 output_html_string(p->out, azCol[i]);
2018 raw_printf(p->out,"</TH>\n");
2019 }
2020 raw_printf(p->out,"</TR>\n");
2021 }
2022 if( azArg==0 ) break;
2023 raw_printf(p->out,"<TR>");
2024 for(i=0; i<nArg; i++){
2025 raw_printf(p->out,"<TD>");
2026 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2027 raw_printf(p->out,"</TD>\n");
2028 }
2029 raw_printf(p->out,"</TR>\n");
2030 break;
2031 }
2032 case MODE_Tcl: {
2033 if( p->cnt++==0 && p->showHeader ){
2034 for(i=0; i<nArg; i++){
2035 output_c_string(p->out,azCol[i] ? azCol[i] : "");
2036 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2037 }
2038 utf8_printf(p->out, "%s", p->rowSeparator);
2039 }
2040 if( azArg==0 ) break;
2041 for(i=0; i<nArg; i++){
2042 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2043 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2044 }
2045 utf8_printf(p->out, "%s", p->rowSeparator);
2046 break;
2047 }
2048 case MODE_Csv: {
2049 setBinaryMode(p->out, 1);
2050 if( p->cnt++==0 && p->showHeader ){
2051 for(i=0; i<nArg; i++){
2052 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2053 }
2054 utf8_printf(p->out, "%s", p->rowSeparator);
2055 }
2056 if( nArg>0 ){
2057 for(i=0; i<nArg; i++){
2058 output_csv(p, azArg[i], i<nArg-1);
2059 }
2060 utf8_printf(p->out, "%s", p->rowSeparator);
2061 }
2062 setTextMode(p->out, 1);
2063 break;
2064 }
2065 case MODE_Insert: {
2066 if( azArg==0 ) break;
2067 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2068 if( p->showHeader ){
2069 raw_printf(p->out,"(");
2070 for(i=0; i<nArg; i++){
2071 if( i>0 ) raw_printf(p->out, ",");
2072 if( quoteChar(azCol[i]) ){
2073 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2074 utf8_printf(p->out, "%s", z);
2075 sqlite3_free(z);
2076 }else{
2077 raw_printf(p->out, "%s", azCol[i]);
2078 }
2079 }
2080 raw_printf(p->out,")");
2081 }
2082 p->cnt++;
2083 for(i=0; i<nArg; i++){
2084 raw_printf(p->out, i>0 ? "," : " VALUES(");
2085 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2086 utf8_printf(p->out,"NULL");
2087 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2088 if( ShellHasFlag(p, SHFLG_Newlines) ){
2089 output_quoted_string(p->out, azArg[i]);
2090 }else{
2091 output_quoted_escaped_string(p->out, azArg[i]);
2092 }
2093 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2094 utf8_printf(p->out,"%s", azArg[i]);
2095 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2096 char z[50];
2097 double r = sqlite3_column_double(p->pStmt, i);
drh2f1f8802018-06-13 17:19:20 +00002098 sqlite3_uint64 ur;
2099 memcpy(&ur,&r,sizeof(r));
2100 if( ur==0x7ff0000000000000LL ){
2101 raw_printf(p->out, "1e999");
2102 }else if( ur==0xfff0000000000000LL ){
2103 raw_printf(p->out, "-1e999");
2104 }else{
2105 sqlite3_snprintf(50,z,"%!.20g", r);
2106 raw_printf(p->out, "%s", z);
2107 }
drh2ce15c32017-07-11 13:34:40 +00002108 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2109 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2110 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2111 output_hex_blob(p->out, pBlob, nBlob);
2112 }else if( isNumber(azArg[i], 0) ){
2113 utf8_printf(p->out,"%s", azArg[i]);
2114 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2115 output_quoted_string(p->out, azArg[i]);
2116 }else{
2117 output_quoted_escaped_string(p->out, azArg[i]);
2118 }
2119 }
2120 raw_printf(p->out,");\n");
2121 break;
2122 }
2123 case MODE_Quote: {
2124 if( azArg==0 ) break;
2125 if( p->cnt==0 && p->showHeader ){
2126 for(i=0; i<nArg; i++){
2127 if( i>0 ) raw_printf(p->out, ",");
2128 output_quoted_string(p->out, azCol[i]);
2129 }
2130 raw_printf(p->out,"\n");
2131 }
2132 p->cnt++;
2133 for(i=0; i<nArg; i++){
2134 if( i>0 ) raw_printf(p->out, ",");
2135 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2136 utf8_printf(p->out,"NULL");
2137 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2138 output_quoted_string(p->out, azArg[i]);
2139 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2140 utf8_printf(p->out,"%s", azArg[i]);
2141 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2142 char z[50];
2143 double r = sqlite3_column_double(p->pStmt, i);
2144 sqlite3_snprintf(50,z,"%!.20g", r);
2145 raw_printf(p->out, "%s", z);
2146 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2147 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2148 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2149 output_hex_blob(p->out, pBlob, nBlob);
2150 }else if( isNumber(azArg[i], 0) ){
2151 utf8_printf(p->out,"%s", azArg[i]);
2152 }else{
2153 output_quoted_string(p->out, azArg[i]);
2154 }
2155 }
2156 raw_printf(p->out,"\n");
2157 break;
2158 }
2159 case MODE_Ascii: {
2160 if( p->cnt++==0 && p->showHeader ){
2161 for(i=0; i<nArg; i++){
2162 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2163 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2164 }
2165 utf8_printf(p->out, "%s", p->rowSeparator);
2166 }
2167 if( azArg==0 ) break;
2168 for(i=0; i<nArg; i++){
2169 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2170 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2171 }
2172 utf8_printf(p->out, "%s", p->rowSeparator);
2173 break;
2174 }
drh4b5345c2018-04-24 13:07:40 +00002175 case MODE_EQP: {
drhe2ca99c2018-05-02 00:33:43 +00002176 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
drh4b5345c2018-04-24 13:07:40 +00002177 break;
2178 }
drh2ce15c32017-07-11 13:34:40 +00002179 }
2180 return 0;
2181}
2182
2183/*
2184** This is the callback routine that the SQLite library
2185** invokes for each row of a query result.
2186*/
2187static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2188 /* since we don't have type info, call the shell_callback with a NULL value */
2189 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2190}
2191
2192/*
2193** This is the callback routine from sqlite3_exec() that appends all
2194** output onto the end of a ShellText object.
2195*/
2196static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2197 ShellText *p = (ShellText*)pArg;
2198 int i;
2199 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00002200 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002201 if( p->n ) appendText(p, "|", 0);
2202 for(i=0; i<nArg; i++){
2203 if( i ) appendText(p, ",", 0);
2204 if( azArg[i] ) appendText(p, azArg[i], 0);
2205 }
2206 return 0;
2207}
2208
2209/*
2210** Generate an appropriate SELFTEST table in the main database.
2211*/
2212static void createSelftestTable(ShellState *p){
2213 char *zErrMsg = 0;
2214 sqlite3_exec(p->db,
2215 "SAVEPOINT selftest_init;\n"
2216 "CREATE TABLE IF NOT EXISTS selftest(\n"
2217 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2218 " op TEXT,\n" /* Operator: memo run */
2219 " cmd TEXT,\n" /* Command text */
2220 " ans TEXT\n" /* Desired answer */
2221 ");"
2222 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2223 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2224 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2225 " 'memo','Tests generated by --init');\n"
2226 "INSERT INTO [_shell$self]\n"
2227 " SELECT 'run',\n"
2228 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2229 "FROM sqlite_master ORDER BY 2'',224))',\n"
2230 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2231 "FROM sqlite_master ORDER BY 2',224));\n"
2232 "INSERT INTO [_shell$self]\n"
2233 " SELECT 'run',"
2234 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2235 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2236 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2237 " FROM (\n"
2238 " SELECT name FROM sqlite_master\n"
2239 " WHERE type='table'\n"
2240 " AND name<>'selftest'\n"
2241 " AND coalesce(rootpage,0)>0\n"
2242 " )\n"
2243 " ORDER BY name;\n"
2244 "INSERT INTO [_shell$self]\n"
2245 " VALUES('run','PRAGMA integrity_check','ok');\n"
2246 "INSERT INTO selftest(tno,op,cmd,ans)"
2247 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2248 "DROP TABLE [_shell$self];"
2249 ,0,0,&zErrMsg);
2250 if( zErrMsg ){
2251 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2252 sqlite3_free(zErrMsg);
2253 }
2254 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2255}
2256
2257
2258/*
2259** Set the destination table field of the ShellState structure to
2260** the name of the table given. Escape any quote characters in the
2261** table name.
2262*/
2263static void set_table_name(ShellState *p, const char *zName){
2264 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00002265 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00002266 char *z;
2267
2268 if( p->zDestTable ){
2269 free(p->zDestTable);
2270 p->zDestTable = 0;
2271 }
2272 if( zName==0 ) return;
2273 cQuote = quoteChar(zName);
2274 n = strlen30(zName);
2275 if( cQuote ) n += n+2;
2276 z = p->zDestTable = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00002277 if( z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002278 n = 0;
2279 if( cQuote ) z[n++] = cQuote;
2280 for(i=0; zName[i]; i++){
2281 z[n++] = zName[i];
2282 if( zName[i]==cQuote ) z[n++] = cQuote;
2283 }
2284 if( cQuote ) z[n++] = cQuote;
2285 z[n] = 0;
2286}
2287
2288
2289/*
2290** Execute a query statement that will generate SQL output. Print
2291** the result columns, comma-separated, on a line and then add a
2292** semicolon terminator to the end of that line.
2293**
2294** If the number of columns is 1 and that column contains text "--"
2295** then write the semicolon on a separate line. That way, if a
2296** "--" comment occurs at the end of the statement, the comment
2297** won't consume the semicolon terminator.
2298*/
2299static int run_table_dump_query(
2300 ShellState *p, /* Query context */
2301 const char *zSelect, /* SELECT statement to extract content */
2302 const char *zFirstRow /* Print before first row, if not NULL */
2303){
2304 sqlite3_stmt *pSelect;
2305 int rc;
2306 int nResult;
2307 int i;
2308 const char *z;
2309 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2310 if( rc!=SQLITE_OK || !pSelect ){
2311 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2312 sqlite3_errmsg(p->db));
2313 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2314 return rc;
2315 }
2316 rc = sqlite3_step(pSelect);
2317 nResult = sqlite3_column_count(pSelect);
2318 while( rc==SQLITE_ROW ){
2319 if( zFirstRow ){
2320 utf8_printf(p->out, "%s", zFirstRow);
2321 zFirstRow = 0;
2322 }
2323 z = (const char*)sqlite3_column_text(pSelect, 0);
2324 utf8_printf(p->out, "%s", z);
2325 for(i=1; i<nResult; i++){
2326 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2327 }
2328 if( z==0 ) z = "";
2329 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2330 if( z[0] ){
2331 raw_printf(p->out, "\n;\n");
2332 }else{
2333 raw_printf(p->out, ";\n");
2334 }
2335 rc = sqlite3_step(pSelect);
2336 }
2337 rc = sqlite3_finalize(pSelect);
2338 if( rc!=SQLITE_OK ){
2339 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2340 sqlite3_errmsg(p->db));
2341 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2342 }
2343 return rc;
2344}
2345
2346/*
2347** Allocate space and save off current error string.
2348*/
2349static char *save_err_msg(
2350 sqlite3 *db /* Database to query */
2351){
2352 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2353 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2354 if( zErrMsg ){
2355 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2356 }
2357 return zErrMsg;
2358}
2359
2360#ifdef __linux__
2361/*
2362** Attempt to display I/O stats on Linux using /proc/PID/io
2363*/
2364static void displayLinuxIoStats(FILE *out){
2365 FILE *in;
2366 char z[200];
2367 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2368 in = fopen(z, "rb");
2369 if( in==0 ) return;
2370 while( fgets(z, sizeof(z), in)!=0 ){
2371 static const struct {
2372 const char *zPattern;
2373 const char *zDesc;
2374 } aTrans[] = {
2375 { "rchar: ", "Bytes received by read():" },
2376 { "wchar: ", "Bytes sent to write():" },
2377 { "syscr: ", "Read() system calls:" },
2378 { "syscw: ", "Write() system calls:" },
2379 { "read_bytes: ", "Bytes read from storage:" },
2380 { "write_bytes: ", "Bytes written to storage:" },
2381 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2382 };
2383 int i;
2384 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00002385 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00002386 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2387 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2388 break;
2389 }
2390 }
2391 }
2392 fclose(in);
2393}
2394#endif
2395
2396/*
2397** Display a single line of status using 64-bit values.
2398*/
2399static void displayStatLine(
2400 ShellState *p, /* The shell context */
2401 char *zLabel, /* Label for this one line */
2402 char *zFormat, /* Format for the result */
2403 int iStatusCtrl, /* Which status to display */
2404 int bReset /* True to reset the stats */
2405){
2406 sqlite3_int64 iCur = -1;
2407 sqlite3_int64 iHiwtr = -1;
2408 int i, nPercent;
2409 char zLine[200];
2410 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2411 for(i=0, nPercent=0; zFormat[i]; i++){
2412 if( zFormat[i]=='%' ) nPercent++;
2413 }
2414 if( nPercent>1 ){
2415 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2416 }else{
2417 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2418 }
2419 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2420}
2421
2422/*
2423** Display memory stats.
2424*/
2425static int display_stats(
2426 sqlite3 *db, /* Database to query */
2427 ShellState *pArg, /* Pointer to ShellState */
2428 int bReset /* True to reset the stats */
2429){
2430 int iCur;
2431 int iHiwtr;
drh393344f2018-03-09 16:37:05 +00002432 FILE *out;
2433 if( pArg==0 || pArg->out==0 ) return 0;
2434 out = pArg->out;
drh2ce15c32017-07-11 13:34:40 +00002435
drh393344f2018-03-09 16:37:05 +00002436 if( pArg->pStmt && (pArg->statsOn & 2) ){
2437 int nCol, i, x;
2438 sqlite3_stmt *pStmt = pArg->pStmt;
2439 char z[100];
2440 nCol = sqlite3_column_count(pStmt);
2441 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2442 for(i=0; i<nCol; i++){
2443 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2444 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002445#ifndef SQLITE_OMIT_DECLTYPE
drh393344f2018-03-09 16:37:05 +00002446 sqlite3_snprintf(30, z+x, "declared type:");
2447 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
drh929cce82018-03-17 16:26:36 +00002448#endif
2449#ifdef SQLITE_ENABLE_COLUMN_METADATA
drh393344f2018-03-09 16:37:05 +00002450 sqlite3_snprintf(30, z+x, "database name:");
2451 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2452 sqlite3_snprintf(30, z+x, "table name:");
2453 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2454 sqlite3_snprintf(30, z+x, "origin name:");
2455 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002456#endif
drh2ce15c32017-07-11 13:34:40 +00002457 }
drh929cce82018-03-17 16:26:36 +00002458 }
drh2ce15c32017-07-11 13:34:40 +00002459
drh393344f2018-03-09 16:37:05 +00002460 displayStatLine(pArg, "Memory Used:",
2461 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2462 displayStatLine(pArg, "Number of Outstanding Allocations:",
2463 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2464 if( pArg->shellFlgs & SHFLG_Pagecache ){
2465 displayStatLine(pArg, "Number of Pcache Pages Used:",
2466 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2467 }
2468 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2469 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2470 displayStatLine(pArg, "Largest Allocation:",
2471 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2472 displayStatLine(pArg, "Largest Pcache Allocation:",
2473 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2474#ifdef YYTRACKMAXSTACKDEPTH
2475 displayStatLine(pArg, "Deepest Parser Stack:",
2476 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2477#endif
2478
2479 if( db ){
drh2ce15c32017-07-11 13:34:40 +00002480 if( pArg->shellFlgs & SHFLG_Lookaside ){
2481 iHiwtr = iCur = -1;
2482 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2483 &iCur, &iHiwtr, bReset);
2484 raw_printf(pArg->out,
2485 "Lookaside Slots Used: %d (max %d)\n",
2486 iCur, iHiwtr);
2487 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2488 &iCur, &iHiwtr, bReset);
2489 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2490 iHiwtr);
2491 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2492 &iCur, &iHiwtr, bReset);
2493 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2494 iHiwtr);
2495 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2496 &iCur, &iHiwtr, bReset);
2497 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2498 iHiwtr);
2499 }
2500 iHiwtr = iCur = -1;
2501 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2502 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2503 iCur);
2504 iHiwtr = iCur = -1;
2505 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2506 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2507 iHiwtr = iCur = -1;
2508 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2509 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2510 iHiwtr = iCur = -1;
2511 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2512 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2513 iHiwtr = iCur = -1;
drhffc78a42018-03-14 14:53:50 +00002514 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2515 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2516 iHiwtr = iCur = -1;
drh2ce15c32017-07-11 13:34:40 +00002517 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2518 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2519 iCur);
2520 iHiwtr = iCur = -1;
2521 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2522 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2523 iCur);
2524 }
2525
drh393344f2018-03-09 16:37:05 +00002526 if( pArg->pStmt ){
drh2ce15c32017-07-11 13:34:40 +00002527 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2528 bReset);
2529 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2530 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2531 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2532 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2533 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2534 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2535 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
drh393344f2018-03-09 16:37:05 +00002536 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
2537 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2538 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2539 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2540 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2541 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
drh2ce15c32017-07-11 13:34:40 +00002542 }
2543
2544#ifdef __linux__
2545 displayLinuxIoStats(pArg->out);
2546#endif
2547
2548 /* Do not remove this machine readable comment: extra-stats-output-here */
2549
2550 return 0;
2551}
2552
2553/*
2554** Display scan stats.
2555*/
2556static void display_scanstats(
2557 sqlite3 *db, /* Database to query */
2558 ShellState *pArg /* Pointer to ShellState */
2559){
2560#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2561 UNUSED_PARAMETER(db);
2562 UNUSED_PARAMETER(pArg);
2563#else
2564 int i, k, n, mx;
2565 raw_printf(pArg->out, "-------- scanstats --------\n");
2566 mx = 0;
2567 for(k=0; k<=mx; k++){
2568 double rEstLoop = 1.0;
2569 for(i=n=0; 1; i++){
2570 sqlite3_stmt *p = pArg->pStmt;
2571 sqlite3_int64 nLoop, nVisit;
2572 double rEst;
2573 int iSid;
2574 const char *zExplain;
2575 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2576 break;
2577 }
2578 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2579 if( iSid>mx ) mx = iSid;
2580 if( iSid!=k ) continue;
2581 if( n==0 ){
2582 rEstLoop = (double)nLoop;
2583 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2584 }
2585 n++;
2586 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2587 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2588 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2589 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2590 rEstLoop *= rEst;
2591 raw_printf(pArg->out,
2592 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2593 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2594 );
2595 }
2596 }
2597 raw_printf(pArg->out, "---------------------------\n");
2598#endif
2599}
2600
2601/*
2602** Parameter azArray points to a zero-terminated array of strings. zStr
2603** points to a single nul-terminated string. Return non-zero if zStr
2604** is equal, according to strcmp(), to any of the strings in the array.
2605** Otherwise, return zero.
2606*/
2607static int str_in_array(const char *zStr, const char **azArray){
2608 int i;
2609 for(i=0; azArray[i]; i++){
2610 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2611 }
2612 return 0;
2613}
2614
2615/*
2616** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2617** and populate the ShellState.aiIndent[] array with the number of
2618** spaces each opcode should be indented before it is output.
2619**
2620** The indenting rules are:
2621**
2622** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2623** all opcodes that occur between the p2 jump destination and the opcode
2624** itself by 2 spaces.
2625**
2626** * For each "Goto", if the jump destination is earlier in the program
2627** and ends on one of:
2628** Yield SeekGt SeekLt RowSetRead Rewind
2629** or if the P1 parameter is one instead of zero,
2630** then indent all opcodes between the earlier instruction
2631** and "Goto" by 2 spaces.
2632*/
2633static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2634 const char *zSql; /* The text of the SQL statement */
2635 const char *z; /* Used to check if this is an EXPLAIN */
2636 int *abYield = 0; /* True if op is an OP_Yield */
2637 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2638 int iOp; /* Index of operation in p->aiIndent[] */
2639
drhf1949b62018-06-07 17:32:59 +00002640 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
drh2ce15c32017-07-11 13:34:40 +00002641 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2642 "Rewind", 0 };
2643 const char *azGoto[] = { "Goto", 0 };
2644
2645 /* Try to figure out if this is really an EXPLAIN statement. If this
2646 ** cannot be verified, return early. */
2647 if( sqlite3_column_count(pSql)!=8 ){
2648 p->cMode = p->mode;
2649 return;
2650 }
2651 zSql = sqlite3_sql(pSql);
2652 if( zSql==0 ) return;
2653 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2654 if( sqlite3_strnicmp(z, "explain", 7) ){
2655 p->cMode = p->mode;
2656 return;
2657 }
2658
2659 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2660 int i;
2661 int iAddr = sqlite3_column_int(pSql, 0);
2662 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2663
2664 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2665 ** p2 is an instruction address, set variable p2op to the index of that
2666 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2667 ** the current instruction is part of a sub-program generated by an
2668 ** SQL trigger or foreign key. */
2669 int p2 = sqlite3_column_int(pSql, 3);
2670 int p2op = (p2 + (iOp-iAddr));
2671
2672 /* Grow the p->aiIndent array as required */
2673 if( iOp>=nAlloc ){
2674 if( iOp==0 ){
2675 /* Do further verfication that this is explain output. Abort if
2676 ** it is not */
2677 static const char *explainCols[] = {
2678 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2679 int jj;
2680 for(jj=0; jj<ArraySize(explainCols); jj++){
2681 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2682 p->cMode = p->mode;
2683 sqlite3_reset(pSql);
2684 return;
2685 }
2686 }
2687 }
2688 nAlloc += 100;
2689 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002690 if( p->aiIndent==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002691 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002692 if( abYield==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002693 }
2694 abYield[iOp] = str_in_array(zOp, azYield);
2695 p->aiIndent[iOp] = 0;
2696 p->nIndent = iOp+1;
2697
2698 if( str_in_array(zOp, azNext) ){
2699 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2700 }
2701 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2702 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2703 ){
2704 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2705 }
2706 }
2707
2708 p->iIndent = 0;
2709 sqlite3_free(abYield);
2710 sqlite3_reset(pSql);
2711}
2712
2713/*
2714** Free the array allocated by explain_data_prepare().
2715*/
2716static void explain_data_delete(ShellState *p){
2717 sqlite3_free(p->aiIndent);
2718 p->aiIndent = 0;
2719 p->nIndent = 0;
2720 p->iIndent = 0;
2721}
2722
2723/*
2724** Disable and restore .wheretrace and .selecttrace settings.
2725*/
2726#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2727extern int sqlite3SelectTrace;
2728static int savedSelectTrace;
2729#endif
2730#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2731extern int sqlite3WhereTrace;
2732static int savedWhereTrace;
2733#endif
2734static void disable_debug_trace_modes(void){
2735#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2736 savedSelectTrace = sqlite3SelectTrace;
2737 sqlite3SelectTrace = 0;
2738#endif
2739#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2740 savedWhereTrace = sqlite3WhereTrace;
2741 sqlite3WhereTrace = 0;
2742#endif
2743}
2744static void restore_debug_trace_modes(void){
2745#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2746 sqlite3SelectTrace = savedSelectTrace;
2747#endif
2748#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2749 sqlite3WhereTrace = savedWhereTrace;
2750#endif
2751}
2752
drh9cb02642019-02-28 20:10:52 +00002753/* Create the TEMP table used to store parameter bindings */
2754static void bind_table_init(ShellState *p){
drh346f4e22019-03-25 21:35:41 +00002755 int wrSchema = 0;
2756 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
2757 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
drh9cb02642019-02-28 20:10:52 +00002758 sqlite3_exec(p->db,
drh65c29fd2019-03-25 21:56:26 +00002759 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
drh9cb02642019-02-28 20:10:52 +00002760 " key TEXT PRIMARY KEY,\n"
2761 " value ANY\n"
2762 ") WITHOUT ROWID;",
2763 0, 0, 0);
drh346f4e22019-03-25 21:35:41 +00002764 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
drh9cb02642019-02-28 20:10:52 +00002765}
2766
drh8b738d02019-02-25 18:43:54 +00002767/*
2768** Bind parameters on a prepared statement.
2769**
2770** Parameter bindings are taken from a TEMP table of the form:
2771**
drh1cb02632019-03-25 22:05:22 +00002772** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
drh8b738d02019-02-25 18:43:54 +00002773** WITHOUT ROWID;
2774**
2775** No bindings occur if this table does not exist. The special character '$'
2776** is included in the table name to help prevent collisions with actual tables.
2777** The table must be in the TEMP schema.
2778*/
2779static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2780 int nVar;
2781 int i;
2782 int rc;
2783 sqlite3_stmt *pQ = 0;
2784
2785 nVar = sqlite3_bind_parameter_count(pStmt);
2786 if( nVar==0 ) return; /* Nothing to do */
drh65c29fd2019-03-25 21:56:26 +00002787 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
drh8b738d02019-02-25 18:43:54 +00002788 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2789 return; /* Parameter table does not exist */
2790 }
2791 rc = sqlite3_prepare_v2(pArg->db,
drh65c29fd2019-03-25 21:56:26 +00002792 "SELECT value FROM temp.sqlite_parameters"
drh8b738d02019-02-25 18:43:54 +00002793 " WHERE key=?1", -1, &pQ, 0);
2794 if( rc || pQ==0 ) return;
2795 for(i=1; i<=nVar; i++){
2796 char zNum[30];
2797 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2798 if( zVar==0 ){
2799 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2800 zVar = zNum;
2801 }
2802 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2803 if( sqlite3_step(pQ)==SQLITE_ROW ){
2804 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2805 }else{
2806 sqlite3_bind_null(pStmt, i);
2807 }
2808 sqlite3_reset(pQ);
2809 }
2810 sqlite3_finalize(pQ);
2811}
2812
drh2ce15c32017-07-11 13:34:40 +00002813/*
2814** Run a prepared statement
2815*/
2816static void exec_prepared_stmt(
2817 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002818 sqlite3_stmt *pStmt /* Statment to run */
drh2ce15c32017-07-11 13:34:40 +00002819){
2820 int rc;
2821
2822 /* perform the first step. this will tell us if we
2823 ** have a result set or not and how wide it is.
2824 */
2825 rc = sqlite3_step(pStmt);
2826 /* if we have a result set... */
2827 if( SQLITE_ROW == rc ){
drha10b9992018-03-09 15:24:33 +00002828 /* allocate space for col name ptr, value ptr, and type */
2829 int nCol = sqlite3_column_count(pStmt);
2830 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2831 if( !pData ){
2832 rc = SQLITE_NOMEM;
drh2ce15c32017-07-11 13:34:40 +00002833 }else{
drha10b9992018-03-09 15:24:33 +00002834 char **azCols = (char **)pData; /* Names of result columns */
2835 char **azVals = &azCols[nCol]; /* Results */
2836 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2837 int i, x;
2838 assert(sizeof(int) <= sizeof(char *));
2839 /* save off ptrs to column names */
2840 for(i=0; i<nCol; i++){
2841 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2842 }
drh2ce15c32017-07-11 13:34:40 +00002843 do{
drha10b9992018-03-09 15:24:33 +00002844 /* extract the data and data types */
2845 for(i=0; i<nCol; i++){
2846 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2847 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2848 azVals[i] = "";
2849 }else{
2850 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2851 }
2852 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2853 rc = SQLITE_NOMEM;
2854 break; /* from for */
2855 }
2856 } /* end for */
2857
2858 /* if data and types extracted successfully... */
2859 if( SQLITE_ROW == rc ){
2860 /* call the supplied callback with the result row data */
2861 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2862 rc = SQLITE_ABORT;
2863 }else{
2864 rc = sqlite3_step(pStmt);
2865 }
2866 }
2867 } while( SQLITE_ROW == rc );
2868 sqlite3_free(pData);
drh2ce15c32017-07-11 13:34:40 +00002869 }
2870 }
2871}
2872
dan6b046be2018-01-09 15:25:55 +00002873#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002874/*
dan43efc182017-12-19 17:42:13 +00002875** This function is called to process SQL if the previous shell command
2876** was ".expert". It passes the SQL in the second argument directly to
2877** the sqlite3expert object.
2878**
2879** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2880** code. In this case, (*pzErr) may be set to point to a buffer containing
2881** an English language error message. It is the responsibility of the
2882** caller to eventually free this buffer using sqlite3_free().
2883*/
2884static int expertHandleSQL(
2885 ShellState *pState,
2886 const char *zSql,
2887 char **pzErr
2888){
2889 assert( pState->expert.pExpert );
2890 assert( pzErr==0 || *pzErr==0 );
2891 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2892}
2893
2894/*
2895** This function is called either to silently clean up the object
2896** created by the ".expert" command (if bCancel==1), or to generate a
2897** report from it and then clean it up (if bCancel==0).
2898**
2899** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2900** code. In this case, (*pzErr) may be set to point to a buffer containing
2901** an English language error message. It is the responsibility of the
2902** caller to eventually free this buffer using sqlite3_free().
2903*/
2904static int expertFinish(
2905 ShellState *pState,
2906 int bCancel,
2907 char **pzErr
2908){
2909 int rc = SQLITE_OK;
2910 sqlite3expert *p = pState->expert.pExpert;
2911 assert( p );
2912 assert( bCancel || pzErr==0 || *pzErr==0 );
2913 if( bCancel==0 ){
2914 FILE *out = pState->out;
2915 int bVerbose = pState->expert.bVerbose;
2916
2917 rc = sqlite3_expert_analyze(p, pzErr);
2918 if( rc==SQLITE_OK ){
2919 int nQuery = sqlite3_expert_count(p);
2920 int i;
2921
2922 if( bVerbose ){
2923 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2924 raw_printf(out, "-- Candidates -----------------------------\n");
2925 raw_printf(out, "%s\n", zCand);
2926 }
2927 for(i=0; i<nQuery; i++){
2928 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2929 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2930 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2931 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2932 if( bVerbose ){
2933 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2934 raw_printf(out, "%s\n\n", zSql);
2935 }
2936 raw_printf(out, "%s\n", zIdx);
2937 raw_printf(out, "%s\n", zEQP);
2938 }
2939 }
2940 }
2941 sqlite3_expert_destroy(p);
2942 pState->expert.pExpert = 0;
2943 return rc;
2944}
2945
dan6b046be2018-01-09 15:25:55 +00002946/*
2947** Implementation of ".expert" dot command.
2948*/
2949static int expertDotCommand(
2950 ShellState *pState, /* Current shell tool state */
2951 char **azArg, /* Array of arguments passed to dot command */
2952 int nArg /* Number of entries in azArg[] */
2953){
2954 int rc = SQLITE_OK;
2955 char *zErr = 0;
2956 int i;
2957 int iSample = 0;
2958
2959 assert( pState->expert.pExpert==0 );
2960 memset(&pState->expert, 0, sizeof(ExpertInfo));
2961
2962 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2963 char *z = azArg[i];
2964 int n;
2965 if( z[0]=='-' && z[1]=='-' ) z++;
2966 n = strlen30(z);
2967 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2968 pState->expert.bVerbose = 1;
2969 }
2970 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2971 if( i==(nArg-1) ){
2972 raw_printf(stderr, "option requires an argument: %s\n", z);
2973 rc = SQLITE_ERROR;
2974 }else{
2975 iSample = (int)integerValue(azArg[++i]);
2976 if( iSample<0 || iSample>100 ){
2977 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2978 rc = SQLITE_ERROR;
2979 }
2980 }
2981 }
2982 else{
2983 raw_printf(stderr, "unknown option: %s\n", z);
2984 rc = SQLITE_ERROR;
2985 }
2986 }
2987
2988 if( rc==SQLITE_OK ){
2989 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2990 if( pState->expert.pExpert==0 ){
2991 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2992 rc = SQLITE_ERROR;
2993 }else{
2994 sqlite3_expert_config(
2995 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2996 );
2997 }
2998 }
2999
3000 return rc;
3001}
3002#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00003003
3004/*
drh2ce15c32017-07-11 13:34:40 +00003005** Execute a statement or set of statements. Print
3006** any result rows/columns depending on the current mode
3007** set via the supplied callback.
3008**
3009** This is very similar to SQLite's built-in sqlite3_exec()
3010** function except it takes a slightly different callback
3011** and callback data argument.
3012*/
3013static int shell_exec(
drh2ce15c32017-07-11 13:34:40 +00003014 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00003015 const char *zSql, /* SQL to be evaluated */
drh2ce15c32017-07-11 13:34:40 +00003016 char **pzErrMsg /* Error msg written here */
3017){
3018 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
3019 int rc = SQLITE_OK; /* Return Code */
3020 int rc2;
3021 const char *zLeftover; /* Tail of unprocessed SQL */
drha10b9992018-03-09 15:24:33 +00003022 sqlite3 *db = pArg->db;
drh2ce15c32017-07-11 13:34:40 +00003023
3024 if( pzErrMsg ){
3025 *pzErrMsg = NULL;
3026 }
3027
dan6b046be2018-01-09 15:25:55 +00003028#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00003029 if( pArg->expert.pExpert ){
3030 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3031 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3032 }
dan6b046be2018-01-09 15:25:55 +00003033#endif
dan43efc182017-12-19 17:42:13 +00003034
drh2ce15c32017-07-11 13:34:40 +00003035 while( zSql[0] && (SQLITE_OK == rc) ){
3036 static const char *zStmtSql;
3037 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3038 if( SQLITE_OK != rc ){
3039 if( pzErrMsg ){
3040 *pzErrMsg = save_err_msg(db);
3041 }
3042 }else{
3043 if( !pStmt ){
3044 /* this happens for a comment or white-space */
3045 zSql = zLeftover;
3046 while( IsSpace(zSql[0]) ) zSql++;
3047 continue;
3048 }
3049 zStmtSql = sqlite3_sql(pStmt);
3050 if( zStmtSql==0 ) zStmtSql = "";
3051 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3052
3053 /* save off the prepared statment handle and reset row count */
3054 if( pArg ){
3055 pArg->pStmt = pStmt;
3056 pArg->cnt = 0;
3057 }
3058
3059 /* echo the sql statement if echo on */
3060 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3061 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3062 }
3063
3064 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drh39c5c4a2019-03-06 14:53:27 +00003065 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
drh2ce15c32017-07-11 13:34:40 +00003066 sqlite3_stmt *pExplain;
3067 char *zEQP;
drhada70452017-12-21 21:02:27 +00003068 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00003069 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00003070 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3071 if( pArg->autoEQP>=AUTOEQP_trigger ){
3072 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3073 }
drh2ce15c32017-07-11 13:34:40 +00003074 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3075 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3076 if( rc==SQLITE_OK ){
3077 while( sqlite3_step(pExplain)==SQLITE_ROW ){
drh4b5345c2018-04-24 13:07:40 +00003078 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
drhe2ca99c2018-05-02 00:33:43 +00003079 int iEqpId = sqlite3_column_int(pExplain, 0);
3080 int iParentId = sqlite3_column_int(pExplain, 1);
drh4b5345c2018-04-24 13:07:40 +00003081 if( zEQPLine[0]=='-' ) eqp_render(pArg);
drhe2ca99c2018-05-02 00:33:43 +00003082 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
drh2ce15c32017-07-11 13:34:40 +00003083 }
drh4b5345c2018-04-24 13:07:40 +00003084 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003085 }
3086 sqlite3_finalize(pExplain);
3087 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00003088 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00003089 /* Also do an EXPLAIN for ".eqp full" mode */
3090 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3091 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3092 if( rc==SQLITE_OK ){
3093 pArg->cMode = MODE_Explain;
3094 explain_data_prepare(pArg, pExplain);
drha10b9992018-03-09 15:24:33 +00003095 exec_prepared_stmt(pArg, pExplain);
drh2ce15c32017-07-11 13:34:40 +00003096 explain_data_delete(pArg);
3097 }
3098 sqlite3_finalize(pExplain);
3099 sqlite3_free(zEQP);
3100 }
drh51efe092018-03-20 12:04:38 +00003101 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3102 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3103 /* Reprepare pStmt before reactiving trace modes */
3104 sqlite3_finalize(pStmt);
3105 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
drh3c49eaf2018-06-07 15:23:43 +00003106 if( pArg ) pArg->pStmt = pStmt;
drh51efe092018-03-20 12:04:38 +00003107 }
drh2ce15c32017-07-11 13:34:40 +00003108 restore_debug_trace_modes();
3109 }
3110
3111 if( pArg ){
3112 pArg->cMode = pArg->mode;
drh4b5345c2018-04-24 13:07:40 +00003113 if( pArg->autoExplain ){
drh39c5c4a2019-03-06 14:53:27 +00003114 if( sqlite3_stmt_isexplain(pStmt)==1 ){
drh4b5345c2018-04-24 13:07:40 +00003115 pArg->cMode = MODE_Explain;
3116 }
drh39c5c4a2019-03-06 14:53:27 +00003117 if( sqlite3_stmt_isexplain(pStmt)==2 ){
drh4b5345c2018-04-24 13:07:40 +00003118 pArg->cMode = MODE_EQP;
3119 }
drh2ce15c32017-07-11 13:34:40 +00003120 }
3121
3122 /* If the shell is currently in ".explain" mode, gather the extra
3123 ** data required to add indents to the output.*/
3124 if( pArg->cMode==MODE_Explain ){
3125 explain_data_prepare(pArg, pStmt);
3126 }
3127 }
3128
drh8b738d02019-02-25 18:43:54 +00003129 bind_prepared_stmt(pArg, pStmt);
drha10b9992018-03-09 15:24:33 +00003130 exec_prepared_stmt(pArg, pStmt);
drh2ce15c32017-07-11 13:34:40 +00003131 explain_data_delete(pArg);
drh4b5345c2018-04-24 13:07:40 +00003132 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003133
3134 /* print usage stats if stats on */
3135 if( pArg && pArg->statsOn ){
3136 display_stats(db, pArg, 0);
3137 }
3138
3139 /* print loop-counters if required */
3140 if( pArg && pArg->scanstatsOn ){
3141 display_scanstats(db, pArg);
3142 }
3143
3144 /* Finalize the statement just executed. If this fails, save a
3145 ** copy of the error message. Otherwise, set zSql to point to the
3146 ** next statement to execute. */
3147 rc2 = sqlite3_finalize(pStmt);
3148 if( rc!=SQLITE_NOMEM ) rc = rc2;
3149 if( rc==SQLITE_OK ){
3150 zSql = zLeftover;
3151 while( IsSpace(zSql[0]) ) zSql++;
3152 }else if( pzErrMsg ){
3153 *pzErrMsg = save_err_msg(db);
3154 }
3155
3156 /* clear saved stmt handle */
3157 if( pArg ){
3158 pArg->pStmt = NULL;
3159 }
3160 }
3161 } /* end while */
3162
3163 return rc;
3164}
3165
3166/*
3167** Release memory previously allocated by tableColumnList().
3168*/
3169static void freeColumnList(char **azCol){
3170 int i;
3171 for(i=1; azCol[i]; i++){
3172 sqlite3_free(azCol[i]);
3173 }
3174 /* azCol[0] is a static string */
3175 sqlite3_free(azCol);
3176}
3177
3178/*
3179** Return a list of pointers to strings which are the names of all
3180** columns in table zTab. The memory to hold the names is dynamically
3181** allocated and must be released by the caller using a subsequent call
3182** to freeColumnList().
3183**
3184** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3185** value that needs to be preserved, then azCol[0] is filled in with the
3186** name of the rowid column.
3187**
3188** The first regular column in the table is azCol[1]. The list is terminated
3189** by an entry with azCol[i]==0.
3190*/
3191static char **tableColumnList(ShellState *p, const char *zTab){
3192 char **azCol = 0;
3193 sqlite3_stmt *pStmt;
3194 char *zSql;
3195 int nCol = 0;
3196 int nAlloc = 0;
3197 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3198 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3199 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3200 int rc;
3201
3202 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3203 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3204 sqlite3_free(zSql);
3205 if( rc ) return 0;
3206 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3207 if( nCol>=nAlloc-2 ){
3208 nAlloc = nAlloc*2 + nCol + 10;
3209 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
drh4b5345c2018-04-24 13:07:40 +00003210 if( azCol==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00003211 }
3212 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3213 if( sqlite3_column_int(pStmt, 5) ){
3214 nPK++;
3215 if( nPK==1
3216 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3217 "INTEGER")==0
3218 ){
3219 isIPK = 1;
3220 }else{
3221 isIPK = 0;
3222 }
3223 }
3224 }
3225 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00003226 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003227 azCol[0] = 0;
3228 azCol[nCol+1] = 0;
3229
3230 /* The decision of whether or not a rowid really needs to be preserved
3231 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3232 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3233 ** rowids on tables where the rowid is inaccessible because there are other
3234 ** columns in the table named "rowid", "_rowid_", and "oid".
3235 */
3236 if( preserveRowid && isIPK ){
3237 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3238 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3239 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3240 ** ROWID aliases. To distinguish these cases, check to see if
3241 ** there is a "pk" entry in "PRAGMA index_list". There will be
3242 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3243 */
3244 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3245 " WHERE origin='pk'", zTab);
3246 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3247 sqlite3_free(zSql);
3248 if( rc ){
3249 freeColumnList(azCol);
3250 return 0;
3251 }
3252 rc = sqlite3_step(pStmt);
3253 sqlite3_finalize(pStmt);
3254 preserveRowid = rc==SQLITE_ROW;
3255 }
3256 if( preserveRowid ){
3257 /* Only preserve the rowid if we can find a name to use for the
3258 ** rowid */
3259 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3260 int i, j;
3261 for(j=0; j<3; j++){
3262 for(i=1; i<=nCol; i++){
3263 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3264 }
3265 if( i>nCol ){
3266 /* At this point, we know that azRowid[j] is not the name of any
3267 ** ordinary column in the table. Verify that azRowid[j] is a valid
3268 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3269 ** tables will fail this last check */
3270 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3271 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3272 break;
3273 }
3274 }
3275 }
3276 return azCol;
3277}
3278
3279/*
3280** Toggle the reverse_unordered_selects setting.
3281*/
3282static void toggleSelectOrder(sqlite3 *db){
3283 sqlite3_stmt *pStmt = 0;
3284 int iSetting = 0;
3285 char zStmt[100];
3286 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3287 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3288 iSetting = sqlite3_column_int(pStmt, 0);
3289 }
3290 sqlite3_finalize(pStmt);
3291 sqlite3_snprintf(sizeof(zStmt), zStmt,
3292 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3293 sqlite3_exec(db, zStmt, 0, 0, 0);
3294}
3295
3296/*
3297** This is a different callback routine used for dumping the database.
3298** Each row received by this callback consists of a table name,
3299** the table type ("index" or "table") and SQL to create the table.
3300** This routine should print text sufficient to recreate the table.
3301*/
3302static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3303 int rc;
3304 const char *zTable;
3305 const char *zType;
3306 const char *zSql;
3307 ShellState *p = (ShellState *)pArg;
3308
3309 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00003310 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003311 zTable = azArg[0];
3312 zType = azArg[1];
3313 zSql = azArg[2];
3314
3315 if( strcmp(zTable, "sqlite_sequence")==0 ){
3316 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3317 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3318 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3319 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3320 return 0;
3321 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3322 char *zIns;
3323 if( !p->writableSchema ){
3324 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3325 p->writableSchema = 1;
3326 }
3327 zIns = sqlite3_mprintf(
3328 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3329 "VALUES('table','%q','%q',0,'%q');",
3330 zTable, zTable, zSql);
3331 utf8_printf(p->out, "%s\n", zIns);
3332 sqlite3_free(zIns);
3333 return 0;
3334 }else{
3335 printSchemaLine(p->out, zSql, ";\n");
3336 }
3337
3338 if( strcmp(zType, "table")==0 ){
3339 ShellText sSelect;
3340 ShellText sTable;
3341 char **azCol;
3342 int i;
3343 char *savedDestTable;
3344 int savedMode;
3345
3346 azCol = tableColumnList(p, zTable);
3347 if( azCol==0 ){
3348 p->nErr++;
3349 return 0;
3350 }
3351
3352 /* Always quote the table name, even if it appears to be pure ascii,
3353 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3354 initText(&sTable);
3355 appendText(&sTable, zTable, quoteChar(zTable));
3356 /* If preserving the rowid, add a column list after the table name.
3357 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3358 ** instead of the usual "INSERT INTO tab VALUES(...)".
3359 */
3360 if( azCol[0] ){
3361 appendText(&sTable, "(", 0);
3362 appendText(&sTable, azCol[0], 0);
3363 for(i=1; azCol[i]; i++){
3364 appendText(&sTable, ",", 0);
3365 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3366 }
3367 appendText(&sTable, ")", 0);
3368 }
3369
3370 /* Build an appropriate SELECT statement */
3371 initText(&sSelect);
3372 appendText(&sSelect, "SELECT ", 0);
3373 if( azCol[0] ){
3374 appendText(&sSelect, azCol[0], 0);
3375 appendText(&sSelect, ",", 0);
3376 }
3377 for(i=1; azCol[i]; i++){
3378 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3379 if( azCol[i+1] ){
3380 appendText(&sSelect, ",", 0);
3381 }
3382 }
3383 freeColumnList(azCol);
3384 appendText(&sSelect, " FROM ", 0);
3385 appendText(&sSelect, zTable, quoteChar(zTable));
3386
3387 savedDestTable = p->zDestTable;
3388 savedMode = p->mode;
3389 p->zDestTable = sTable.z;
3390 p->mode = p->cMode = MODE_Insert;
drha10b9992018-03-09 15:24:33 +00003391 rc = shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003392 if( (rc&0xff)==SQLITE_CORRUPT ){
3393 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3394 toggleSelectOrder(p->db);
drha10b9992018-03-09 15:24:33 +00003395 shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003396 toggleSelectOrder(p->db);
3397 }
3398 p->zDestTable = savedDestTable;
3399 p->mode = savedMode;
3400 freeText(&sTable);
3401 freeText(&sSelect);
3402 if( rc ) p->nErr++;
3403 }
3404 return 0;
3405}
3406
3407/*
3408** Run zQuery. Use dump_callback() as the callback routine so that
3409** the contents of the query are output as SQL statements.
3410**
3411** If we get a SQLITE_CORRUPT error, rerun the query after appending
3412** "ORDER BY rowid DESC" to the end.
3413*/
3414static int run_schema_dump_query(
3415 ShellState *p,
3416 const char *zQuery
3417){
3418 int rc;
3419 char *zErr = 0;
3420 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3421 if( rc==SQLITE_CORRUPT ){
3422 char *zQ2;
3423 int len = strlen30(zQuery);
3424 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3425 if( zErr ){
3426 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3427 sqlite3_free(zErr);
3428 zErr = 0;
3429 }
3430 zQ2 = malloc( len+100 );
3431 if( zQ2==0 ) return rc;
3432 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3433 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3434 if( rc ){
3435 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3436 }else{
3437 rc = SQLITE_CORRUPT;
3438 }
3439 sqlite3_free(zErr);
3440 free(zQ2);
3441 }
3442 return rc;
3443}
3444
3445/*
drh98aa2ab2018-09-26 16:53:51 +00003446** Text of help messages.
3447**
3448** The help text for each individual command begins with a line that starts
3449** with ".". Subsequent lines are supplimental information.
3450**
3451** There must be two or more spaces between the end of the command and the
3452** start of the description of what that command does.
drh2ce15c32017-07-11 13:34:40 +00003453*/
drh98aa2ab2018-09-26 16:53:51 +00003454static const char *(azHelp[]) = {
drhe37c0e12018-01-06 19:19:50 +00003455#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drh98aa2ab2018-09-26 16:53:51 +00003456 ".archive ... Manage SQL archives",
3457 " Each command must have exactly one of the following options:",
3458 " -c, --create Create a new archive",
drhaf5a2e12019-03-25 15:09:19 +00003459 " -u, --update Add files or update files with changed mtime",
drhb17ea912019-03-25 14:24:19 +00003460 " -i, --insert Like -u but always add even if mtime unchanged",
drh98aa2ab2018-09-26 16:53:51 +00003461 " -t, --list List contents of archive",
3462 " -x, --extract Extract files from archive",
3463 " Optional arguments:",
3464 " -v, --verbose Print each filename as it is processed",
3465 " -f FILE, --file FILE Operate on archive FILE (default is current db)",
3466 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS",
3467 " -C DIR, --directory DIR Change to directory DIR to read/extract files",
3468 " -n, --dryrun Show the SQL that would have occurred",
3469 " Examples:",
3470 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar",
3471 " .ar -tf archive.sar # List members of archive.sar",
3472 " .ar -xvf archive.sar # Verbosely extract files from archive.sar",
3473 " See also:",
3474 " http://sqlite.org/cli.html#sqlar_archive_support",
drhe37c0e12018-01-06 19:19:50 +00003475#endif
drh2ce15c32017-07-11 13:34:40 +00003476#ifndef SQLITE_OMIT_AUTHORIZATION
drh98aa2ab2018-09-26 16:53:51 +00003477 ".auth ON|OFF Show authorizer callbacks",
drh2ce15c32017-07-11 13:34:40 +00003478#endif
drh98aa2ab2018-09-26 16:53:51 +00003479 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3480 " --append Use the appendvfs",
drha50bffb2018-12-08 01:09:14 +00003481 " --async Write to FILE without a journal and without fsync()",
drh98aa2ab2018-09-26 16:53:51 +00003482 ".bail on|off Stop after hitting an error. Default OFF",
3483 ".binary on|off Turn binary output on or off. Default OFF",
3484 ".cd DIRECTORY Change the working directory to DIRECTORY",
3485 ".changes on|off Show number of rows changed by SQL",
3486 ".check GLOB Fail if output since .testcase does not match",
3487 ".clone NEWDB Clone data into NEWDB from the existing database",
3488 ".databases List names and files of attached databases",
3489 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3490 ".dbinfo ?DB? Show status information about the database",
drheb7f2a02018-09-26 18:02:32 +00003491 ".dump ?TABLE? ... Render all database content as SQL",
3492 " Options:",
3493 " --preserve-rowids Include ROWID values in the output",
3494 " --newlines Allow unescaped newline characters in output",
drhe551b512019-04-17 13:58:07 +00003495 " TABLE is a LIKE pattern for the tables to dump",
drh98aa2ab2018-09-26 16:53:51 +00003496 ".echo on|off Turn command echo on or off",
drhb4e50392019-01-26 15:40:04 +00003497 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
3498 " Other Modes:",
3499#ifdef SQLITE_DEBUG
3500 " test Show raw EXPLAIN QUERY PLAN output",
3501 " trace Like \"full\" but also enable \"PRAGMA vdbe_trace\"",
3502#endif
3503 " trigger Like \"full\" but also show trigger bytecode",
drh98aa2ab2018-09-26 16:53:51 +00003504 ".excel Display the output of next command in a spreadsheet",
drheb7f2a02018-09-26 18:02:32 +00003505 ".exit ?CODE? Exit this program with return-code CODE",
drh98aa2ab2018-09-26 16:53:51 +00003506 ".expert EXPERIMENTAL. Suggest indexes for specified queries",
drh2ce15c32017-07-11 13:34:40 +00003507/* Because explain mode comes on automatically now, the ".explain" mode
3508** is removed from the help screen. It is still supported for legacy, however */
drh98aa2ab2018-09-26 16:53:51 +00003509/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/
3510 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3511 ".headers on|off Turn display of headers on or off",
3512 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3513 ".import FILE TABLE Import data from FILE into TABLE",
drh2ce15c32017-07-11 13:34:40 +00003514#ifndef SQLITE_OMIT_TEST_CONTROL
drh98aa2ab2018-09-26 16:53:51 +00003515 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
drh2ce15c32017-07-11 13:34:40 +00003516#endif
drh98aa2ab2018-09-26 16:53:51 +00003517 ".indexes ?TABLE? Show names of indexes",
3518 " If TABLE is specified, only show indexes for",
3519 " tables matching TABLE using the LIKE operator.",
drh2ce15c32017-07-11 13:34:40 +00003520#ifdef SQLITE_ENABLE_IOTRACE
drh98aa2ab2018-09-26 16:53:51 +00003521 ".iotrace FILE Enable I/O diagnostic logging to FILE",
drh2ce15c32017-07-11 13:34:40 +00003522#endif
drh98aa2ab2018-09-26 16:53:51 +00003523 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3524 ".lint OPTIONS Report potential schema issues.",
3525 " Options:",
3526 " fkey-indexes Find missing foreign key indexes",
drh2ce15c32017-07-11 13:34:40 +00003527#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh98aa2ab2018-09-26 16:53:51 +00003528 ".load FILE ?ENTRY? Load an extension library",
drh2ce15c32017-07-11 13:34:40 +00003529#endif
drh98aa2ab2018-09-26 16:53:51 +00003530 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3531 ".mode MODE ?TABLE? Set output mode",
3532 " MODE is one of:",
3533 " ascii Columns/rows delimited by 0x1F and 0x1E",
3534 " csv Comma-separated values",
3535 " column Left-aligned columns. (See .width)",
3536 " html HTML <table> code",
3537 " insert SQL insert statements for TABLE",
3538 " line One value per line",
3539 " list Values delimited by \"|\"",
3540 " quote Escape answers as for SQL",
3541 " tabs Tab-separated values",
3542 " tcl TCL list elements",
3543 ".nullvalue STRING Use STRING in place of NULL values",
3544 ".once (-e|-x|FILE) Output for the next SQL command only to FILE",
3545 " If FILE begins with '|' then open as a pipe",
3546 " Other options:",
3547 " -e Invoke system text editor",
3548 " -x Open in a spreadsheet",
3549 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3550 " Options:",
drh60f34ae2018-10-30 13:19:49 +00003551 " --append Use appendvfs to append database to the end of FILE",
drha751f392018-10-30 15:31:22 +00003552#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00003553 " --deserialize Load into memory useing sqlite3_deserialize()",
drh33746482018-12-13 15:06:26 +00003554 " --hexdb Load the output of \"dbtotxt\" as an in-memory database",
drh6ca64482019-01-22 16:06:20 +00003555 " --maxsize N Maximum size for --hexdb or --deserialized database",
drha751f392018-10-30 15:31:22 +00003556#endif
drh60f34ae2018-10-30 13:19:49 +00003557 " --new Initialize FILE to an empty database",
3558 " --readonly Open FILE readonly",
3559 " --zip FILE is a ZIP archive",
drh98aa2ab2018-09-26 16:53:51 +00003560 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
3561 " If FILE begins with '|' then open it as a pipe.",
drh9cb02642019-02-28 20:10:52 +00003562 ".parameter CMD ... Manage SQL parameter bindings",
3563 " clear Erase all bindings",
3564 " init Initialize the TEMP table that holds bindings",
3565 " list List the current parameter bindings",
3566 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
3567 " PARAMETER should start with '$', ':', '@', or '?'",
3568 " unset PARAMETER Remove PARAMETER from the binding table",
drh98aa2ab2018-09-26 16:53:51 +00003569 ".print STRING... Print literal STRING",
drh569b1d92019-02-05 20:51:41 +00003570#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00003571 ".progress N Invoke progress handler after every N opcodes",
3572 " --limit N Interrupt after N progress callbacks",
3573 " --once Do no more than one progress interrupt",
3574 " --quiet|-q No output except at interrupts",
3575 " --reset Reset the count for each input and interrupt",
drh569b1d92019-02-05 20:51:41 +00003576#endif
drh98aa2ab2018-09-26 16:53:51 +00003577 ".prompt MAIN CONTINUE Replace the standard prompts",
3578 ".quit Exit this program",
3579 ".read FILE Read input from FILE",
3580 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
3581 ".save FILE Write in-memory database into FILE",
3582 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
3583 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
3584 " Options:",
3585 " --indent Try to pretty-print the schema",
drheb7f2a02018-09-26 18:02:32 +00003586 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
3587 " Options:",
3588 " --init Create a new SELFTEST table",
3589 " -v Verbose output",
drh98aa2ab2018-09-26 16:53:51 +00003590 ".separator COL ?ROW? Change the column and row separators",
drh2ce15c32017-07-11 13:34:40 +00003591#if defined(SQLITE_ENABLE_SESSION)
drheb7f2a02018-09-26 18:02:32 +00003592 ".session ?NAME? CMD ... Create or control sessions",
3593 " Subcommands:",
3594 " attach TABLE Attach TABLE",
3595 " changeset FILE Write a changeset into FILE",
3596 " close Close one session",
3597 " enable ?BOOLEAN? Set or query the enable bit",
3598 " filter GLOB... Reject tables matching GLOBs",
3599 " indirect ?BOOLEAN? Mark or query the indirect status",
3600 " isempty Query whether the session is empty",
3601 " list List currently open session names",
3602 " open DB NAME Open a new session on DB",
3603 " patchset FILE Write a patchset into FILE",
3604 " If ?NAME? is omitted, the first defined session is used.",
drh2ce15c32017-07-11 13:34:40 +00003605#endif
drheb7f2a02018-09-26 18:02:32 +00003606 ".sha3sum ... Compute a SHA3 hash of database content",
3607 " Options:",
3608 " --schema Also hash the sqlite_master table",
3609 " --sha3-224 Use the sha3-224 algorithm",
3610 " --sha3-256 Use the sha3-256 algorithm. This is the default.",
3611 " --sha3-384 Use the sha3-384 algorithm",
3612 " --sha3-512 Use the sha3-512 algorithm",
3613 " Any other argument is a LIKE pattern for tables to hash",
drh04a28c32018-01-31 01:38:44 +00003614#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003615 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003616#endif
drh98aa2ab2018-09-26 16:53:51 +00003617 ".show Show the current values for various settings",
3618 ".stats ?on|off? Show stats or turn stats on or off",
drh04a28c32018-01-31 01:38:44 +00003619#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003620 ".system CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003621#endif
drh98aa2ab2018-09-26 16:53:51 +00003622 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
3623 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
3624 ".timeout MS Try opening locked tables for MS milliseconds",
3625 ".timer on|off Turn SQL timer on or off",
drh707821f2018-12-05 13:39:06 +00003626#ifndef SQLITE_OMIT_TRACE
3627 ".trace ?OPTIONS? Output each SQL statement as it is run",
3628 " FILE Send output to FILE",
3629 " stdout Send output to stdout",
3630 " stderr Send output to stderr",
3631 " off Disable tracing",
3632 " --expanded Expand query parameters",
3633#ifdef SQLITE_ENABLE_NORMALIZE
3634 " --normalized Normal the SQL statements",
3635#endif
3636 " --plain Show SQL as it is input",
3637 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
3638 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
3639 " --row Trace each row (SQLITE_TRACE_ROW)",
3640 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
3641#endif /* SQLITE_OMIT_TRACE */
drh98aa2ab2018-09-26 16:53:51 +00003642 ".vfsinfo ?AUX? Information about the top-level VFS",
3643 ".vfslist List all available VFSes",
3644 ".vfsname ?AUX? Print the name of the VFS stack",
3645 ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
3646 " Negative values right-justify",
3647};
3648
3649/*
3650** Output help text.
3651**
3652** zPattern describes the set of commands for which help text is provided.
3653** If zPattern is NULL, then show all commands, but only give a one-line
3654** description of each.
3655**
3656** Return the number of matches.
3657*/
3658static int showHelp(FILE *out, const char *zPattern){
drhe93f8262018-10-11 16:53:37 +00003659 int i = 0;
3660 int j = 0;
drh98aa2ab2018-09-26 16:53:51 +00003661 int n = 0;
3662 char *zPat;
drh488cddf2018-10-06 14:38:17 +00003663 if( zPattern==0
3664 || zPattern[0]=='0'
3665 || strcmp(zPattern,"-a")==0
3666 || strcmp(zPattern,"-all")==0
3667 ){
drh98aa2ab2018-09-26 16:53:51 +00003668 /* Show all commands, but only one line per command */
drh488cddf2018-10-06 14:38:17 +00003669 if( zPattern==0 ) zPattern = "";
drh98aa2ab2018-09-26 16:53:51 +00003670 for(i=0; i<ArraySize(azHelp); i++){
drh488cddf2018-10-06 14:38:17 +00003671 if( azHelp[i][0]=='.' || zPattern[0] ){
drh98aa2ab2018-09-26 16:53:51 +00003672 utf8_printf(out, "%s\n", azHelp[i]);
3673 n++;
3674 }
3675 }
3676 }else{
3677 /* Look for commands that for which zPattern is an exact prefix */
3678 zPat = sqlite3_mprintf(".%s*", zPattern);
3679 for(i=0; i<ArraySize(azHelp); i++){
3680 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3681 utf8_printf(out, "%s\n", azHelp[i]);
drheb7f2a02018-09-26 18:02:32 +00003682 j = i+1;
drh98aa2ab2018-09-26 16:53:51 +00003683 n++;
3684 }
3685 }
3686 sqlite3_free(zPat);
drheb7f2a02018-09-26 18:02:32 +00003687 if( n ){
3688 if( n==1 ){
3689 /* when zPattern is a prefix of exactly one command, then include the
3690 ** details of that command, which should begin at offset j */
3691 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3692 utf8_printf(out, "%s\n", azHelp[j]);
3693 j++;
3694 }
3695 }
3696 return n;
3697 }
3698 /* Look for commands that contain zPattern anywhere. Show the complete
3699 ** text of all commands that match. */
drh98aa2ab2018-09-26 16:53:51 +00003700 zPat = sqlite3_mprintf("%%%s%%", zPattern);
3701 for(i=0; i<ArraySize(azHelp); i++){
3702 if( azHelp[i][0]=='.' ) j = i;
3703 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3704 utf8_printf(out, "%s\n", azHelp[j]);
3705 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3706 j++;
3707 utf8_printf(out, "%s\n", azHelp[j]);
3708 }
3709 i = j;
3710 n++;
3711 }
3712 }
3713 sqlite3_free(zPat);
3714 }
3715 return n;
3716}
drh2ce15c32017-07-11 13:34:40 +00003717
drh2ce15c32017-07-11 13:34:40 +00003718/* Forward reference */
drh60379d42018-12-13 18:30:01 +00003719static int process_input(ShellState *p);
drh2ce15c32017-07-11 13:34:40 +00003720
3721/*
3722** Read the content of file zName into memory obtained from sqlite3_malloc64()
3723** and return a pointer to the buffer. The caller is responsible for freeing
3724** the memory.
3725**
3726** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3727** read.
3728**
3729** For convenience, a nul-terminator byte is always appended to the data read
3730** from the file before the buffer is returned. This byte is not included in
3731** the final value of (*pnByte), if applicable.
3732**
3733** NULL is returned if any error is encountered. The final value of *pnByte
3734** is undefined in this case.
3735*/
3736static char *readFile(const char *zName, int *pnByte){
3737 FILE *in = fopen(zName, "rb");
3738 long nIn;
3739 size_t nRead;
3740 char *pBuf;
3741 if( in==0 ) return 0;
3742 fseek(in, 0, SEEK_END);
3743 nIn = ftell(in);
3744 rewind(in);
3745 pBuf = sqlite3_malloc64( nIn+1 );
drh1dbb1472018-10-11 10:37:24 +00003746 if( pBuf==0 ){ fclose(in); return 0; }
drh2ce15c32017-07-11 13:34:40 +00003747 nRead = fread(pBuf, nIn, 1, in);
3748 fclose(in);
3749 if( nRead!=1 ){
3750 sqlite3_free(pBuf);
3751 return 0;
3752 }
3753 pBuf[nIn] = 0;
3754 if( pnByte ) *pnByte = nIn;
3755 return pBuf;
3756}
3757
3758#if defined(SQLITE_ENABLE_SESSION)
3759/*
3760** Close a single OpenSession object and release all of its associated
3761** resources.
3762*/
3763static void session_close(OpenSession *pSession){
3764 int i;
3765 sqlite3session_delete(pSession->p);
3766 sqlite3_free(pSession->zName);
3767 for(i=0; i<pSession->nFilter; i++){
3768 sqlite3_free(pSession->azFilter[i]);
3769 }
3770 sqlite3_free(pSession->azFilter);
3771 memset(pSession, 0, sizeof(OpenSession));
3772}
3773#endif
3774
3775/*
3776** Close all OpenSession objects and release all associated resources.
3777*/
3778#if defined(SQLITE_ENABLE_SESSION)
3779static void session_close_all(ShellState *p){
3780 int i;
3781 for(i=0; i<p->nSession; i++){
3782 session_close(&p->aSession[i]);
3783 }
3784 p->nSession = 0;
3785}
3786#else
3787# define session_close_all(X)
3788#endif
3789
3790/*
3791** Implementation of the xFilter function for an open session. Omit
3792** any tables named by ".session filter" but let all other table through.
3793*/
3794#if defined(SQLITE_ENABLE_SESSION)
3795static int session_filter(void *pCtx, const char *zTab){
3796 OpenSession *pSession = (OpenSession*)pCtx;
3797 int i;
3798 for(i=0; i<pSession->nFilter; i++){
3799 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3800 }
3801 return 1;
3802}
3803#endif
3804
3805/*
drh1fa6d9f2018-01-06 21:46:01 +00003806** Try to deduce the type of file for zName based on its content. Return
3807** one of the SHELL_OPEN_* constants.
drh1bf208c2018-03-09 21:54:01 +00003808**
3809** If the file does not exist or is empty but its name looks like a ZIP
3810** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3811** Otherwise, assume an ordinary database regardless of the filename if
3812** the type cannot be determined from content.
drh1fa6d9f2018-01-06 21:46:01 +00003813*/
drhfc97c1c2018-05-14 00:41:12 +00003814int deduceDatabaseType(const char *zName, int dfltZip){
drh1fa6d9f2018-01-06 21:46:01 +00003815 FILE *f = fopen(zName, "rb");
3816 size_t n;
3817 int rc = SHELL_OPEN_UNSPEC;
3818 char zBuf[100];
drh1bf208c2018-03-09 21:54:01 +00003819 if( f==0 ){
drhbe4ccb22018-05-17 20:04:24 +00003820 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3821 return SHELL_OPEN_ZIPFILE;
3822 }else{
3823 return SHELL_OPEN_NORMAL;
3824 }
drh1bf208c2018-03-09 21:54:01 +00003825 }
drh2b3c4af2018-10-30 14:36:21 +00003826 n = fread(zBuf, 16, 1, f);
3827 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
3828 fclose(f);
3829 return SHELL_OPEN_NORMAL;
3830 }
drh1fa6d9f2018-01-06 21:46:01 +00003831 fseek(f, -25, SEEK_END);
3832 n = fread(zBuf, 25, 1, f);
3833 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3834 rc = SHELL_OPEN_APPENDVFS;
3835 }else{
3836 fseek(f, -22, SEEK_END);
3837 n = fread(zBuf, 22, 1, f);
3838 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3839 && zBuf[3]==0x06 ){
3840 rc = SHELL_OPEN_ZIPFILE;
drh1bf208c2018-03-09 21:54:01 +00003841 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
mistachkina3926f42018-05-14 12:23:04 +00003842 rc = SHELL_OPEN_ZIPFILE;
drh1fa6d9f2018-01-06 21:46:01 +00003843 }
3844 }
3845 fclose(f);
3846 return rc;
3847}
3848
drh33746482018-12-13 15:06:26 +00003849#ifdef SQLITE_ENABLE_DESERIALIZE
3850/*
3851** Reconstruct an in-memory database using the output from the "dbtotxt"
3852** program. Read content from the file in p->zDbFilename. If p->zDbFilename
3853** is 0, then read from standard input.
3854*/
3855static unsigned char *readHexDb(ShellState *p, int *pnData){
3856 unsigned char *a = 0;
drh2c8ee022018-12-13 18:59:30 +00003857 int nLine;
drh33746482018-12-13 15:06:26 +00003858 int n = 0;
3859 int pgsz = 0;
3860 int iOffset = 0;
3861 int j, k;
3862 int rc;
3863 FILE *in;
drh3ea557e2019-04-23 15:30:58 +00003864 unsigned int x[16];
drh2c8ee022018-12-13 18:59:30 +00003865 char zLine[1000];
drh33746482018-12-13 15:06:26 +00003866 if( p->zDbFilename ){
3867 in = fopen(p->zDbFilename, "r");
3868 if( in==0 ){
3869 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
3870 return 0;
3871 }
drh2c8ee022018-12-13 18:59:30 +00003872 nLine = 0;
drh33746482018-12-13 15:06:26 +00003873 }else{
drh60379d42018-12-13 18:30:01 +00003874 in = p->in;
drh2c8ee022018-12-13 18:59:30 +00003875 nLine = p->lineno;
drh33746482018-12-13 15:06:26 +00003876 }
3877 *pnData = 0;
drh2c8ee022018-12-13 18:59:30 +00003878 nLine++;
drh33746482018-12-13 15:06:26 +00003879 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
3880 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
3881 if( rc!=2 ) goto readHexDb_error;
3882 if( n<=0 ) goto readHexDb_error;
3883 a = sqlite3_malloc( n );
3884 if( a==0 ){
3885 utf8_printf(stderr, "Out of memory!\n");
3886 goto readHexDb_error;
3887 }
3888 memset(a, 0, n);
3889 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
3890 utf8_printf(stderr, "invalid pagesize\n");
3891 goto readHexDb_error;
3892 }
drh2c8ee022018-12-13 18:59:30 +00003893 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
drh33746482018-12-13 15:06:26 +00003894 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
3895 if( rc==2 ){
3896 iOffset = k;
3897 continue;
3898 }
3899 if( strncmp(zLine, "| end ", 6)==0 ){
3900 break;
3901 }
drh3ea557e2019-04-23 15:30:58 +00003902 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
drh33746482018-12-13 15:06:26 +00003903 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
3904 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
3905 if( rc==17 ){
3906 k = iOffset+j;
drhf354e772018-12-13 22:58:52 +00003907 if( k+16<=n ){
drh3ea557e2019-04-23 15:30:58 +00003908 int ii;
3909 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
drh33746482018-12-13 15:06:26 +00003910 }
drh33746482018-12-13 15:06:26 +00003911 }
3912 }
3913 *pnData = n;
drh2c8ee022018-12-13 18:59:30 +00003914 if( in!=p->in ){
3915 fclose(in);
3916 }else{
3917 p->lineno = nLine;
3918 }
drh33746482018-12-13 15:06:26 +00003919 return a;
3920
3921readHexDb_error:
3922 if( in!=stdin ){
3923 fclose(in);
3924 }else{
drh60379d42018-12-13 18:30:01 +00003925 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
drh2c8ee022018-12-13 18:59:30 +00003926 nLine++;
drh33746482018-12-13 15:06:26 +00003927 if(strncmp(zLine, "| end ", 6)==0 ) break;
3928 }
drh2c8ee022018-12-13 18:59:30 +00003929 p->lineno = nLine;
drh33746482018-12-13 15:06:26 +00003930 }
3931 sqlite3_free(a);
3932 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
3933 return 0;
3934}
3935#endif /* SQLITE_ENABLE_DESERIALIZE */
3936
danb1825882019-04-23 20:48:32 +00003937/*
dan9c014f82019-04-25 19:23:15 +00003938** Scalar function "shell_int32". The first argument to this function
3939** must be a blob. The second a non-negative integer. This function
3940** reads and returns a 32-bit big-endian integer from byte
3941** offset (4*<arg2>) of the blob.
3942*/
3943static void shellInt32(
3944 sqlite3_context *context,
3945 int argc,
3946 sqlite3_value **argv
3947){
3948 const unsigned char *pBlob;
3949 int nBlob;
3950 int iInt;
3951
3952 nBlob = sqlite3_value_bytes(argv[0]);
3953 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
3954 iInt = sqlite3_value_int(argv[1]);
3955
3956 if( iInt>=0 && (iInt+1)*4<=nBlob ){
3957 const unsigned char *a = &pBlob[iInt*4];
3958 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
3959 + ((sqlite3_int64)a[1]<<16)
3960 + ((sqlite3_int64)a[2]<< 8)
3961 + ((sqlite3_int64)a[3]<< 0);
3962 sqlite3_result_int64(context, iVal);
3963 }
3964}
3965
3966/*
danb1825882019-04-23 20:48:32 +00003967** Scalar function "shell_escape_crnl" used by the .recover command.
3968** The argument passed to this function is the output of built-in
3969** function quote(). If the first character of the input is "'",
3970** indicating that the value passed to quote() was a text value,
3971** then this function searches the input for "\n" and "\r" characters
3972** and adds a wrapper similar to the following:
3973**
3974** replace(replace(<input>, '\n', char(10), '\r', char(13));
3975**
3976** Or, if the first character of the input is not "'", then a copy
3977** of the input is returned.
3978*/
3979static void shellEscapeCrnl(
3980 sqlite3_context *context,
3981 int argc,
3982 sqlite3_value **argv
3983){
3984 const char *zText = (const char*)sqlite3_value_text(argv[0]);
3985 if( zText[0]=='\'' ){
3986 int nText = sqlite3_value_bytes(argv[0]);
3987 int i;
3988 char zBuf1[20];
3989 char zBuf2[20];
3990 const char *zNL = 0;
3991 const char *zCR = 0;
3992 int nCR = 0;
3993 int nNL = 0;
3994
3995 for(i=0; zText[i]; i++){
3996 if( zNL==0 && zText[i]=='\n' ){
3997 zNL = unused_string(zText, "\\n", "\\012", zBuf1);
3998 nNL = (int)strlen(zNL);
3999 }
4000 if( zCR==0 && zText[i]=='\r' ){
4001 zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4002 nCR = (int)strlen(zCR);
4003 }
4004 }
4005
4006 if( zNL || zCR ){
4007 int iOut = 0;
4008 i64 nMax = (nNL > nCR) ? nNL : nCR;
4009 i64 nAlloc = nMax * nText + (nMax+12)*2;
4010 char *zOut = (char*)sqlite3_malloc64(nAlloc);
4011 if( zOut==0 ){
4012 sqlite3_result_error_nomem(context);
4013 return;
4014 }
4015
4016 if( zNL && zCR ){
4017 memcpy(&zOut[iOut], "replace(replace(", 16);
4018 iOut += 16;
4019 }else{
4020 memcpy(&zOut[iOut], "replace(", 8);
4021 iOut += 8;
4022 }
4023 for(i=0; zText[i]; i++){
4024 if( zText[i]=='\n' ){
4025 memcpy(&zOut[iOut], zNL, nNL);
4026 iOut += nNL;
4027 }else if( zText[i]=='\r' ){
4028 memcpy(&zOut[iOut], zCR, nCR);
4029 iOut += nCR;
4030 }else{
4031 zOut[iOut] = zText[i];
4032 iOut++;
4033 }
4034 }
4035
4036 if( zNL ){
4037 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4038 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4039 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4040 }
4041 if( zCR ){
4042 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4043 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4044 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4045 }
4046
4047 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4048 sqlite3_free(zOut);
4049 return;
4050 }
4051 }
4052
4053 sqlite3_result_value(context, argv[0]);
4054}
4055
drhbe4ccb22018-05-17 20:04:24 +00004056/* Flags for open_db().
4057**
4058** The default behavior of open_db() is to exit(1) if the database fails to
4059** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4060** but still returns without calling exit.
4061**
4062** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4063** ZIP archive if the file does not exist or is empty and its name matches
4064** the *.zip pattern.
4065*/
4066#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
4067#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
4068
drh1fa6d9f2018-01-06 21:46:01 +00004069/*
drh2ce15c32017-07-11 13:34:40 +00004070** Make sure the database is open. If it is not, then open it. If
4071** the database fails to open, print an error message and exit.
4072*/
drhbe4ccb22018-05-17 20:04:24 +00004073static void open_db(ShellState *p, int openFlags){
drh2ce15c32017-07-11 13:34:40 +00004074 if( p->db==0 ){
drhf2072d12018-05-11 15:10:11 +00004075 if( p->openMode==SHELL_OPEN_UNSPEC ){
4076 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
4077 p->openMode = SHELL_OPEN_NORMAL;
drhbe4ccb22018-05-17 20:04:24 +00004078 }else{
4079 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
4080 (openFlags & OPEN_DB_ZIPFILE)!=0);
drhf2072d12018-05-11 15:10:11 +00004081 }
drh1fa6d9f2018-01-06 21:46:01 +00004082 }
4083 switch( p->openMode ){
4084 case SHELL_OPEN_APPENDVFS: {
4085 sqlite3_open_v2(p->zDbFilename, &p->db,
4086 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
4087 break;
4088 }
drh33746482018-12-13 15:06:26 +00004089 case SHELL_OPEN_HEXDB:
drh60f34ae2018-10-30 13:19:49 +00004090 case SHELL_OPEN_DESERIALIZE: {
4091 sqlite3_open(0, &p->db);
4092 break;
4093 }
drh1fa6d9f2018-01-06 21:46:01 +00004094 case SHELL_OPEN_ZIPFILE: {
4095 sqlite3_open(":memory:", &p->db);
4096 break;
4097 }
drhee269a62018-02-14 23:27:43 +00004098 case SHELL_OPEN_READONLY: {
4099 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
4100 break;
4101 }
drh1fa6d9f2018-01-06 21:46:01 +00004102 case SHELL_OPEN_UNSPEC:
4103 case SHELL_OPEN_NORMAL: {
4104 sqlite3_open(p->zDbFilename, &p->db);
4105 break;
4106 }
4107 }
drh2ce15c32017-07-11 13:34:40 +00004108 globalDb = p->db;
4109 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4110 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4111 p->zDbFilename, sqlite3_errmsg(p->db));
drhf25cc4f2019-01-04 14:29:21 +00004112 if( openFlags & OPEN_DB_KEEPALIVE ){
4113 sqlite3_open(":memory:", &p->db);
4114 return;
4115 }
drh2ce15c32017-07-11 13:34:40 +00004116 exit(1);
4117 }
4118#ifndef SQLITE_OMIT_LOAD_EXTENSION
4119 sqlite3_enable_load_extension(p->db, 1);
4120#endif
4121 sqlite3_fileio_init(p->db, 0, 0);
4122 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00004123 sqlite3_completion_init(p->db, 0, 0);
dan68cb86e2019-04-20 20:57:28 +00004124 sqlite3_dbdata_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00004125#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00004126 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00004127 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00004128#endif
drhceba7922018-01-01 21:28:25 +00004129 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00004130 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00004131 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4132 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00004133 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4134 shellPutsFunc, 0, 0);
danb1825882019-04-23 20:48:32 +00004135 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4136 shellEscapeCrnl, 0, 0);
dan9c014f82019-04-25 19:23:15 +00004137 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4138 shellInt32, 0, 0);
drh04a28c32018-01-31 01:38:44 +00004139#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00004140 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4141 editFunc, 0, 0);
4142 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4143 editFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00004144#endif
drh1fa6d9f2018-01-06 21:46:01 +00004145 if( p->openMode==SHELL_OPEN_ZIPFILE ){
4146 char *zSql = sqlite3_mprintf(
4147 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
4148 sqlite3_exec(p->db, zSql, 0, 0, 0);
4149 sqlite3_free(zSql);
drha751f392018-10-30 15:31:22 +00004150 }
4151#ifdef SQLITE_ENABLE_DESERIALIZE
drh33746482018-12-13 15:06:26 +00004152 else
4153 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
mistachkin99490932018-12-17 22:19:57 +00004154 int rc;
drh60f34ae2018-10-30 13:19:49 +00004155 int nData = 0;
drh33746482018-12-13 15:06:26 +00004156 unsigned char *aData;
4157 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4158 aData = (unsigned char*)readFile(p->zDbFilename, &nData);
4159 }else{
4160 aData = readHexDb(p, &nData);
4161 if( aData==0 ){
4162 utf8_printf(stderr, "Error in hexdb input\n");
4163 return;
4164 }
4165 }
mistachkin99490932018-12-17 22:19:57 +00004166 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
drh60f34ae2018-10-30 13:19:49 +00004167 SQLITE_DESERIALIZE_RESIZEABLE |
4168 SQLITE_DESERIALIZE_FREEONCLOSE);
4169 if( rc ){
4170 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4171 }
drh6ca64482019-01-22 16:06:20 +00004172 if( p->szMax>0 ){
4173 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4174 }
drh1fa6d9f2018-01-06 21:46:01 +00004175 }
drha751f392018-10-30 15:31:22 +00004176#endif
drh2ce15c32017-07-11 13:34:40 +00004177 }
4178}
4179
drh9e804032018-05-18 17:11:50 +00004180/*
4181** Attempt to close the databaes connection. Report errors.
4182*/
4183void close_db(sqlite3 *db){
4184 int rc = sqlite3_close(db);
4185 if( rc ){
4186 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4187 rc, sqlite3_errmsg(db));
4188 }
4189}
4190
drh56eb09b2017-07-11 13:59:07 +00004191#if HAVE_READLINE || HAVE_EDITLINE
4192/*
4193** Readline completion callbacks
4194*/
4195static char *readline_completion_generator(const char *text, int state){
4196 static sqlite3_stmt *pStmt = 0;
4197 char *zRet;
4198 if( state==0 ){
4199 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00004200 sqlite3_finalize(pStmt);
4201 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4202 " FROM completion(%Q) ORDER BY 1", text);
4203 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4204 sqlite3_free(zSql);
4205 }
4206 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00004207 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00004208 }else{
4209 sqlite3_finalize(pStmt);
4210 pStmt = 0;
4211 zRet = 0;
4212 }
4213 return zRet;
4214}
4215static char **readline_completion(const char *zText, int iStart, int iEnd){
4216 rl_attempted_completion_over = 1;
4217 return rl_completion_matches(zText, readline_completion_generator);
4218}
4219
4220#elif HAVE_LINENOISE
4221/*
4222** Linenoise completion callback
4223*/
4224static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00004225 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00004226 int i, iStart;
4227 sqlite3_stmt *pStmt = 0;
4228 char *zSql;
4229 char zBuf[1000];
4230
4231 if( nLine>sizeof(zBuf)-30 ) return;
drh1615c372018-05-12 23:56:22 +00004232 if( zLine[0]=='.' || zLine[0]=='#') return;
drh56eb09b2017-07-11 13:59:07 +00004233 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4234 if( i==nLine-1 ) return;
4235 iStart = i+1;
4236 memcpy(zBuf, zLine, iStart);
4237 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4238 " FROM completion(%Q,%Q) ORDER BY 1",
4239 &zLine[iStart], zLine);
4240 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4241 sqlite3_free(zSql);
4242 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4243 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4244 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4245 int nCompletion = sqlite3_column_bytes(pStmt, 0);
4246 if( iStart+nCompletion < sizeof(zBuf)-1 ){
4247 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4248 linenoiseAddCompletion(lc, zBuf);
4249 }
4250 }
4251 sqlite3_finalize(pStmt);
4252}
4253#endif
4254
drh2ce15c32017-07-11 13:34:40 +00004255/*
4256** Do C-language style dequoting.
4257**
4258** \a -> alarm
4259** \b -> backspace
4260** \t -> tab
4261** \n -> newline
4262** \v -> vertical tab
4263** \f -> form feed
4264** \r -> carriage return
4265** \s -> space
4266** \" -> "
4267** \' -> '
4268** \\ -> backslash
4269** \NNN -> ascii character NNN in octal
4270*/
4271static void resolve_backslashes(char *z){
4272 int i, j;
4273 char c;
4274 while( *z && *z!='\\' ) z++;
4275 for(i=j=0; (c = z[i])!=0; i++, j++){
4276 if( c=='\\' && z[i+1]!=0 ){
4277 c = z[++i];
4278 if( c=='a' ){
4279 c = '\a';
4280 }else if( c=='b' ){
4281 c = '\b';
4282 }else if( c=='t' ){
4283 c = '\t';
4284 }else if( c=='n' ){
4285 c = '\n';
4286 }else if( c=='v' ){
4287 c = '\v';
4288 }else if( c=='f' ){
4289 c = '\f';
4290 }else if( c=='r' ){
4291 c = '\r';
4292 }else if( c=='"' ){
4293 c = '"';
4294 }else if( c=='\'' ){
4295 c = '\'';
4296 }else if( c=='\\' ){
4297 c = '\\';
4298 }else if( c>='0' && c<='7' ){
4299 c -= '0';
4300 if( z[i+1]>='0' && z[i+1]<='7' ){
4301 i++;
4302 c = (c<<3) + z[i] - '0';
4303 if( z[i+1]>='0' && z[i+1]<='7' ){
4304 i++;
4305 c = (c<<3) + z[i] - '0';
4306 }
4307 }
4308 }
4309 }
4310 z[j] = c;
4311 }
4312 if( j<i ) z[j] = 0;
4313}
4314
4315/*
drh2ce15c32017-07-11 13:34:40 +00004316** Interpret zArg as either an integer or a boolean value. Return 1 or 0
4317** for TRUE and FALSE. Return the integer value if appropriate.
4318*/
4319static int booleanValue(const char *zArg){
4320 int i;
4321 if( zArg[0]=='0' && zArg[1]=='x' ){
4322 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4323 }else{
4324 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4325 }
4326 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4327 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4328 return 1;
4329 }
4330 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4331 return 0;
4332 }
4333 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4334 zArg);
4335 return 0;
4336}
4337
4338/*
4339** Set or clear a shell flag according to a boolean value.
4340*/
4341static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4342 if( booleanValue(zArg) ){
4343 ShellSetFlag(p, mFlag);
4344 }else{
4345 ShellClearFlag(p, mFlag);
4346 }
4347}
4348
4349/*
4350** Close an output file, assuming it is not stderr or stdout
4351*/
4352static void output_file_close(FILE *f){
4353 if( f && f!=stdout && f!=stderr ) fclose(f);
4354}
4355
4356/*
4357** Try to open an output file. The names "stdout" and "stderr" are
4358** recognized and do the right thing. NULL is returned if the output
4359** filename is "off".
4360*/
drha92a01a2018-01-10 22:15:37 +00004361static FILE *output_file_open(const char *zFile, int bTextMode){
drh2ce15c32017-07-11 13:34:40 +00004362 FILE *f;
4363 if( strcmp(zFile,"stdout")==0 ){
4364 f = stdout;
4365 }else if( strcmp(zFile, "stderr")==0 ){
4366 f = stderr;
4367 }else if( strcmp(zFile, "off")==0 ){
4368 f = 0;
4369 }else{
drha92a01a2018-01-10 22:15:37 +00004370 f = fopen(zFile, bTextMode ? "w" : "wb");
drh2ce15c32017-07-11 13:34:40 +00004371 if( f==0 ){
4372 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4373 }
4374 }
4375 return f;
4376}
4377
drh707821f2018-12-05 13:39:06 +00004378#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00004379/*
4380** A routine for handling output from sqlite3_trace().
4381*/
4382static int sql_trace_callback(
drh707821f2018-12-05 13:39:06 +00004383 unsigned mType, /* The trace type */
4384 void *pArg, /* The ShellState pointer */
4385 void *pP, /* Usually a pointer to sqlite_stmt */
4386 void *pX /* Auxiliary output */
drh2ce15c32017-07-11 13:34:40 +00004387){
drh707821f2018-12-05 13:39:06 +00004388 ShellState *p = (ShellState*)pArg;
4389 sqlite3_stmt *pStmt;
4390 const char *zSql;
4391 int nSql;
4392 if( p->traceOut==0 ) return 0;
4393 if( mType==SQLITE_TRACE_CLOSE ){
4394 utf8_printf(p->traceOut, "-- closing database connection\n");
4395 return 0;
4396 }
4397 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4398 zSql = (const char*)pX;
4399 }else{
4400 pStmt = (sqlite3_stmt*)pP;
4401 switch( p->eTraceType ){
4402 case SHELL_TRACE_EXPANDED: {
4403 zSql = sqlite3_expanded_sql(pStmt);
4404 break;
4405 }
4406#ifdef SQLITE_ENABLE_NORMALIZE
4407 case SHELL_TRACE_NORMALIZED: {
4408 zSql = sqlite3_normalized_sql(pStmt);
4409 break;
4410 }
4411#endif
4412 default: {
4413 zSql = sqlite3_sql(pStmt);
4414 break;
4415 }
4416 }
4417 }
4418 if( zSql==0 ) return 0;
4419 nSql = strlen30(zSql);
4420 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4421 switch( mType ){
4422 case SQLITE_TRACE_ROW:
4423 case SQLITE_TRACE_STMT: {
4424 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4425 break;
4426 }
4427 case SQLITE_TRACE_PROFILE: {
4428 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4429 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4430 break;
4431 }
drh2ce15c32017-07-11 13:34:40 +00004432 }
4433 return 0;
4434}
4435#endif
drh2ce15c32017-07-11 13:34:40 +00004436
4437/*
4438** A no-op routine that runs with the ".breakpoint" doc-command. This is
4439** a useful spot to set a debugger breakpoint.
4440*/
4441static void test_breakpoint(void){
4442 static int nCall = 0;
4443 nCall++;
4444}
4445
4446/*
4447** An object used to read a CSV and other files for import.
4448*/
4449typedef struct ImportCtx ImportCtx;
4450struct ImportCtx {
4451 const char *zFile; /* Name of the input file */
4452 FILE *in; /* Read the CSV text from this input stream */
4453 char *z; /* Accumulated text for a field */
4454 int n; /* Number of bytes in z */
4455 int nAlloc; /* Space allocated for z[] */
4456 int nLine; /* Current line number */
4457 int bNotFirst; /* True if one or more bytes already read */
4458 int cTerm; /* Character that terminated the most recent field */
4459 int cColSep; /* The column separator character. (Usually ",") */
4460 int cRowSep; /* The row separator character. (Usually "\n") */
4461};
4462
4463/* Append a single byte to z[] */
4464static void import_append_char(ImportCtx *p, int c){
4465 if( p->n+1>=p->nAlloc ){
4466 p->nAlloc += p->nAlloc + 100;
4467 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drh4b5345c2018-04-24 13:07:40 +00004468 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004469 }
4470 p->z[p->n++] = (char)c;
4471}
4472
4473/* Read a single field of CSV text. Compatible with rfc4180 and extended
4474** with the option of having a separator other than ",".
4475**
4476** + Input comes from p->in.
4477** + Store results in p->z of length p->n. Space to hold p->z comes
4478** from sqlite3_malloc64().
4479** + Use p->cSep as the column separator. The default is ",".
4480** + Use p->rSep as the row separator. The default is "\n".
4481** + Keep track of the line number in p->nLine.
4482** + Store the character that terminates the field in p->cTerm. Store
4483** EOF on end-of-file.
4484** + Report syntax errors on stderr
4485*/
4486static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4487 int c;
4488 int cSep = p->cColSep;
4489 int rSep = p->cRowSep;
4490 p->n = 0;
4491 c = fgetc(p->in);
4492 if( c==EOF || seenInterrupt ){
4493 p->cTerm = EOF;
4494 return 0;
4495 }
4496 if( c=='"' ){
4497 int pc, ppc;
4498 int startLine = p->nLine;
4499 int cQuote = c;
4500 pc = ppc = 0;
4501 while( 1 ){
4502 c = fgetc(p->in);
4503 if( c==rSep ) p->nLine++;
4504 if( c==cQuote ){
4505 if( pc==cQuote ){
4506 pc = 0;
4507 continue;
4508 }
4509 }
4510 if( (c==cSep && pc==cQuote)
4511 || (c==rSep && pc==cQuote)
4512 || (c==rSep && pc=='\r' && ppc==cQuote)
4513 || (c==EOF && pc==cQuote)
4514 ){
4515 do{ p->n--; }while( p->z[p->n]!=cQuote );
4516 p->cTerm = c;
4517 break;
4518 }
4519 if( pc==cQuote && c!='\r' ){
4520 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4521 p->zFile, p->nLine, cQuote);
4522 }
4523 if( c==EOF ){
4524 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4525 p->zFile, startLine, cQuote);
4526 p->cTerm = c;
4527 break;
4528 }
4529 import_append_char(p, c);
4530 ppc = pc;
4531 pc = c;
4532 }
4533 }else{
4534 /* If this is the first field being parsed and it begins with the
4535 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4536 if( (c&0xff)==0xef && p->bNotFirst==0 ){
4537 import_append_char(p, c);
4538 c = fgetc(p->in);
4539 if( (c&0xff)==0xbb ){
4540 import_append_char(p, c);
4541 c = fgetc(p->in);
4542 if( (c&0xff)==0xbf ){
4543 p->bNotFirst = 1;
4544 p->n = 0;
4545 return csv_read_one_field(p);
4546 }
4547 }
4548 }
4549 while( c!=EOF && c!=cSep && c!=rSep ){
4550 import_append_char(p, c);
4551 c = fgetc(p->in);
4552 }
4553 if( c==rSep ){
4554 p->nLine++;
4555 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4556 }
4557 p->cTerm = c;
4558 }
4559 if( p->z ) p->z[p->n] = 0;
4560 p->bNotFirst = 1;
4561 return p->z;
4562}
4563
4564/* Read a single field of ASCII delimited text.
4565**
4566** + Input comes from p->in.
4567** + Store results in p->z of length p->n. Space to hold p->z comes
4568** from sqlite3_malloc64().
4569** + Use p->cSep as the column separator. The default is "\x1F".
4570** + Use p->rSep as the row separator. The default is "\x1E".
4571** + Keep track of the row number in p->nLine.
4572** + Store the character that terminates the field in p->cTerm. Store
4573** EOF on end-of-file.
4574** + Report syntax errors on stderr
4575*/
4576static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4577 int c;
4578 int cSep = p->cColSep;
4579 int rSep = p->cRowSep;
4580 p->n = 0;
4581 c = fgetc(p->in);
4582 if( c==EOF || seenInterrupt ){
4583 p->cTerm = EOF;
4584 return 0;
4585 }
4586 while( c!=EOF && c!=cSep && c!=rSep ){
4587 import_append_char(p, c);
4588 c = fgetc(p->in);
4589 }
4590 if( c==rSep ){
4591 p->nLine++;
4592 }
4593 p->cTerm = c;
4594 if( p->z ) p->z[p->n] = 0;
4595 return p->z;
4596}
4597
4598/*
4599** Try to transfer data for table zTable. If an error is seen while
4600** moving forward, try to go backwards. The backwards movement won't
4601** work for WITHOUT ROWID tables.
4602*/
4603static void tryToCloneData(
4604 ShellState *p,
4605 sqlite3 *newDb,
4606 const char *zTable
4607){
4608 sqlite3_stmt *pQuery = 0;
4609 sqlite3_stmt *pInsert = 0;
4610 char *zQuery = 0;
4611 char *zInsert = 0;
4612 int rc;
4613 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00004614 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00004615 int k = 0;
4616 int cnt = 0;
4617 const int spinRate = 10000;
4618
4619 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4620 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4621 if( rc ){
4622 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4623 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4624 zQuery);
4625 goto end_data_xfer;
4626 }
4627 n = sqlite3_column_count(pQuery);
4628 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh4b5345c2018-04-24 13:07:40 +00004629 if( zInsert==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004630 sqlite3_snprintf(200+nTable,zInsert,
4631 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00004632 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00004633 for(j=1; j<n; j++){
4634 memcpy(zInsert+i, ",?", 2);
4635 i += 2;
4636 }
4637 memcpy(zInsert+i, ");", 3);
4638 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4639 if( rc ){
4640 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4641 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4642 zQuery);
4643 goto end_data_xfer;
4644 }
4645 for(k=0; k<2; k++){
4646 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4647 for(i=0; i<n; i++){
4648 switch( sqlite3_column_type(pQuery, i) ){
4649 case SQLITE_NULL: {
4650 sqlite3_bind_null(pInsert, i+1);
4651 break;
4652 }
4653 case SQLITE_INTEGER: {
4654 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4655 break;
4656 }
4657 case SQLITE_FLOAT: {
4658 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4659 break;
4660 }
4661 case SQLITE_TEXT: {
4662 sqlite3_bind_text(pInsert, i+1,
4663 (const char*)sqlite3_column_text(pQuery,i),
4664 -1, SQLITE_STATIC);
4665 break;
4666 }
4667 case SQLITE_BLOB: {
4668 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4669 sqlite3_column_bytes(pQuery,i),
4670 SQLITE_STATIC);
4671 break;
4672 }
4673 }
4674 } /* End for */
4675 rc = sqlite3_step(pInsert);
4676 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4677 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4678 sqlite3_errmsg(newDb));
4679 }
4680 sqlite3_reset(pInsert);
4681 cnt++;
4682 if( (cnt%spinRate)==0 ){
4683 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4684 fflush(stdout);
4685 }
4686 } /* End while */
4687 if( rc==SQLITE_DONE ) break;
4688 sqlite3_finalize(pQuery);
4689 sqlite3_free(zQuery);
4690 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4691 zTable);
4692 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4693 if( rc ){
4694 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4695 break;
4696 }
4697 } /* End for(k=0...) */
4698
4699end_data_xfer:
4700 sqlite3_finalize(pQuery);
4701 sqlite3_finalize(pInsert);
4702 sqlite3_free(zQuery);
4703 sqlite3_free(zInsert);
4704}
4705
4706
4707/*
4708** Try to transfer all rows of the schema that match zWhere. For
4709** each row, invoke xForEach() on the object defined by that row.
4710** If an error is encountered while moving forward through the
4711** sqlite_master table, try again moving backwards.
4712*/
4713static void tryToCloneSchema(
4714 ShellState *p,
4715 sqlite3 *newDb,
4716 const char *zWhere,
4717 void (*xForEach)(ShellState*,sqlite3*,const char*)
4718){
4719 sqlite3_stmt *pQuery = 0;
4720 char *zQuery = 0;
4721 int rc;
4722 const unsigned char *zName;
4723 const unsigned char *zSql;
4724 char *zErrMsg = 0;
4725
4726 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4727 " WHERE %s", zWhere);
4728 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4729 if( rc ){
4730 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4731 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4732 zQuery);
4733 goto end_schema_xfer;
4734 }
4735 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4736 zName = sqlite3_column_text(pQuery, 0);
4737 zSql = sqlite3_column_text(pQuery, 1);
4738 printf("%s... ", zName); fflush(stdout);
4739 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4740 if( zErrMsg ){
4741 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4742 sqlite3_free(zErrMsg);
4743 zErrMsg = 0;
4744 }
4745 if( xForEach ){
4746 xForEach(p, newDb, (const char*)zName);
4747 }
4748 printf("done\n");
4749 }
4750 if( rc!=SQLITE_DONE ){
4751 sqlite3_finalize(pQuery);
4752 sqlite3_free(zQuery);
4753 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4754 " WHERE %s ORDER BY rowid DESC", zWhere);
4755 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4756 if( rc ){
4757 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4758 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4759 zQuery);
4760 goto end_schema_xfer;
4761 }
4762 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4763 zName = sqlite3_column_text(pQuery, 0);
4764 zSql = sqlite3_column_text(pQuery, 1);
4765 printf("%s... ", zName); fflush(stdout);
4766 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4767 if( zErrMsg ){
4768 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4769 sqlite3_free(zErrMsg);
4770 zErrMsg = 0;
4771 }
4772 if( xForEach ){
4773 xForEach(p, newDb, (const char*)zName);
4774 }
4775 printf("done\n");
4776 }
4777 }
4778end_schema_xfer:
4779 sqlite3_finalize(pQuery);
4780 sqlite3_free(zQuery);
4781}
4782
4783/*
4784** Open a new database file named "zNewDb". Try to recover as much information
4785** as possible out of the main database (which might be corrupt) and write it
4786** into zNewDb.
4787*/
4788static void tryToClone(ShellState *p, const char *zNewDb){
4789 int rc;
4790 sqlite3 *newDb = 0;
4791 if( access(zNewDb,0)==0 ){
4792 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4793 return;
4794 }
4795 rc = sqlite3_open(zNewDb, &newDb);
4796 if( rc ){
4797 utf8_printf(stderr, "Cannot create output database: %s\n",
4798 sqlite3_errmsg(newDb));
4799 }else{
4800 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4801 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4802 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4803 tryToCloneSchema(p, newDb, "type!='table'", 0);
4804 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4805 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4806 }
drh9e804032018-05-18 17:11:50 +00004807 close_db(newDb);
drh2ce15c32017-07-11 13:34:40 +00004808}
4809
4810/*
drh13c20932018-01-10 21:41:55 +00004811** Change the output file back to stdout.
4812**
4813** If the p->doXdgOpen flag is set, that means the output was being
4814** redirected to a temporary file named by p->zTempFile. In that case,
4815** launch start/open/xdg-open on that temporary file.
drh2ce15c32017-07-11 13:34:40 +00004816*/
4817static void output_reset(ShellState *p){
4818 if( p->outfile[0]=='|' ){
4819#ifndef SQLITE_OMIT_POPEN
4820 pclose(p->out);
4821#endif
4822 }else{
4823 output_file_close(p->out);
drh04a28c32018-01-31 01:38:44 +00004824#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00004825 if( p->doXdgOpen ){
4826 const char *zXdgOpenCmd =
4827#if defined(_WIN32)
4828 "start";
4829#elif defined(__APPLE__)
4830 "open";
4831#else
4832 "xdg-open";
4833#endif
4834 char *zCmd;
4835 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
drha92a01a2018-01-10 22:15:37 +00004836 if( system(zCmd) ){
4837 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4838 }
drh13c20932018-01-10 21:41:55 +00004839 sqlite3_free(zCmd);
drh3c484e82018-01-10 22:27:21 +00004840 outputModePop(p);
drh13c20932018-01-10 21:41:55 +00004841 p->doXdgOpen = 0;
4842 }
drh04a28c32018-01-31 01:38:44 +00004843#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00004844 }
4845 p->outfile[0] = 0;
4846 p->out = stdout;
4847}
4848
4849/*
4850** Run an SQL command and return the single integer result.
4851*/
4852static int db_int(ShellState *p, const char *zSql){
4853 sqlite3_stmt *pStmt;
4854 int res = 0;
4855 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4856 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4857 res = sqlite3_column_int(pStmt,0);
4858 }
4859 sqlite3_finalize(pStmt);
4860 return res;
4861}
4862
4863/*
4864** Convert a 2-byte or 4-byte big-endian integer into a native integer
4865*/
4866static unsigned int get2byteInt(unsigned char *a){
4867 return (a[0]<<8) + a[1];
4868}
4869static unsigned int get4byteInt(unsigned char *a){
4870 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4871}
4872
4873/*
4874** Implementation of the ".info" command.
4875**
4876** Return 1 on error, 2 to exit, and 0 otherwise.
4877*/
4878static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4879 static const struct { const char *zName; int ofst; } aField[] = {
4880 { "file change counter:", 24 },
4881 { "database page count:", 28 },
4882 { "freelist page count:", 36 },
4883 { "schema cookie:", 40 },
4884 { "schema format:", 44 },
4885 { "default cache size:", 48 },
4886 { "autovacuum top root:", 52 },
4887 { "incremental vacuum:", 64 },
4888 { "text encoding:", 56 },
4889 { "user version:", 60 },
4890 { "application id:", 68 },
4891 { "software version:", 96 },
4892 };
4893 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4894 { "number of tables:",
4895 "SELECT count(*) FROM %s WHERE type='table'" },
4896 { "number of indexes:",
4897 "SELECT count(*) FROM %s WHERE type='index'" },
4898 { "number of triggers:",
4899 "SELECT count(*) FROM %s WHERE type='trigger'" },
4900 { "number of views:",
4901 "SELECT count(*) FROM %s WHERE type='view'" },
4902 { "schema size:",
4903 "SELECT total(length(sql)) FROM %s" },
4904 };
drh87c889c2019-03-20 18:22:51 +00004905 int i, rc;
drhea99a312018-07-18 19:09:07 +00004906 unsigned iDataVersion;
drh2ce15c32017-07-11 13:34:40 +00004907 char *zSchemaTab;
4908 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004909 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004910 unsigned char aHdr[100];
4911 open_db(p, 0);
4912 if( p->db==0 ) return 1;
drh87c889c2019-03-20 18:22:51 +00004913 rc = sqlite3_prepare_v2(p->db,
4914 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4915 -1, &pStmt, 0);
4916 if( rc ){
4917 if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){
4918 utf8_printf(stderr, "the \".dbinfo\" command requires the "
4919 "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n");
4920 }else{
4921 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
4922 }
4923 sqlite3_finalize(pStmt);
4924 return 1;
4925 }
drh512e6c32017-10-11 17:51:08 +00004926 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4927 if( sqlite3_step(pStmt)==SQLITE_ROW
4928 && sqlite3_column_bytes(pStmt,0)>100
4929 ){
4930 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4931 sqlite3_finalize(pStmt);
4932 }else{
drh2ce15c32017-07-11 13:34:40 +00004933 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004934 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004935 return 1;
4936 }
4937 i = get2byteInt(aHdr+16);
4938 if( i==1 ) i = 65536;
4939 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4940 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4941 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4942 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4943 for(i=0; i<ArraySize(aField); i++){
4944 int ofst = aField[i].ofst;
4945 unsigned int val = get4byteInt(aHdr + ofst);
4946 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4947 switch( ofst ){
4948 case 56: {
4949 if( val==1 ) raw_printf(p->out, " (utf8)");
4950 if( val==2 ) raw_printf(p->out, " (utf16le)");
4951 if( val==3 ) raw_printf(p->out, " (utf16be)");
4952 }
4953 }
4954 raw_printf(p->out, "\n");
4955 }
4956 if( zDb==0 ){
4957 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4958 }else if( strcmp(zDb,"temp")==0 ){
4959 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4960 }else{
4961 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4962 }
4963 for(i=0; i<ArraySize(aQuery); i++){
4964 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4965 int val = db_int(p, zSql);
4966 sqlite3_free(zSql);
4967 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4968 }
4969 sqlite3_free(zSchemaTab);
drhea99a312018-07-18 19:09:07 +00004970 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
4971 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
drh2ce15c32017-07-11 13:34:40 +00004972 return 0;
4973}
4974
4975/*
4976** Print the current sqlite3_errmsg() value to stderr and return 1.
4977*/
4978static int shellDatabaseError(sqlite3 *db){
4979 const char *zErr = sqlite3_errmsg(db);
4980 utf8_printf(stderr, "Error: %s\n", zErr);
4981 return 1;
4982}
4983
4984/*
drh2ce15c32017-07-11 13:34:40 +00004985** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4986** if they match and FALSE (0) if they do not match.
4987**
4988** Globbing rules:
4989**
4990** '*' Matches any sequence of zero or more characters.
4991**
4992** '?' Matches exactly one character.
4993**
4994** [...] Matches one character from the enclosed list of
4995** characters.
4996**
4997** [^...] Matches one character not in the enclosed list.
4998**
4999** '#' Matches any sequence of one or more digits with an
5000** optional + or - sign in front
5001**
5002** ' ' Any span of whitespace matches any other span of
5003** whitespace.
5004**
5005** Extra whitespace at the end of z[] is ignored.
5006*/
5007static int testcase_glob(const char *zGlob, const char *z){
5008 int c, c2;
5009 int invert;
5010 int seen;
5011
5012 while( (c = (*(zGlob++)))!=0 ){
5013 if( IsSpace(c) ){
5014 if( !IsSpace(*z) ) return 0;
5015 while( IsSpace(*zGlob) ) zGlob++;
5016 while( IsSpace(*z) ) z++;
5017 }else if( c=='*' ){
5018 while( (c=(*(zGlob++))) == '*' || c=='?' ){
5019 if( c=='?' && (*(z++))==0 ) return 0;
5020 }
5021 if( c==0 ){
5022 return 1;
5023 }else if( c=='[' ){
5024 while( *z && testcase_glob(zGlob-1,z)==0 ){
5025 z++;
5026 }
5027 return (*z)!=0;
5028 }
5029 while( (c2 = (*(z++)))!=0 ){
5030 while( c2!=c ){
5031 c2 = *(z++);
5032 if( c2==0 ) return 0;
5033 }
5034 if( testcase_glob(zGlob,z) ) return 1;
5035 }
5036 return 0;
5037 }else if( c=='?' ){
5038 if( (*(z++))==0 ) return 0;
5039 }else if( c=='[' ){
5040 int prior_c = 0;
5041 seen = 0;
5042 invert = 0;
5043 c = *(z++);
5044 if( c==0 ) return 0;
5045 c2 = *(zGlob++);
5046 if( c2=='^' ){
5047 invert = 1;
5048 c2 = *(zGlob++);
5049 }
5050 if( c2==']' ){
5051 if( c==']' ) seen = 1;
5052 c2 = *(zGlob++);
5053 }
5054 while( c2 && c2!=']' ){
5055 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5056 c2 = *(zGlob++);
5057 if( c>=prior_c && c<=c2 ) seen = 1;
5058 prior_c = 0;
5059 }else{
5060 if( c==c2 ){
5061 seen = 1;
5062 }
5063 prior_c = c2;
5064 }
5065 c2 = *(zGlob++);
5066 }
5067 if( c2==0 || (seen ^ invert)==0 ) return 0;
5068 }else if( c=='#' ){
5069 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5070 if( !IsDigit(z[0]) ) return 0;
5071 z++;
5072 while( IsDigit(z[0]) ){ z++; }
5073 }else{
5074 if( c!=(*(z++)) ) return 0;
5075 }
5076 }
5077 while( IsSpace(*z) ){ z++; }
5078 return *z==0;
5079}
5080
5081
5082/*
5083** Compare the string as a command-line option with either one or two
5084** initial "-" characters.
5085*/
5086static int optionMatch(const char *zStr, const char *zOpt){
5087 if( zStr[0]!='-' ) return 0;
5088 zStr++;
5089 if( zStr[0]=='-' ) zStr++;
5090 return strcmp(zStr, zOpt)==0;
5091}
5092
5093/*
5094** Delete a file.
5095*/
5096int shellDeleteFile(const char *zFilename){
5097 int rc;
5098#ifdef _WIN32
5099 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5100 rc = _wunlink(z);
5101 sqlite3_free(z);
5102#else
5103 rc = unlink(zFilename);
5104#endif
5105 return rc;
5106}
5107
drh13c20932018-01-10 21:41:55 +00005108/*
5109** Try to delete the temporary file (if there is one) and free the
5110** memory used to hold the name of the temp file.
5111*/
5112static void clearTempFile(ShellState *p){
5113 if( p->zTempFile==0 ) return;
drh536c3452018-01-11 00:38:39 +00005114 if( p->doXdgOpen ) return;
drh13c20932018-01-10 21:41:55 +00005115 if( shellDeleteFile(p->zTempFile) ) return;
5116 sqlite3_free(p->zTempFile);
5117 p->zTempFile = 0;
5118}
5119
5120/*
5121** Create a new temp file name with the given suffix.
5122*/
5123static void newTempFile(ShellState *p, const char *zSuffix){
5124 clearTempFile(p);
5125 sqlite3_free(p->zTempFile);
5126 p->zTempFile = 0;
drh7f3bf8a2018-01-10 21:50:08 +00005127 if( p->db ){
5128 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5129 }
drh13c20932018-01-10 21:41:55 +00005130 if( p->zTempFile==0 ){
5131 sqlite3_uint64 r;
5132 sqlite3_randomness(sizeof(r), &r);
5133 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
5134 }else{
5135 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5136 }
5137 if( p->zTempFile==0 ){
5138 raw_printf(stderr, "out of memory\n");
5139 exit(1);
5140 }
5141}
5142
drh2ce15c32017-07-11 13:34:40 +00005143
5144/*
5145** The implementation of SQL scalar function fkey_collate_clause(), used
5146** by the ".lint fkey-indexes" command. This scalar function is always
5147** called with four arguments - the parent table name, the parent column name,
5148** the child table name and the child column name.
5149**
5150** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5151**
5152** If either of the named tables or columns do not exist, this function
5153** returns an empty string. An empty string is also returned if both tables
5154** and columns exist but have the same default collation sequence. Or,
5155** if both exist but the default collation sequences are different, this
5156** function returns the string " COLLATE <parent-collation>", where
5157** <parent-collation> is the default collation sequence of the parent column.
5158*/
5159static void shellFkeyCollateClause(
5160 sqlite3_context *pCtx,
5161 int nVal,
5162 sqlite3_value **apVal
5163){
5164 sqlite3 *db = sqlite3_context_db_handle(pCtx);
5165 const char *zParent;
5166 const char *zParentCol;
5167 const char *zParentSeq;
5168 const char *zChild;
5169 const char *zChildCol;
5170 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
5171 int rc;
5172
5173 assert( nVal==4 );
5174 zParent = (const char*)sqlite3_value_text(apVal[0]);
5175 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5176 zChild = (const char*)sqlite3_value_text(apVal[2]);
5177 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5178
5179 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5180 rc = sqlite3_table_column_metadata(
5181 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5182 );
5183 if( rc==SQLITE_OK ){
5184 rc = sqlite3_table_column_metadata(
5185 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5186 );
5187 }
5188
5189 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5190 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5191 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5192 sqlite3_free(z);
5193 }
5194}
5195
5196
5197/*
5198** The implementation of dot-command ".lint fkey-indexes".
5199*/
5200static int lintFkeyIndexes(
5201 ShellState *pState, /* Current shell tool state */
5202 char **azArg, /* Array of arguments passed to dot command */
5203 int nArg /* Number of entries in azArg[] */
5204){
5205 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
5206 FILE *out = pState->out; /* Stream to write non-error output to */
5207 int bVerbose = 0; /* If -verbose is present */
5208 int bGroupByParent = 0; /* If -groupbyparent is present */
5209 int i; /* To iterate through azArg[] */
5210 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
5211 int rc; /* Return code */
5212 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
5213
5214 /*
5215 ** This SELECT statement returns one row for each foreign key constraint
5216 ** in the schema of the main database. The column values are:
5217 **
5218 ** 0. The text of an SQL statement similar to:
5219 **
danf9679312017-12-01 18:40:18 +00005220 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00005221 **
danf9679312017-12-01 18:40:18 +00005222 ** This SELECT is similar to the one that the foreign keys implementation
5223 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00005224 ** be used to optimize this query, then it can also be used by the FK
5225 ** implementation to optimize DELETE or UPDATE statements on the parent
5226 ** table.
5227 **
5228 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5229 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5230 ** contains an index that can be used to optimize the query.
5231 **
5232 ** 2. Human readable text that describes the child table and columns. e.g.
5233 **
5234 ** "child_table(child_key1, child_key2)"
5235 **
5236 ** 3. Human readable text that describes the parent table and columns. e.g.
5237 **
5238 ** "parent_table(parent_key1, parent_key2)"
5239 **
5240 ** 4. A full CREATE INDEX statement for an index that could be used to
5241 ** optimize DELETE or UPDATE statements on the parent table. e.g.
5242 **
5243 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
5244 **
5245 ** 5. The name of the parent table.
5246 **
5247 ** These six values are used by the C logic below to generate the report.
5248 */
5249 const char *zSql =
5250 "SELECT "
danf9679312017-12-01 18:40:18 +00005251 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00005252 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5253 " || fkey_collate_clause("
5254 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5255 ", "
5256 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
5257 " || group_concat('*=?', ' AND ') || ')'"
5258 ", "
5259 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
5260 ", "
5261 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5262 ", "
5263 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5264 " || ' ON ' || quote(s.name) || '('"
5265 " || group_concat(quote(f.[from]) ||"
5266 " fkey_collate_clause("
5267 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5268 " || ');'"
5269 ", "
5270 " f.[table] "
5271 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
5272 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5273 "GROUP BY s.name, f.id "
5274 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5275 ;
5276 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
5277
5278 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00005279 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00005280 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5281 bVerbose = 1;
5282 }
5283 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5284 bGroupByParent = 1;
5285 zIndent = " ";
5286 }
5287 else{
5288 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5289 azArg[0], azArg[1]
5290 );
5291 return SQLITE_ERROR;
5292 }
5293 }
5294
5295 /* Register the fkey_collate_clause() SQL function */
5296 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5297 0, shellFkeyCollateClause, 0, 0
5298 );
5299
5300
5301 if( rc==SQLITE_OK ){
5302 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5303 }
5304 if( rc==SQLITE_OK ){
5305 sqlite3_bind_int(pSql, 1, bGroupByParent);
5306 }
5307
5308 if( rc==SQLITE_OK ){
5309 int rc2;
5310 char *zPrev = 0;
5311 while( SQLITE_ROW==sqlite3_step(pSql) ){
5312 int res = -1;
5313 sqlite3_stmt *pExplain = 0;
5314 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5315 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5316 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5317 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5318 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5319 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5320
5321 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5322 if( rc!=SQLITE_OK ) break;
5323 if( SQLITE_ROW==sqlite3_step(pExplain) ){
5324 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5325 res = (
5326 0==sqlite3_strglob(zGlob, zPlan)
5327 || 0==sqlite3_strglob(zGlobIPK, zPlan)
5328 );
5329 }
5330 rc = sqlite3_finalize(pExplain);
5331 if( rc!=SQLITE_OK ) break;
5332
5333 if( res<0 ){
5334 raw_printf(stderr, "Error: internal error");
5335 break;
5336 }else{
5337 if( bGroupByParent
5338 && (bVerbose || res==0)
5339 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5340 ){
5341 raw_printf(out, "-- Parent table %s\n", zParent);
5342 sqlite3_free(zPrev);
5343 zPrev = sqlite3_mprintf("%s", zParent);
5344 }
5345
5346 if( res==0 ){
5347 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5348 }else if( bVerbose ){
5349 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5350 zIndent, zFrom, zTarget
5351 );
5352 }
5353 }
5354 }
5355 sqlite3_free(zPrev);
5356
5357 if( rc!=SQLITE_OK ){
5358 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5359 }
5360
5361 rc2 = sqlite3_finalize(pSql);
5362 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5363 rc = rc2;
5364 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5365 }
5366 }else{
5367 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5368 }
5369
5370 return rc;
5371}
5372
5373/*
5374** Implementation of ".lint" dot command.
5375*/
5376static int lintDotCommand(
5377 ShellState *pState, /* Current shell tool state */
5378 char **azArg, /* Array of arguments passed to dot command */
5379 int nArg /* Number of entries in azArg[] */
5380){
5381 int n;
drhaf2770f2018-01-05 14:55:43 +00005382 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00005383 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5384 return lintFkeyIndexes(pState, azArg, nArg);
5385
5386 usage:
5387 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5388 raw_printf(stderr, "Where sub-commands are:\n");
5389 raw_printf(stderr, " fkey-indexes\n");
5390 return SQLITE_ERROR;
5391}
5392
drhe37c0e12018-01-06 19:19:50 +00005393#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5394/*********************************************************************************
5395** The ".archive" or ".ar" command.
5396*/
danfd0245d2017-12-07 15:44:29 +00005397static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00005398 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00005399 int *pRc,
5400 const char *zSql,
5401 sqlite3_stmt **ppStmt
5402){
5403 *ppStmt = 0;
5404 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00005405 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00005406 if( rc!=SQLITE_OK ){
5407 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00005408 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00005409 );
5410 *pRc = rc;
5411 }
5412 }
5413}
5414
danac15e2d2017-12-14 19:15:07 +00005415static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00005416 sqlite3 *db,
5417 int *pRc,
danac15e2d2017-12-14 19:15:07 +00005418 sqlite3_stmt **ppStmt,
5419 const char *zFmt,
5420 ...
dan3f67ddf2017-12-13 20:04:53 +00005421){
danac15e2d2017-12-14 19:15:07 +00005422 *ppStmt = 0;
5423 if( *pRc==SQLITE_OK ){
5424 va_list ap;
5425 char *z;
5426 va_start(ap, zFmt);
5427 z = sqlite3_vmprintf(zFmt, ap);
drh1dbb1472018-10-11 10:37:24 +00005428 va_end(ap);
dan3f67ddf2017-12-13 20:04:53 +00005429 if( z==0 ){
5430 *pRc = SQLITE_NOMEM;
5431 }else{
5432 shellPrepare(db, pRc, z, ppStmt);
5433 sqlite3_free(z);
5434 }
dan3f67ddf2017-12-13 20:04:53 +00005435 }
5436}
5437
danfd0245d2017-12-07 15:44:29 +00005438static void shellFinalize(
5439 int *pRc,
5440 sqlite3_stmt *pStmt
5441){
dan25c12182017-12-07 21:03:33 +00005442 if( pStmt ){
5443 sqlite3 *db = sqlite3_db_handle(pStmt);
5444 int rc = sqlite3_finalize(pStmt);
5445 if( *pRc==SQLITE_OK ){
5446 if( rc!=SQLITE_OK ){
5447 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5448 }
5449 *pRc = rc;
5450 }
5451 }
danfd0245d2017-12-07 15:44:29 +00005452}
5453
5454static void shellReset(
5455 int *pRc,
5456 sqlite3_stmt *pStmt
5457){
5458 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00005459 if( *pRc==SQLITE_OK ){
5460 if( rc!=SQLITE_OK ){
5461 sqlite3 *db = sqlite3_db_handle(pStmt);
5462 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5463 }
5464 *pRc = rc;
5465 }
danfd0245d2017-12-07 15:44:29 +00005466}
drhe37c0e12018-01-06 19:19:50 +00005467/*
dan88be0202017-12-09 17:58:02 +00005468** Structure representing a single ".ar" command.
5469*/
5470typedef struct ArCommand ArCommand;
5471struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00005472 u8 eCmd; /* An AR_CMD_* value */
5473 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00005474 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00005475 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00005476 u8 bAppend; /* True if --append */
drhd0f9cdc2018-05-17 14:09:06 +00005477 u8 fromCmdLine; /* Run from -A instead of .archive */
drhb376b3d2018-01-10 13:11:51 +00005478 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00005479 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00005480 const char *zFile; /* --file argument, or NULL */
5481 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00005482 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00005483 ShellState *p; /* Shell state */
5484 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00005485};
5486
5487/*
5488** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5489*/
dan0d0547f2017-12-14 15:40:42 +00005490static int arUsage(FILE *f){
drh98aa2ab2018-09-26 16:53:51 +00005491 showHelp(f,"archive");
dan0d0547f2017-12-14 15:40:42 +00005492 return SQLITE_ERROR;
5493}
5494
5495/*
5496** Print an error message for the .ar command to stderr and return
5497** SQLITE_ERROR.
5498*/
drhd0f9cdc2018-05-17 14:09:06 +00005499static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
dan0d0547f2017-12-14 15:40:42 +00005500 va_list ap;
5501 char *z;
5502 va_start(ap, zFmt);
5503 z = sqlite3_vmprintf(zFmt, ap);
5504 va_end(ap);
drhd0f9cdc2018-05-17 14:09:06 +00005505 utf8_printf(stderr, "Error: %s\n", z);
5506 if( pAr->fromCmdLine ){
5507 utf8_printf(stderr, "Use \"-A\" for more help\n");
5508 }else{
5509 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5510 }
dan0d0547f2017-12-14 15:40:42 +00005511 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00005512 return SQLITE_ERROR;
5513}
5514
5515/*
5516** Values for ArCommand.eCmd.
5517*/
dand4b56e52017-12-12 20:04:59 +00005518#define AR_CMD_CREATE 1
drhb17ea912019-03-25 14:24:19 +00005519#define AR_CMD_UPDATE 2
5520#define AR_CMD_INSERT 3
5521#define AR_CMD_EXTRACT 4
5522#define AR_CMD_LIST 5
5523#define AR_CMD_HELP 6
dand4b56e52017-12-12 20:04:59 +00005524
5525/*
5526** Other (non-command) switches.
5527*/
drhb17ea912019-03-25 14:24:19 +00005528#define AR_SWITCH_VERBOSE 7
5529#define AR_SWITCH_FILE 8
5530#define AR_SWITCH_DIRECTORY 9
5531#define AR_SWITCH_APPEND 10
5532#define AR_SWITCH_DRYRUN 11
dand4b56e52017-12-12 20:04:59 +00005533
5534static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5535 switch( eSwitch ){
5536 case AR_CMD_CREATE:
5537 case AR_CMD_EXTRACT:
5538 case AR_CMD_LIST:
5539 case AR_CMD_UPDATE:
drhb17ea912019-03-25 14:24:19 +00005540 case AR_CMD_INSERT:
dan0d0547f2017-12-14 15:40:42 +00005541 case AR_CMD_HELP:
5542 if( pAr->eCmd ){
drhd0f9cdc2018-05-17 14:09:06 +00005543 return arErrorMsg(pAr, "multiple command options");
dan0d0547f2017-12-14 15:40:42 +00005544 }
dand4b56e52017-12-12 20:04:59 +00005545 pAr->eCmd = eSwitch;
5546 break;
5547
drhb376b3d2018-01-10 13:11:51 +00005548 case AR_SWITCH_DRYRUN:
5549 pAr->bDryRun = 1;
5550 break;
dand4b56e52017-12-12 20:04:59 +00005551 case AR_SWITCH_VERBOSE:
5552 pAr->bVerbose = 1;
5553 break;
drha5676c42018-01-10 15:17:34 +00005554 case AR_SWITCH_APPEND:
5555 pAr->bAppend = 1;
drhca7733b2018-01-10 18:09:20 +00005556 /* Fall thru into --file */
dand4b56e52017-12-12 20:04:59 +00005557 case AR_SWITCH_FILE:
5558 pAr->zFile = zArg;
5559 break;
5560 case AR_SWITCH_DIRECTORY:
5561 pAr->zDir = zArg;
5562 break;
5563 }
5564
5565 return SQLITE_OK;
5566}
dan88be0202017-12-09 17:58:02 +00005567
5568/*
5569** Parse the command line for an ".ar" command. The results are written into
5570** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5571** successfully, otherwise an error message is written to stderr and
5572** SQLITE_ERROR returned.
5573*/
5574static int arParseCommand(
5575 char **azArg, /* Array of arguments passed to dot command */
5576 int nArg, /* Number of entries in azArg[] */
5577 ArCommand *pAr /* Populate this object */
5578){
dand4b56e52017-12-12 20:04:59 +00005579 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00005580 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00005581 char cShort;
5582 u8 eSwitch;
5583 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00005584 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00005585 { "create", 'c', AR_CMD_CREATE, 0 },
5586 { "extract", 'x', AR_CMD_EXTRACT, 0 },
drhb17ea912019-03-25 14:24:19 +00005587 { "insert", 'i', AR_CMD_INSERT, 0 },
drhb376b3d2018-01-10 13:11:51 +00005588 { "list", 't', AR_CMD_LIST, 0 },
5589 { "update", 'u', AR_CMD_UPDATE, 0 },
5590 { "help", 'h', AR_CMD_HELP, 0 },
5591 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
5592 { "file", 'f', AR_SWITCH_FILE, 1 },
drhca7733b2018-01-10 18:09:20 +00005593 { "append", 'a', AR_SWITCH_APPEND, 1 },
drhb376b3d2018-01-10 13:11:51 +00005594 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drhb376b3d2018-01-10 13:11:51 +00005595 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00005596 };
5597 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5598 struct ArSwitch *pEnd = &aSwitch[nSwitch];
5599
dan88be0202017-12-09 17:58:02 +00005600 if( nArg<=1 ){
drh98aa2ab2018-09-26 16:53:51 +00005601 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
dan0d0547f2017-12-14 15:40:42 +00005602 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00005603 }else{
5604 char *z = azArg[1];
dan88be0202017-12-09 17:58:02 +00005605 if( z[0]!='-' ){
5606 /* Traditional style [tar] invocation */
5607 int i;
5608 int iArg = 2;
5609 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00005610 const char *zArg = 0;
5611 struct ArSwitch *pOpt;
5612 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5613 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00005614 }
dan0d0547f2017-12-14 15:40:42 +00005615 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005616 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005617 }
dand4b56e52017-12-12 20:04:59 +00005618 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005619 if( iArg>=nArg ){
drhd0f9cdc2018-05-17 14:09:06 +00005620 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005621 }
dand4b56e52017-12-12 20:04:59 +00005622 zArg = azArg[iArg++];
5623 }
5624 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00005625 }
dan88be0202017-12-09 17:58:02 +00005626 pAr->nArg = nArg-iArg;
5627 if( pAr->nArg>0 ){
5628 pAr->azArg = &azArg[iArg];
5629 }
dand4b56e52017-12-12 20:04:59 +00005630 }else{
5631 /* Non-traditional invocation */
5632 int iArg;
5633 for(iArg=1; iArg<nArg; iArg++){
5634 int n;
5635 z = azArg[iArg];
5636 if( z[0]!='-' ){
5637 /* All remaining command line words are command arguments. */
5638 pAr->azArg = &azArg[iArg];
5639 pAr->nArg = nArg-iArg;
5640 break;
5641 }
drhaf2770f2018-01-05 14:55:43 +00005642 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00005643
5644 if( z[1]!='-' ){
5645 int i;
5646 /* One or more short options */
5647 for(i=1; i<n; i++){
5648 const char *zArg = 0;
5649 struct ArSwitch *pOpt;
5650 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5651 if( z[i]==pOpt->cShort ) break;
5652 }
dan0d0547f2017-12-14 15:40:42 +00005653 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005654 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005655 }
dand4b56e52017-12-12 20:04:59 +00005656 if( pOpt->bArg ){
5657 if( i<(n-1) ){
5658 zArg = &z[i+1];
5659 i = n;
5660 }else{
dan0d0547f2017-12-14 15:40:42 +00005661 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005662 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005663 }
dand4b56e52017-12-12 20:04:59 +00005664 zArg = azArg[++iArg];
5665 }
5666 }
5667 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5668 }
5669 }else if( z[2]=='\0' ){
5670 /* A -- option, indicating that all remaining command line words
5671 ** are command arguments. */
5672 pAr->azArg = &azArg[iArg+1];
5673 pAr->nArg = nArg-iArg-1;
5674 break;
5675 }else{
5676 /* A long option */
5677 const char *zArg = 0; /* Argument for option, if any */
5678 struct ArSwitch *pMatch = 0; /* Matching option */
5679 struct ArSwitch *pOpt; /* Iterator */
5680 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5681 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00005682 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00005683 if( pMatch ){
drhd0f9cdc2018-05-17 14:09:06 +00005684 return arErrorMsg(pAr, "ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00005685 }else{
5686 pMatch = pOpt;
5687 }
5688 }
5689 }
5690
5691 if( pMatch==0 ){
drhd0f9cdc2018-05-17 14:09:06 +00005692 return arErrorMsg(pAr, "unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00005693 }
5694 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005695 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005696 return arErrorMsg(pAr, "option requires an argument: %s", z);
dan0d0547f2017-12-14 15:40:42 +00005697 }
dand4b56e52017-12-12 20:04:59 +00005698 zArg = azArg[++iArg];
5699 }
5700 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5701 }
5702 }
dan88be0202017-12-09 17:58:02 +00005703 }
5704 }
5705
5706 return SQLITE_OK;
5707}
5708
5709/*
dan3f67ddf2017-12-13 20:04:53 +00005710** This function assumes that all arguments within the ArCommand.azArg[]
5711** array refer to archive members, as for the --extract or --list commands.
5712** It checks that each of them are present. If any specified file is not
5713** present in the archive, an error is printed to stderr and an error
5714** code returned. Otherwise, if all specified arguments are present in
5715** the archive, SQLITE_OK is returned.
5716**
5717** This function strips any trailing '/' characters from each argument.
5718** This is consistent with the way the [tar] command seems to work on
5719** Linux.
5720*/
drhb376b3d2018-01-10 13:11:51 +00005721static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00005722 int rc = SQLITE_OK;
5723 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00005724 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00005725 sqlite3_stmt *pTest = 0;
5726
drhb376b3d2018-01-10 13:11:51 +00005727 shellPreparePrintf(pAr->db, &rc, &pTest,
5728 "SELECT name FROM %s WHERE name=$name",
5729 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00005730 );
drhb376b3d2018-01-10 13:11:51 +00005731 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00005732 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5733 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00005734 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00005735 int bOk = 0;
5736 while( n>0 && z[n-1]=='/' ) n--;
5737 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00005738 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00005739 if( SQLITE_ROW==sqlite3_step(pTest) ){
5740 bOk = 1;
5741 }
5742 shellReset(&rc, pTest);
5743 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00005744 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00005745 rc = SQLITE_ERROR;
5746 }
5747 }
5748 shellFinalize(&rc, pTest);
5749 }
dan3f67ddf2017-12-13 20:04:53 +00005750 return rc;
5751}
5752
5753/*
5754** Format a WHERE clause that can be used against the "sqlar" table to
5755** identify all archive members that match the command arguments held
5756** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5757** The caller is responsible for eventually calling sqlite3_free() on
5758** any non-NULL (*pzWhere) value.
5759*/
5760static void arWhereClause(
5761 int *pRc,
5762 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00005763 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00005764){
5765 char *zWhere = 0;
5766 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00005767 if( pAr->nArg==0 ){
5768 zWhere = sqlite3_mprintf("1");
5769 }else{
5770 int i;
5771 const char *zSep = "";
5772 for(i=0; i<pAr->nArg; i++){
5773 const char *z = pAr->azArg[i];
5774 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00005775 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5776 zWhere, zSep, z, strlen30(z)+1, z
5777 );
danac15e2d2017-12-14 19:15:07 +00005778 if( zWhere==0 ){
5779 *pRc = SQLITE_NOMEM;
5780 break;
5781 }
5782 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00005783 }
dan3f67ddf2017-12-13 20:04:53 +00005784 }
5785 }
5786 *pzWhere = zWhere;
5787}
5788
5789/*
dan88be0202017-12-09 17:58:02 +00005790** Implementation of .ar "lisT" command.
5791*/
drhb376b3d2018-01-10 13:11:51 +00005792static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00005793 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00005794 const char *azCols[] = {
5795 "name",
drh410cad92018-01-10 17:19:16 +00005796 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00005797 };
dan5a78b812017-12-27 18:54:11 +00005798
dan3f67ddf2017-12-13 20:04:53 +00005799 char *zWhere = 0;
5800 sqlite3_stmt *pSql = 0;
5801 int rc;
5802
drhb376b3d2018-01-10 13:11:51 +00005803 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005804 arWhereClause(&rc, pAr, &zWhere);
5805
drhb376b3d2018-01-10 13:11:51 +00005806 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5807 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00005808 if( pAr->bDryRun ){
5809 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5810 }else{
5811 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5812 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00005813 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5814 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00005815 sqlite3_column_int(pSql, 1),
5816 sqlite3_column_text(pSql, 2),
5817 sqlite3_column_text(pSql, 3)
5818 );
5819 }else{
5820 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5821 }
danb5090e42017-12-27 21:13:21 +00005822 }
dan3f67ddf2017-12-13 20:04:53 +00005823 }
dan5a78b812017-12-27 18:54:11 +00005824 shellFinalize(&rc, pSql);
drhd0f9cdc2018-05-17 14:09:06 +00005825 sqlite3_free(zWhere);
dan3f67ddf2017-12-13 20:04:53 +00005826 return rc;
dan88be0202017-12-09 17:58:02 +00005827}
5828
5829
danfd0245d2017-12-07 15:44:29 +00005830/*
5831** Implementation of .ar "eXtract" command.
5832*/
drhb376b3d2018-01-10 13:11:51 +00005833static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00005834 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00005835 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00005836 " ($dir || name),"
5837 " writefile(($dir || name), %s, mode, mtime) "
drh0cfd46a2018-06-06 01:18:01 +00005838 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5839 " AND name NOT GLOB '*..[/\\]*'";
dan5a78b812017-12-27 18:54:11 +00005840
5841 const char *azExtraArg[] = {
5842 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00005843 "data"
dan5a78b812017-12-27 18:54:11 +00005844 };
dan5a78b812017-12-27 18:54:11 +00005845
danfd0245d2017-12-07 15:44:29 +00005846 sqlite3_stmt *pSql = 0;
5847 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00005848 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00005849 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00005850 int i, j;
dan2ad09492017-12-09 18:28:22 +00005851
dan3f67ddf2017-12-13 20:04:53 +00005852 /* If arguments are specified, check that they actually exist within
5853 ** the archive before proceeding. And formulate a WHERE clause to
5854 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00005855 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005856 arWhereClause(&rc, pAr, &zWhere);
5857
5858 if( rc==SQLITE_OK ){
5859 if( pAr->zDir ){
5860 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5861 }else{
5862 zDir = sqlite3_mprintf("");
5863 }
5864 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00005865 }
danfd0245d2017-12-07 15:44:29 +00005866
drhb376b3d2018-01-10 13:11:51 +00005867 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5868 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00005869 );
5870
dan2ad09492017-12-09 18:28:22 +00005871 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005872 j = sqlite3_bind_parameter_index(pSql, "$dir");
5873 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00005874
danac15e2d2017-12-14 19:15:07 +00005875 /* Run the SELECT statement twice. The first time, writefile() is called
5876 ** for all archive members that should be extracted. The second time,
5877 ** only for the directories. This is because the timestamps for
5878 ** extracted directories must be reset after they are populated (as
5879 ** populating them changes the timestamp). */
5880 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00005881 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5882 sqlite3_bind_int(pSql, j, i);
5883 if( pAr->bDryRun ){
5884 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5885 }else{
5886 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5887 if( i==0 && pAr->bVerbose ){
5888 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5889 }
danac15e2d2017-12-14 19:15:07 +00005890 }
5891 }
5892 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005893 }
danac15e2d2017-12-14 19:15:07 +00005894 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005895 }
dan25c12182017-12-07 21:03:33 +00005896
dan2ad09492017-12-09 18:28:22 +00005897 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00005898 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00005899 return rc;
5900}
5901
drhb376b3d2018-01-10 13:11:51 +00005902/*
5903** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5904*/
5905static int arExecSql(ArCommand *pAr, const char *zSql){
5906 int rc;
5907 if( pAr->bDryRun ){
5908 utf8_printf(pAr->p->out, "%s\n", zSql);
5909 rc = SQLITE_OK;
5910 }else{
drh410cad92018-01-10 17:19:16 +00005911 char *zErr = 0;
5912 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5913 if( zErr ){
5914 utf8_printf(stdout, "ERROR: %s\n", zErr);
5915 sqlite3_free(zErr);
5916 }
drhb376b3d2018-01-10 13:11:51 +00005917 }
5918 return rc;
5919}
5920
dan1ad3f612017-12-11 20:22:02 +00005921
danfd0245d2017-12-07 15:44:29 +00005922/*
drhb17ea912019-03-25 14:24:19 +00005923** Implementation of .ar "create", "insert", and "update" commands.
5924**
5925** create -> Create a new SQL archive
5926** insert -> Insert or reinsert all files listed
5927** update -> Insert files that have changed or that were not
5928** previously in the archive
danfd0245d2017-12-07 15:44:29 +00005929**
5930** Create the "sqlar" table in the database if it does not already exist.
5931** Then add each file in the azFile[] array to the archive. Directories
5932** are added recursively. If argument bVerbose is non-zero, a message is
5933** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00005934**
5935** The create command is the same as update, except that it drops
drhb17ea912019-03-25 14:24:19 +00005936** any existing "sqlar" table before beginning. The "insert" command
5937** always overwrites every file named on the command-line, where as
5938** "update" only overwrites if the size or mtime or mode has changed.
danfd0245d2017-12-07 15:44:29 +00005939*/
drhb376b3d2018-01-10 13:11:51 +00005940static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00005941 ArCommand *pAr, /* Command arguments and options */
drhb17ea912019-03-25 14:24:19 +00005942 int bUpdate, /* true for a --create. */
5943 int bOnlyIfChanged /* Only update if file has changed */
danfd0245d2017-12-07 15:44:29 +00005944){
dand4b56e52017-12-12 20:04:59 +00005945 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00005946 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5947 " name TEXT PRIMARY KEY, -- name of the file\n"
5948 " mode INT, -- access permissions\n"
5949 " mtime INT, -- last modification time\n"
5950 " sz INT, -- original file size\n"
5951 " data BLOB -- compressed content\n"
5952 ")";
dand4b56e52017-12-12 20:04:59 +00005953 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh1bf208c2018-03-09 21:54:01 +00005954 const char *zInsertFmt[2] = {
5955 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
drh634c70f2018-01-10 16:50:18 +00005956 " SELECT\n"
5957 " %s,\n"
5958 " mode,\n"
5959 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00005960 " CASE substr(lsmode(mode),1,1)\n"
5961 " WHEN '-' THEN length(data)\n"
5962 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00005963 " ELSE -1 END,\n"
drh69d2d352018-03-09 22:18:53 +00005964 " sqlar_compress(data)\n"
drhb17ea912019-03-25 14:24:19 +00005965 " FROM fsdir(%Q,%Q) AS disk\n"
5966 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
5967 ,
drh1bf208c2018-03-09 21:54:01 +00005968 "REPLACE INTO %s(name,mode,mtime,data)\n"
5969 " SELECT\n"
5970 " %s,\n"
5971 " mode,\n"
5972 " mtime,\n"
5973 " data\n"
drhb17ea912019-03-25 14:24:19 +00005974 " FROM fsdir(%Q,%Q) AS disk\n"
5975 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
drh1bf208c2018-03-09 21:54:01 +00005976 };
danfd0245d2017-12-07 15:44:29 +00005977 int i; /* For iterating through azFile[] */
5978 int rc; /* Return code */
drh1bf208c2018-03-09 21:54:01 +00005979 const char *zTab = 0; /* SQL table into which to insert */
5980 char *zSql;
5981 char zTemp[50];
drhb17ea912019-03-25 14:24:19 +00005982 char *zExists = 0;
danfd0245d2017-12-07 15:44:29 +00005983
drh1bf208c2018-03-09 21:54:01 +00005984 arExecSql(pAr, "PRAGMA page_size=512");
drhb376b3d2018-01-10 13:11:51 +00005985 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00005986 if( rc!=SQLITE_OK ) return rc;
drh1bf208c2018-03-09 21:54:01 +00005987 zTemp[0] = 0;
5988 if( pAr->bZip ){
5989 /* Initialize the zipfile virtual table, if necessary */
5990 if( pAr->zFile ){
5991 sqlite3_uint64 r;
5992 sqlite3_randomness(sizeof(r),&r);
5993 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5994 zTab = zTemp;
5995 zSql = sqlite3_mprintf(
5996 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5997 zTab, pAr->zFile
5998 );
5999 rc = arExecSql(pAr, zSql);
6000 sqlite3_free(zSql);
6001 }else{
6002 zTab = "zip";
6003 }
6004 }else{
6005 /* Initialize the table for an SQLAR */
6006 zTab = "sqlar";
6007 if( bUpdate==0 ){
6008 rc = arExecSql(pAr, zDrop);
6009 if( rc!=SQLITE_OK ) goto end_ar_transaction;
6010 }
6011 rc = arExecSql(pAr, zCreate);
dan06741a32017-12-13 20:17:18 +00006012 }
drhb17ea912019-03-25 14:24:19 +00006013 if( bOnlyIfChanged ){
6014 zExists = sqlite3_mprintf(
6015 " AND NOT EXISTS("
6016 "SELECT 1 FROM %s AS mem"
6017 " WHERE mem.name=disk.name"
6018 " AND mem.mtime=disk.mtime"
6019 " AND mem.mode=disk.mode)", zTab);
6020 }else{
6021 zExists = sqlite3_mprintf("");
6022 }
6023 if( zExists==0 ) rc = SQLITE_NOMEM;
dan88be0202017-12-09 17:58:02 +00006024 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
mistachkince2052b2018-03-23 00:31:53 +00006025 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
drh634c70f2018-01-10 16:50:18 +00006026 pAr->bVerbose ? "shell_putsnl(name)" : "name",
drhb17ea912019-03-25 14:24:19 +00006027 pAr->azArg[i], pAr->zDir, zExists);
mistachkince2052b2018-03-23 00:31:53 +00006028 rc = arExecSql(pAr, zSql2);
6029 sqlite3_free(zSql2);
danfd0245d2017-12-07 15:44:29 +00006030 }
drh1bf208c2018-03-09 21:54:01 +00006031end_ar_transaction:
danfd0245d2017-12-07 15:44:29 +00006032 if( rc!=SQLITE_OK ){
drh2bd207f2019-01-11 17:19:59 +00006033 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00006034 }else{
drhb376b3d2018-01-10 13:11:51 +00006035 rc = arExecSql(pAr, "RELEASE ar;");
drh1bf208c2018-03-09 21:54:01 +00006036 if( pAr->bZip && pAr->zFile ){
6037 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6038 arExecSql(pAr, zSql);
6039 sqlite3_free(zSql);
6040 }
danfd0245d2017-12-07 15:44:29 +00006041 }
drhb17ea912019-03-25 14:24:19 +00006042 sqlite3_free(zExists);
danfd0245d2017-12-07 15:44:29 +00006043 return rc;
6044}
6045
6046/*
6047** Implementation of ".ar" dot command.
6048*/
6049static int arDotCommand(
6050 ShellState *pState, /* Current shell tool state */
drhd0f9cdc2018-05-17 14:09:06 +00006051 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
danfd0245d2017-12-07 15:44:29 +00006052 char **azArg, /* Array of arguments passed to dot command */
6053 int nArg /* Number of entries in azArg[] */
6054){
dan88be0202017-12-09 17:58:02 +00006055 ArCommand cmd;
6056 int rc;
drh34660642018-01-10 17:39:54 +00006057 memset(&cmd, 0, sizeof(cmd));
drhd0f9cdc2018-05-17 14:09:06 +00006058 cmd.fromCmdLine = fromCmdLine;
dan88be0202017-12-09 17:58:02 +00006059 rc = arParseCommand(azArg, nArg, &cmd);
6060 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00006061 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00006062 cmd.p = pState;
6063 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00006064 if( cmd.zFile ){
drh1bf208c2018-03-09 21:54:01 +00006065 eDbType = deduceDatabaseType(cmd.zFile, 1);
drha5676c42018-01-10 15:17:34 +00006066 }else{
6067 eDbType = pState->openMode;
6068 }
6069 if( eDbType==SHELL_OPEN_ZIPFILE ){
drh1bf208c2018-03-09 21:54:01 +00006070 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6071 if( cmd.zFile==0 ){
6072 cmd.zSrcTable = sqlite3_mprintf("zip");
6073 }else{
6074 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6075 }
dan5a78b812017-12-27 18:54:11 +00006076 }
drha5676c42018-01-10 15:17:34 +00006077 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00006078 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00006079 int flags;
drha5676c42018-01-10 15:17:34 +00006080 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
drhb17ea912019-03-25 14:24:19 +00006081 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6082 || cmd.eCmd==AR_CMD_UPDATE ){
dand4b56e52017-12-12 20:04:59 +00006083 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6084 }else{
6085 flags = SQLITE_OPEN_READONLY;
6086 }
drha82c95b2018-01-10 14:00:00 +00006087 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00006088 if( cmd.bDryRun ){
6089 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6090 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6091 }
6092 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6093 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00006094 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00006095 utf8_printf(stderr, "cannot open file: %s (%s)\n",
6096 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00006097 );
drha5676c42018-01-10 15:17:34 +00006098 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00006099 }
drhb376b3d2018-01-10 13:11:51 +00006100 sqlite3_fileio_init(cmd.db, 0, 0);
drhb376b3d2018-01-10 13:11:51 +00006101 sqlite3_sqlar_init(cmd.db, 0, 0);
drh34660642018-01-10 17:39:54 +00006102 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6103 shellPutsFunc, 0, 0);
6104
dand4b56e52017-12-12 20:04:59 +00006105 }
drhd0f9cdc2018-05-17 14:09:06 +00006106 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
drh634c70f2018-01-10 16:50:18 +00006107 if( cmd.eCmd!=AR_CMD_CREATE
6108 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6109 ){
drha5676c42018-01-10 15:17:34 +00006110 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6111 rc = SQLITE_ERROR;
6112 goto end_ar_command;
6113 }
6114 cmd.zSrcTable = sqlite3_mprintf("sqlar");
6115 }
dand4b56e52017-12-12 20:04:59 +00006116
dan88be0202017-12-09 17:58:02 +00006117 switch( cmd.eCmd ){
6118 case AR_CMD_CREATE:
drhb17ea912019-03-25 14:24:19 +00006119 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
dan88be0202017-12-09 17:58:02 +00006120 break;
danfd0245d2017-12-07 15:44:29 +00006121
dan88be0202017-12-09 17:58:02 +00006122 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00006123 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00006124 break;
6125
6126 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00006127 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00006128 break;
6129
dan0d0547f2017-12-14 15:40:42 +00006130 case AR_CMD_HELP:
6131 arUsage(pState->out);
6132 break;
6133
drhb17ea912019-03-25 14:24:19 +00006134 case AR_CMD_INSERT:
6135 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6136 break;
6137
dan88be0202017-12-09 17:58:02 +00006138 default:
6139 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb17ea912019-03-25 14:24:19 +00006140 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
dan88be0202017-12-09 17:58:02 +00006141 break;
danfd0245d2017-12-07 15:44:29 +00006142 }
6143 }
drha5676c42018-01-10 15:17:34 +00006144end_ar_command:
6145 if( cmd.db!=pState->db ){
drh9e804032018-05-18 17:11:50 +00006146 close_db(cmd.db);
drha5676c42018-01-10 15:17:34 +00006147 }
6148 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00006149
dan88be0202017-12-09 17:58:02 +00006150 return rc;
danfd0245d2017-12-07 15:44:29 +00006151}
drhe37c0e12018-01-06 19:19:50 +00006152/* End of the ".archive" or ".ar" command logic
6153**********************************************************************************/
6154#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00006155
dan68cb86e2019-04-20 20:57:28 +00006156static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6157 int rc = *pRc;
6158 if( rc==SQLITE_OK ){
6159 char *zErr = 0;
6160 rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6161 if( rc!=SQLITE_OK ){
6162 raw_printf(stderr, "SQL error: %s\n", zErr);
6163 }
6164 *pRc = rc;
6165 }
6166}
6167
danc0b42432019-04-26 15:14:53 +00006168static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6169 char *z = 0;
6170 if( *pRc==SQLITE_OK ){
6171 va_list ap;
6172 va_start(ap, zFmt);
6173 z = sqlite3_vmprintf(zFmt, ap);
6174 va_end(ap);
6175 if( z==0 ){
6176 *pRc = SQLITE_NOMEM;
6177 }else{
6178 shellExec(db, pRc, z);
6179 }
6180 sqlite3_free(z);
6181 }
6182}
6183
dan68cb86e2019-04-20 20:57:28 +00006184static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6185 void *pRet = 0;
6186 if( *pRc==SQLITE_OK ){
6187 pRet = sqlite3_malloc64(nByte);
6188 if( pRet==0 ){
6189 *pRc = SQLITE_NOMEM;
6190 }else{
6191 memset(pRet, 0, nByte);
6192 }
6193 }
6194 return pRet;
6195}
6196
6197static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6198 char *z = 0;
6199 if( *pRc==SQLITE_OK ){
6200 va_list ap;
6201 va_start(ap, zFmt);
6202 z = sqlite3_vmprintf(zFmt, ap);
6203 va_end(ap);
6204 if( z==0 ){
6205 *pRc = SQLITE_NOMEM;
6206 }
6207 }
6208 return z;
6209}
6210
6211typedef struct RecoverTable RecoverTable;
6212struct RecoverTable {
6213 char *zName; /* Name of table */
6214 char *zQuoted; /* Quoted version of zName */
dan68cb86e2019-04-20 20:57:28 +00006215 int nCol; /* Number of columns in table */
6216 char **azlCol; /* Array of column lists */
danb40af492019-04-22 20:52:12 +00006217 int iPk;
dan68cb86e2019-04-20 20:57:28 +00006218};
6219
6220/*
6221** Free a RecoverTable object allocated by recoverNewTable()
6222*/
6223static void recoverFreeTable(RecoverTable *pTab){
6224 if( pTab ){
6225 sqlite3_free(pTab->zName);
6226 sqlite3_free(pTab->zQuoted);
dan68cb86e2019-04-20 20:57:28 +00006227 if( pTab->azlCol ){
6228 int i;
dan98c5ad32019-04-26 21:11:37 +00006229 for(i=0; i<=pTab->nCol; i++){
dan68cb86e2019-04-20 20:57:28 +00006230 sqlite3_free(pTab->azlCol[i]);
6231 }
6232 sqlite3_free(pTab->azlCol);
6233 }
6234 sqlite3_free(pTab);
6235 }
6236}
6237
dan98c5ad32019-04-26 21:11:37 +00006238static RecoverTable *recoverOldTable(
danb40af492019-04-22 20:52:12 +00006239 int *pRc, /* IN/OUT: Error code */
danb40af492019-04-22 20:52:12 +00006240 const char *zName, /* Name of table */
6241 const char *zSql, /* CREATE TABLE statement */
6242 int bIntkey,
6243 int nCol
6244){
6245 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */
6246 int rc = *pRc;
dan98c5ad32019-04-26 21:11:37 +00006247 RecoverTable *pTab = 0;
danb40af492019-04-22 20:52:12 +00006248
dan98c5ad32019-04-26 21:11:37 +00006249 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
danb40af492019-04-22 20:52:12 +00006250 if( rc==SQLITE_OK ){
6251 int nSqlCol = 0;
6252 int bSqlIntkey = 0;
6253 sqlite3_stmt *pStmt = 0;
dan98c5ad32019-04-26 21:11:37 +00006254
danb40af492019-04-22 20:52:12 +00006255 rc = sqlite3_open("", &dbtmp);
6256 if( rc==SQLITE_OK ){
dan38f9c712019-04-23 18:03:02 +00006257 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
6258 }
6259 if( rc==SQLITE_OK ){
danb40af492019-04-22 20:52:12 +00006260 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
6261 if( rc==SQLITE_ERROR ){
6262 rc = SQLITE_OK;
6263 goto finished;
6264 }
6265 }
6266 shellPreparePrintf(dbtmp, &rc, &pStmt,
6267 "SELECT count(*) FROM pragma_table_info(%Q)", zName
6268 );
6269 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6270 nSqlCol = sqlite3_column_int(pStmt, 0);
6271 }
6272 shellFinalize(&rc, pStmt);
6273
6274 if( rc!=SQLITE_OK || nSqlCol<nCol ){
6275 goto finished;
6276 }
6277
6278 shellPreparePrintf(dbtmp, &rc, &pStmt,
6279 "SELECT ("
6280 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
6281 ") FROM sqlite_master WHERE name = %Q", zName
6282 );
6283 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6284 bSqlIntkey = sqlite3_column_int(pStmt, 0);
6285 }
6286 shellFinalize(&rc, pStmt);
6287
6288 if( bIntkey==bSqlIntkey ){
dan98c5ad32019-04-26 21:11:37 +00006289 int i;
danb40af492019-04-22 20:52:12 +00006290 const char *zPk = "_rowid_";
6291 sqlite3_stmt *pPkFinder = 0;
6292
danf57bea32019-04-27 15:35:45 +00006293 /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
6294 ** set zPk to the name of the PK column, and pTab->iPk to the index
6295 ** of the column, where columns are 0-numbered from left to right.
6296 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
6297 ** leave zPk as "_rowid_" and pTab->iPk at -2. */
dan98c5ad32019-04-26 21:11:37 +00006298 pTab->iPk = -2;
6299 if( bIntkey ){
6300 shellPreparePrintf(dbtmp, &rc, &pPkFinder,
danb40af492019-04-22 20:52:12 +00006301 "SELECT cid, name FROM pragma_table_info(%Q) "
6302 " WHERE pk=1 AND type='integer' COLLATE nocase"
dan98c5ad32019-04-26 21:11:37 +00006303 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
6304 , zName, zName
6305 );
6306 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
6307 pTab->iPk = sqlite3_column_int(pPkFinder, 0);
6308 zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
6309 }
danb40af492019-04-22 20:52:12 +00006310 }
6311
6312 pTab->zName = shellMPrintf(&rc, "%s", zName);
6313 pTab->zQuoted = shellMPrintf(&rc, "%Q", pTab->zName);
dan98c5ad32019-04-26 21:11:37 +00006314 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
danb40af492019-04-22 20:52:12 +00006315 pTab->nCol = nSqlCol;
6316
dan98c5ad32019-04-26 21:11:37 +00006317 if( bIntkey ){
danb40af492019-04-22 20:52:12 +00006318 pTab->azlCol[0] = shellMPrintf(&rc, "%Q", zPk);
6319 }else{
dan98c5ad32019-04-26 21:11:37 +00006320 pTab->azlCol[0] = shellMPrintf(&rc, "");
danb40af492019-04-22 20:52:12 +00006321 }
dan98c5ad32019-04-26 21:11:37 +00006322 i = 1;
6323 shellPreparePrintf(dbtmp, &rc, &pStmt,
6324 "SELECT %Q || group_concat(name, ', ') "
danf57bea32019-04-27 15:35:45 +00006325 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
dan98c5ad32019-04-26 21:11:37 +00006326 "FROM pragma_table_info(%Q)",
danf57bea32019-04-27 15:35:45 +00006327 bIntkey ? ", " : "", pTab->iPk,
6328 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
6329 zName
dan98c5ad32019-04-26 21:11:37 +00006330 );
6331 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6332 const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
6333 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
6334 i++;
6335 }
6336 shellFinalize(&rc, pStmt);
6337
danb40af492019-04-22 20:52:12 +00006338 shellFinalize(&rc, pPkFinder);
6339 }
6340 }
6341
6342 finished:
6343 sqlite3_close(dbtmp);
6344 *pRc = rc;
dan98c5ad32019-04-26 21:11:37 +00006345 if( rc!=SQLITE_OK ){
6346 recoverFreeTable(pTab);
6347 pTab = 0;
6348 }
6349 return pTab;
danb40af492019-04-22 20:52:12 +00006350}
6351
dan68cb86e2019-04-20 20:57:28 +00006352static RecoverTable *recoverNewTable(
6353 ShellState *pState,
6354 int *pRc,
6355 int iRoot,
danb40af492019-04-22 20:52:12 +00006356 int bIntkey,
dan98c5ad32019-04-26 21:11:37 +00006357 int nCol,
6358 int *pbNoop
dan68cb86e2019-04-20 20:57:28 +00006359){
danb40af492019-04-22 20:52:12 +00006360 sqlite3_stmt *pStmt = 0;
dan68cb86e2019-04-20 20:57:28 +00006361 RecoverTable *pRet = 0;
danb40af492019-04-22 20:52:12 +00006362 int bNoop = 0;
6363 const char *zSql = 0;
6364 const char *zName = 0;
dan68cb86e2019-04-20 20:57:28 +00006365
danb40af492019-04-22 20:52:12 +00006366
6367 /* Search the recovered schema for an object with root page iRoot. */
6368 shellPreparePrintf(pState->db, pRc, &pStmt,
6369 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
6370 );
6371 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6372 const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
6373 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
6374 bNoop = 1;
6375 break;
6376 }
6377 if( sqlite3_stricmp(zType, "table")==0 ){
6378 zName = (const char*)sqlite3_column_text(pStmt, 1);
6379 zSql = (const char*)sqlite3_column_text(pStmt, 2);
dan98c5ad32019-04-26 21:11:37 +00006380 pRet = recoverOldTable(pRc, zName, zSql, bIntkey, nCol);
danb40af492019-04-22 20:52:12 +00006381 break;
6382 }
6383 }
dan98c5ad32019-04-26 21:11:37 +00006384
danb40af492019-04-22 20:52:12 +00006385 shellFinalize(pRc, pStmt);
dan98c5ad32019-04-26 21:11:37 +00006386 *pbNoop = bNoop;
6387 return pRet;
6388}
danb40af492019-04-22 20:52:12 +00006389
dan98c5ad32019-04-26 21:11:37 +00006390static RecoverTable *recoverOrphanTable(
6391 ShellState *pState,
6392 int *pRc,
6393 int nCol
6394){
6395 RecoverTable *pTab = 0;
6396 if( nCol>=0 && *pRc==SQLITE_OK ){
6397 int i;
6398 raw_printf(pState->out,
6399 "CREATE TABLE recover_orphan(rootpgno INTEGER, "
6400 "pgno INTEGER, nfield INTEGER, id INTEGER"
dan68cb86e2019-04-20 20:57:28 +00006401 );
dan98c5ad32019-04-26 21:11:37 +00006402 for(i=0; i<nCol; i++){
6403 raw_printf(pState->out, ", c%d", i);
dan68cb86e2019-04-20 20:57:28 +00006404 }
dan98c5ad32019-04-26 21:11:37 +00006405 raw_printf(pState->out, ");\n");
dan68cb86e2019-04-20 20:57:28 +00006406
dan98c5ad32019-04-26 21:11:37 +00006407 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
6408 if( pTab ){
6409 pTab->zName = shellMPrintf(pRc, "%s", "recover_orphan");
6410 pTab->zQuoted = shellMPrintf(pRc, "%Q", pTab->zName);
6411 pTab->nCol = nCol;
6412 pTab->iPk = -2;
6413 if( nCol>0 ){
6414 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
6415 if( pTab->azlCol ){
6416 pTab->azlCol[nCol] = shellMPrintf(pRc, "");
6417 for(i=nCol-1; i>=0; i--){
6418 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
6419 }
6420 }
danb40af492019-04-22 20:52:12 +00006421 }
6422 }
dan68cb86e2019-04-20 20:57:28 +00006423
dan98c5ad32019-04-26 21:11:37 +00006424 if( *pRc!=SQLITE_OK ){
6425 recoverFreeTable(pTab);
6426 pTab = 0;
6427 }
dan68cb86e2019-04-20 20:57:28 +00006428 }
dan98c5ad32019-04-26 21:11:37 +00006429 return pTab;
dan68cb86e2019-04-20 20:57:28 +00006430}
6431
6432/*
6433** This function is called to recover data from the database. A script
6434** to construct a new database containing all recovered data is output
6435** on stream pState->out.
6436*/
danb9b71db2019-04-25 16:20:40 +00006437static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
dan68cb86e2019-04-20 20:57:28 +00006438 int rc = SQLITE_OK;
6439 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */
danefa363b2019-04-24 20:48:55 +00006440 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */
6441 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */
danc0b42432019-04-26 15:14:53 +00006442 const char *zRecoveryDb = ""; /* Name of "recovery" database */
dan9c014f82019-04-25 19:23:15 +00006443 int i;
dan98c5ad32019-04-26 21:11:37 +00006444 int nOrphan = -1;
6445 RecoverTable *pOrphan = 0;
dan9c014f82019-04-25 19:23:15 +00006446
6447 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */
6448 for(i=1; i<nArg; i++){
6449 char *z = azArg[i];
6450 int n;
6451 if( z[0]=='-' && z[1]=='-' ) z++;
6452 n = strlen(z);
6453 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
6454 bFreelist = 0;
6455 }
danc0b42432019-04-26 15:14:53 +00006456 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
6457 i++;
6458 zRecoveryDb = azArg[i];
6459 }
dan9c014f82019-04-25 19:23:15 +00006460 else{
danc0b42432019-04-26 15:14:53 +00006461 raw_printf(stderr, "unexpected option: %s\n", azArg[i]);
6462 raw_printf(stderr, "options are:\n");
6463 raw_printf(stderr, " --freelist-corrupt\n");
6464 raw_printf(stderr, " --recovery-db DATABASE\n");
dan9c014f82019-04-25 19:23:15 +00006465 return 1;
6466 }
6467 }
dan68cb86e2019-04-20 20:57:28 +00006468
danc0b42432019-04-26 15:14:53 +00006469 shellExecPrintf(pState->db, &rc,
dan68cb86e2019-04-20 20:57:28 +00006470 /* Attach an in-memory database named 'recovery'. Create an indexed
6471 ** cache of the sqlite_dbptr virtual table. */
danc0b42432019-04-26 15:14:53 +00006472 "ATTACH %Q AS recovery;"
6473 "DROP TABLE IF EXISTS recovery.dbptr;"
6474 "DROP TABLE IF EXISTS recovery.freelist;"
6475 "DROP TABLE IF EXISTS recovery.map;"
6476 "DROP TABLE IF EXISTS recovery.schema;"
danc0b42432019-04-26 15:14:53 +00006477 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
dan9c014f82019-04-25 19:23:15 +00006478 );
6479
6480 if( bFreelist ){
6481 shellExec(pState->db, &rc,
6482 "WITH trunk(pgno) AS ("
6483 " SELECT shell_int32("
6484 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
6485 " WHERE x>0"
6486 " UNION"
6487 " SELECT shell_int32("
6488 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
6489 " FROM trunk WHERE x>0"
6490 "),"
6491 "freelist(data, n, freepgno) AS ("
6492 " SELECT data, shell_int32(data, 1)-1, t.pgno "
6493 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
6494 " UNION ALL"
6495 " SELECT data, n-1, shell_int32(data, 2+n) "
6496 " FROM freelist WHERE n>=0"
6497 ")"
6498 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
6499 );
6500 }
6501
6502 shellExec(pState->db, &rc,
danca424382019-04-26 15:40:27 +00006503 "CREATE TABLE recovery.dbptr("
6504 " pgno, child, PRIMARY KEY(child, pgno)"
6505 ") WITHOUT ROWID;"
6506 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
6507 " SELECT * FROM sqlite_dbptr"
6508 " WHERE pgno NOT IN freelist AND child NOT IN freelist;"
6509
6510 /* Delete any pointer to page 1. This ensures that page 1 is considered
6511 ** a root page, regardless of how corrupt the db is. */
6512 "DELETE FROM recovery.dbptr WHERE child = 1;"
6513
6514 /* Delete all pointers to any pages that have more than one pointer
6515 ** to them. Such pages will be treated as root pages when recovering
6516 ** data. */
6517 "DELETE FROM recovery.dbptr WHERE child IN ("
6518 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
6519 ");"
6520
dan68cb86e2019-04-20 20:57:28 +00006521 /* Create the "map" table that will (eventually) contain instructions
6522 ** for dealing with each page in the db that contains one or more
6523 ** records. */
danb40af492019-04-22 20:52:12 +00006524 "CREATE TABLE recovery.map("
6525 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
6526 ");"
dan68cb86e2019-04-20 20:57:28 +00006527
6528 /* Populate table [map]. If there are circular loops of pages in the
6529 ** database, the following adds all pages in such a loop to the map
6530 ** as individual root pages. This could be handled better. */
6531 "WITH pages(i, maxlen) AS ("
danb9b71db2019-04-25 16:20:40 +00006532 " SELECT page_count, ("
6533 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
6534 " ) FROM pragma_page_count"
dan68cb86e2019-04-20 20:57:28 +00006535 " UNION ALL"
danb40af492019-04-22 20:52:12 +00006536 " SELECT i-1, ("
6537 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
6538 " ) FROM pages WHERE i>=2"
dan68cb86e2019-04-20 20:57:28 +00006539 ")"
danb40af492019-04-22 20:52:12 +00006540 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
6541 " SELECT i, maxlen, NULL, ("
dan68cb86e2019-04-20 20:57:28 +00006542 " WITH p(orig, pgno, parent) AS ("
6543 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
6544 " UNION ALL"
6545 " SELECT i, p.parent, "
6546 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
6547 " )"
6548 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
6549 ") "
dan9c014f82019-04-25 19:23:15 +00006550 "FROM pages WHERE maxlen > 0 AND i NOT IN freelist;"
danb40af492019-04-22 20:52:12 +00006551 "UPDATE recovery.map AS o SET intkey = ("
6552 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
6553 ");"
dan68cb86e2019-04-20 20:57:28 +00006554
6555 /* Extract data from page 1 and any linked pages into table
6556 ** recovery.schema. With the same schema as an sqlite_master table. */
6557 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
6558 "INSERT INTO recovery.schema SELECT "
6559 " max(CASE WHEN field=0 THEN value ELSE NULL END),"
6560 " max(CASE WHEN field=1 THEN value ELSE NULL END),"
6561 " max(CASE WHEN field=2 THEN value ELSE NULL END),"
6562 " max(CASE WHEN field=3 THEN value ELSE NULL END),"
6563 " max(CASE WHEN field=4 THEN value ELSE NULL END)"
6564 "FROM sqlite_dbdata WHERE pgno IN ("
6565 " SELECT pgno FROM recovery.map WHERE root=1"
6566 ")"
6567 "GROUP BY pgno, cell;"
dan98c5ad32019-04-26 21:11:37 +00006568 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
dan68cb86e2019-04-20 20:57:28 +00006569 );
6570
danb40af492019-04-22 20:52:12 +00006571 /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
6572 ** CREATE TABLE statements that extracted from the existing schema. */
6573 if( rc==SQLITE_OK ){
6574 sqlite3_stmt *pStmt = 0;
6575 raw_printf(pState->out, "BEGIN;\n");
dan38f9c712019-04-23 18:03:02 +00006576 raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
6577 shellPrepare(pState->db, &rc,
danb40af492019-04-22 20:52:12 +00006578 "SELECT sql FROM recovery.schema "
dan38f9c712019-04-23 18:03:02 +00006579 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
danb40af492019-04-22 20:52:12 +00006580 );
6581 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6582 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
dan38f9c712019-04-23 18:03:02 +00006583 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
6584 &zCreateTable[12]
6585 );
danb40af492019-04-22 20:52:12 +00006586 }
6587 shellFinalize(&rc, pStmt);
6588 }
6589
dan98c5ad32019-04-26 21:11:37 +00006590 /* Figure out if an orphan table will be required. And if so, how many
6591 ** user columns it should contain */
6592 shellPrepare(pState->db, &rc,
6593 "SELECT coalesce(max(maxlen), -2) FROM recovery.map"
6594 " WHERE root>1 AND root NOT IN (SELECT rootpage FROM recovery.schema)"
6595 , &pLoop
6596 );
6597 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6598 nOrphan = sqlite3_column_int(pLoop, 0);
6599 }
6600 shellFinalize(&rc, pLoop);
6601 pLoop = 0;
6602 pOrphan = recoverOrphanTable(pState, &rc, nOrphan);
6603
danefa363b2019-04-24 20:48:55 +00006604 shellPrepare(pState->db, &rc,
6605 "SELECT pgno FROM recovery.map WHERE root=?", &pPages
6606 );
6607 shellPrepare(pState->db, &rc,
6608 "SELECT max(field), group_concat(shell_escape_crnl(quote(value)), ', ')"
6609 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
6610 "GROUP BY cell", &pCells
6611 );
6612
dan68cb86e2019-04-20 20:57:28 +00006613 /* Loop through each root page. */
danb40af492019-04-22 20:52:12 +00006614 shellPrepare(pState->db, &rc,
6615 "SELECT root, intkey, max(maxlen) FROM recovery.map"
dan38f9c712019-04-23 18:03:02 +00006616 " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
6617 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
6618 ")", &pLoop
danb40af492019-04-22 20:52:12 +00006619 );
dan68cb86e2019-04-20 20:57:28 +00006620 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6621 int iRoot = sqlite3_column_int(pLoop, 0);
danb40af492019-04-22 20:52:12 +00006622 int bIntkey = sqlite3_column_int(pLoop, 1);
6623 int nCol = sqlite3_column_int(pLoop, 2);
dan98c5ad32019-04-26 21:11:37 +00006624 int bNoop = 0;
dan68cb86e2019-04-20 20:57:28 +00006625 RecoverTable *pTab;
6626
dan98c5ad32019-04-26 21:11:37 +00006627 pTab = recoverNewTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
6628 if( bNoop || rc ) continue;
6629 if( pTab==0 ) pTab = pOrphan;
6630
6631 if( 0==sqlite3_stricmp(pTab->zName, "sqlite_sequence") ){
6632 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
6633 }
6634 sqlite3_bind_int(pPages, 1, iRoot);
6635 sqlite3_bind_int(pCells, 2, pTab->iPk);
6636
6637 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
6638 int iPgno = sqlite3_column_int(pPages, 0);
6639 sqlite3_bind_int(pCells, 1, iPgno);
6640 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
6641 int nField = sqlite3_column_int(pCells, 0);
6642 const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
6643
6644 nField = nField+1;
6645 if( pTab==pOrphan ){
6646 raw_printf(pState->out,
6647 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
6648 pTab->zQuoted, iRoot, iPgno, nField,
6649 bIntkey ? "" : "NULL, ", zVal, pTab->azlCol[nField]
6650 );
6651 }else{
danefa363b2019-04-24 20:48:55 +00006652 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
dan98c5ad32019-04-26 21:11:37 +00006653 pTab->zQuoted, pTab->azlCol[nField], zVal
danefa363b2019-04-24 20:48:55 +00006654 );
6655 }
dan68cb86e2019-04-20 20:57:28 +00006656 }
dan98c5ad32019-04-26 21:11:37 +00006657 shellReset(&rc, pCells);
dan68cb86e2019-04-20 20:57:28 +00006658 }
dan98c5ad32019-04-26 21:11:37 +00006659 shellReset(&rc, pPages);
6660 if( pTab!=pOrphan ) recoverFreeTable(pTab);
dan68cb86e2019-04-20 20:57:28 +00006661 }
6662 shellFinalize(&rc, pLoop);
danefa363b2019-04-24 20:48:55 +00006663 shellFinalize(&rc, pPages);
6664 shellFinalize(&rc, pCells);
dan98c5ad32019-04-26 21:11:37 +00006665 recoverFreeTable(pOrphan);
dan68cb86e2019-04-20 20:57:28 +00006666
dan38f9c712019-04-23 18:03:02 +00006667 /* The rest of the schema */
danb40af492019-04-22 20:52:12 +00006668 if( rc==SQLITE_OK ){
dan38f9c712019-04-23 18:03:02 +00006669 sqlite3_stmt *pStmt = 0;
6670 shellPrepare(pState->db, &rc,
6671 "SELECT sql, name FROM recovery.schema "
danb1825882019-04-23 20:48:32 +00006672 "WHERE sql NOT LIKE 'create table%'", &pStmt
dan38f9c712019-04-23 18:03:02 +00006673 );
6674 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6675 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
6676 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
6677 const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
6678 char *zPrint = shellMPrintf(&rc,
6679 "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)",
6680 zName, zName, zSql
6681 );
6682 raw_printf(pState->out, "%s;\n", zPrint);
6683 sqlite3_free(zPrint);
6684 }else{
6685 raw_printf(pState->out, "%s;\n", zSql);
6686 }
6687 }
6688 shellFinalize(&rc, pStmt);
6689 }
6690
6691 if( rc==SQLITE_OK ){
6692 raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
danb40af492019-04-22 20:52:12 +00006693 raw_printf(pState->out, "COMMIT;\n");
6694 }
dan68cb86e2019-04-20 20:57:28 +00006695 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
6696 return rc;
6697}
6698
drh2ce15c32017-07-11 13:34:40 +00006699
6700/*
6701** If an input line begins with "." then invoke this routine to
6702** process that line.
6703**
6704** Return 1 on error, 2 to exit, and 0 otherwise.
6705*/
6706static int do_meta_command(char *zLine, ShellState *p){
6707 int h = 1;
6708 int nArg = 0;
6709 int n, c;
6710 int rc = 0;
6711 char *azArg[50];
6712
dan6b046be2018-01-09 15:25:55 +00006713#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006714 if( p->expert.pExpert ){
6715 expertFinish(p, 1, 0);
6716 }
dan6b046be2018-01-09 15:25:55 +00006717#endif
dan43efc182017-12-19 17:42:13 +00006718
drh2ce15c32017-07-11 13:34:40 +00006719 /* Parse the input line into tokens.
6720 */
6721 while( zLine[h] && nArg<ArraySize(azArg) ){
6722 while( IsSpace(zLine[h]) ){ h++; }
6723 if( zLine[h]==0 ) break;
6724 if( zLine[h]=='\'' || zLine[h]=='"' ){
6725 int delim = zLine[h++];
6726 azArg[nArg++] = &zLine[h];
6727 while( zLine[h] && zLine[h]!=delim ){
6728 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
6729 h++;
6730 }
6731 if( zLine[h]==delim ){
6732 zLine[h++] = 0;
6733 }
6734 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
6735 }else{
6736 azArg[nArg++] = &zLine[h];
6737 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
6738 if( zLine[h] ) zLine[h++] = 0;
6739 resolve_backslashes(azArg[nArg-1]);
6740 }
6741 }
6742
6743 /* Process the input line.
6744 */
6745 if( nArg==0 ) return 0; /* no tokens, no error */
6746 n = strlen30(azArg[0]);
6747 c = azArg[0][0];
drh13c20932018-01-10 21:41:55 +00006748 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00006749
6750#ifndef SQLITE_OMIT_AUTHORIZATION
6751 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
6752 if( nArg!=2 ){
6753 raw_printf(stderr, "Usage: .auth ON|OFF\n");
6754 rc = 1;
6755 goto meta_command_exit;
6756 }
6757 open_db(p, 0);
6758 if( booleanValue(azArg[1]) ){
6759 sqlite3_set_authorizer(p->db, shellAuth, p);
6760 }else{
6761 sqlite3_set_authorizer(p->db, 0, 0);
6762 }
6763 }else
6764#endif
6765
drhe37c0e12018-01-06 19:19:50 +00006766#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6767 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00006768 open_db(p, 0);
drhd0f9cdc2018-05-17 14:09:06 +00006769 rc = arDotCommand(p, 0, azArg, nArg);
danfd0245d2017-12-07 15:44:29 +00006770 }else
6771#endif
6772
drh2ce15c32017-07-11 13:34:40 +00006773 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
6774 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
6775 ){
6776 const char *zDestFile = 0;
6777 const char *zDb = 0;
6778 sqlite3 *pDest;
6779 sqlite3_backup *pBackup;
6780 int j;
drha50bffb2018-12-08 01:09:14 +00006781 int bAsync = 0;
drh69ed38a2018-05-14 00:23:08 +00006782 const char *zVfs = 0;
drh2ce15c32017-07-11 13:34:40 +00006783 for(j=1; j<nArg; j++){
6784 const char *z = azArg[j];
6785 if( z[0]=='-' ){
drh69ed38a2018-05-14 00:23:08 +00006786 if( z[1]=='-' ) z++;
6787 if( strcmp(z, "-append")==0 ){
6788 zVfs = "apndvfs";
6789 }else
drha50bffb2018-12-08 01:09:14 +00006790 if( strcmp(z, "-async")==0 ){
6791 bAsync = 1;
6792 }else
drh2ce15c32017-07-11 13:34:40 +00006793 {
6794 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
6795 return 1;
6796 }
6797 }else if( zDestFile==0 ){
6798 zDestFile = azArg[j];
6799 }else if( zDb==0 ){
6800 zDb = zDestFile;
6801 zDestFile = azArg[j];
6802 }else{
drha50bffb2018-12-08 01:09:14 +00006803 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
drh2ce15c32017-07-11 13:34:40 +00006804 return 1;
6805 }
6806 }
6807 if( zDestFile==0 ){
6808 raw_printf(stderr, "missing FILENAME argument on .backup\n");
6809 return 1;
6810 }
6811 if( zDb==0 ) zDb = "main";
drh69ed38a2018-05-14 00:23:08 +00006812 rc = sqlite3_open_v2(zDestFile, &pDest,
6813 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
drh2ce15c32017-07-11 13:34:40 +00006814 if( rc!=SQLITE_OK ){
6815 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9e804032018-05-18 17:11:50 +00006816 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006817 return 1;
6818 }
drha50bffb2018-12-08 01:09:14 +00006819 if( bAsync ){
6820 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
6821 0, 0, 0);
6822 }
drh2ce15c32017-07-11 13:34:40 +00006823 open_db(p, 0);
6824 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
6825 if( pBackup==0 ){
6826 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9e804032018-05-18 17:11:50 +00006827 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006828 return 1;
6829 }
6830 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
6831 sqlite3_backup_finish(pBackup);
6832 if( rc==SQLITE_DONE ){
6833 rc = 0;
6834 }else{
6835 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
6836 rc = 1;
6837 }
drh9e804032018-05-18 17:11:50 +00006838 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006839 }else
6840
6841 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
6842 if( nArg==2 ){
6843 bail_on_error = booleanValue(azArg[1]);
6844 }else{
6845 raw_printf(stderr, "Usage: .bail on|off\n");
6846 rc = 1;
6847 }
6848 }else
6849
6850 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
6851 if( nArg==2 ){
6852 if( booleanValue(azArg[1]) ){
6853 setBinaryMode(p->out, 1);
6854 }else{
6855 setTextMode(p->out, 1);
6856 }
6857 }else{
6858 raw_printf(stderr, "Usage: .binary on|off\n");
6859 rc = 1;
6860 }
6861 }else
6862
6863 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
6864 if( nArg==2 ){
6865#if defined(_WIN32) || defined(WIN32)
6866 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
6867 rc = !SetCurrentDirectoryW(z);
6868 sqlite3_free(z);
6869#else
6870 rc = chdir(azArg[1]);
6871#endif
6872 if( rc ){
6873 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
6874 rc = 1;
6875 }
6876 }else{
6877 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
6878 rc = 1;
6879 }
6880 }else
6881
6882 /* The undocumented ".breakpoint" command causes a call to the no-op
6883 ** routine named test_breakpoint().
6884 */
6885 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
6886 test_breakpoint();
6887 }else
6888
6889 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
6890 if( nArg==2 ){
6891 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
6892 }else{
6893 raw_printf(stderr, "Usage: .changes on|off\n");
6894 rc = 1;
6895 }
6896 }else
6897
6898 /* Cancel output redirection, if it is currently set (by .testcase)
6899 ** Then read the content of the testcase-out.txt file and compare against
6900 ** azArg[1]. If there are differences, report an error and exit.
6901 */
6902 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
6903 char *zRes = 0;
6904 output_reset(p);
6905 if( nArg!=2 ){
6906 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
6907 rc = 2;
6908 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
6909 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
6910 rc = 2;
6911 }else if( testcase_glob(azArg[1],zRes)==0 ){
6912 utf8_printf(stderr,
6913 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
6914 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00006915 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00006916 }else{
6917 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
6918 p->nCheck++;
6919 }
6920 sqlite3_free(zRes);
6921 }else
6922
6923 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
6924 if( nArg==2 ){
6925 tryToClone(p, azArg[1]);
6926 }else{
6927 raw_printf(stderr, "Usage: .clone FILENAME\n");
6928 rc = 1;
6929 }
6930 }else
6931
6932 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
6933 ShellState data;
6934 char *zErrMsg = 0;
6935 open_db(p, 0);
6936 memcpy(&data, p, sizeof(data));
6937 data.showHeader = 0;
6938 data.cMode = data.mode = MODE_List;
6939 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
6940 data.cnt = 0;
6941 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
6942 callback, &data, &zErrMsg);
6943 if( zErrMsg ){
6944 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6945 sqlite3_free(zErrMsg);
6946 rc = 1;
6947 }
6948 }else
6949
drh7df01192018-04-28 12:43:16 +00006950 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
drheb7f2a02018-09-26 18:02:32 +00006951 static const struct DbConfigChoices {
6952 const char *zName;
6953 int op;
6954 } aDbConfig[] = {
drh7df01192018-04-28 12:43:16 +00006955 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
6956 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
6957 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
6958 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
6959 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
6960 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
6961 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
6962 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
drha296cda2018-11-03 16:09:59 +00006963 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
drh7df01192018-04-28 12:43:16 +00006964 };
6965 int ii, v;
6966 open_db(p, 0);
6967 for(ii=0; ii<ArraySize(aDbConfig); ii++){
6968 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
6969 if( nArg>=3 ){
6970 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
6971 }
6972 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
6973 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
6974 if( nArg>1 ) break;
6975 }
6976 if( nArg>1 && ii==ArraySize(aDbConfig) ){
6977 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
6978 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
6979 }
6980 }else
6981
6982 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00006983 rc = shell_dbinfo_command(p, nArg, azArg);
6984 }else
6985
dan68cb86e2019-04-20 20:57:28 +00006986 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
6987 open_db(p, 0);
danb9b71db2019-04-25 16:20:40 +00006988 rc = recoverDatabaseCmd(p, nArg, azArg);
dan68cb86e2019-04-20 20:57:28 +00006989 }else
6990
drh2ce15c32017-07-11 13:34:40 +00006991 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
6992 const char *zLike = 0;
6993 int i;
6994 int savedShowHeader = p->showHeader;
drhf213b332018-07-05 17:35:46 +00006995 int savedShellFlags = p->shellFlgs;
6996 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
drh2ce15c32017-07-11 13:34:40 +00006997 for(i=1; i<nArg; i++){
6998 if( azArg[i][0]=='-' ){
6999 const char *z = azArg[i]+1;
7000 if( z[0]=='-' ) z++;
7001 if( strcmp(z,"preserve-rowids")==0 ){
7002#ifdef SQLITE_OMIT_VIRTUALTABLE
7003 raw_printf(stderr, "The --preserve-rowids option is not compatible"
7004 " with SQLITE_OMIT_VIRTUALTABLE\n");
7005 rc = 1;
7006 goto meta_command_exit;
7007#else
7008 ShellSetFlag(p, SHFLG_PreserveRowid);
7009#endif
7010 }else
7011 if( strcmp(z,"newlines")==0 ){
7012 ShellSetFlag(p, SHFLG_Newlines);
7013 }else
7014 {
7015 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7016 rc = 1;
7017 goto meta_command_exit;
7018 }
7019 }else if( zLike ){
7020 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
7021 "?--newlines? ?LIKE-PATTERN?\n");
7022 rc = 1;
7023 goto meta_command_exit;
7024 }else{
7025 zLike = azArg[i];
7026 }
7027 }
dan68cb86e2019-04-20 20:57:28 +00007028
drh2ce15c32017-07-11 13:34:40 +00007029 open_db(p, 0);
dan68cb86e2019-04-20 20:57:28 +00007030
drh2ce15c32017-07-11 13:34:40 +00007031 /* When playing back a "dump", the content might appear in an order
7032 ** which causes immediate foreign key constraints to be violated.
7033 ** So disable foreign-key constraint enforcement to prevent problems. */
7034 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
7035 raw_printf(p->out, "BEGIN TRANSACTION;\n");
7036 p->writableSchema = 0;
7037 p->showHeader = 0;
7038 /* Set writable_schema=ON since doing so forces SQLite to initialize
7039 ** as much of the schema as it can even if the sqlite_master table is
7040 ** corrupt. */
7041 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
7042 p->nErr = 0;
7043 if( zLike==0 ){
7044 run_schema_dump_query(p,
dan68cb86e2019-04-20 20:57:28 +00007045 "SELECT name, type, sql FROM sqlite_master "
7046 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
7047 );
drh2ce15c32017-07-11 13:34:40 +00007048 run_schema_dump_query(p,
dan68cb86e2019-04-20 20:57:28 +00007049 "SELECT name, type, sql FROM sqlite_master "
7050 "WHERE name=='sqlite_sequence'"
7051 );
drh2ce15c32017-07-11 13:34:40 +00007052 run_table_dump_query(p,
dan68cb86e2019-04-20 20:57:28 +00007053 "SELECT sql FROM sqlite_master "
7054 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
7055 );
drh2ce15c32017-07-11 13:34:40 +00007056 }else{
7057 char *zSql;
7058 zSql = sqlite3_mprintf(
dan68cb86e2019-04-20 20:57:28 +00007059 "SELECT name, type, sql FROM sqlite_master "
7060 "WHERE tbl_name LIKE %Q AND type=='table'"
7061 " AND sql NOT NULL", zLike);
drh2ce15c32017-07-11 13:34:40 +00007062 run_schema_dump_query(p,zSql);
7063 sqlite3_free(zSql);
7064 zSql = sqlite3_mprintf(
dan68cb86e2019-04-20 20:57:28 +00007065 "SELECT sql FROM sqlite_master "
7066 "WHERE sql NOT NULL"
7067 " AND type IN ('index','trigger','view')"
7068 " AND tbl_name LIKE %Q", zLike);
drh2ce15c32017-07-11 13:34:40 +00007069 run_table_dump_query(p, zSql, 0);
7070 sqlite3_free(zSql);
7071 }
7072 if( p->writableSchema ){
7073 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
7074 p->writableSchema = 0;
7075 }
7076 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
7077 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
dan68cb86e2019-04-20 20:57:28 +00007078 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
drh2ce15c32017-07-11 13:34:40 +00007079 p->showHeader = savedShowHeader;
drhf213b332018-07-05 17:35:46 +00007080 p->shellFlgs = savedShellFlags;
drh2ce15c32017-07-11 13:34:40 +00007081 }else
7082
7083 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
7084 if( nArg==2 ){
7085 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
7086 }else{
7087 raw_printf(stderr, "Usage: .echo on|off\n");
7088 rc = 1;
7089 }
7090 }else
7091
7092 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
7093 if( nArg==2 ){
drhe2ca99c2018-05-02 00:33:43 +00007094 p->autoEQPtest = 0;
drhb4e50392019-01-26 15:40:04 +00007095 if( p->autoEQPtrace ){
7096 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
7097 p->autoEQPtrace = 0;
7098 }
drh2ce15c32017-07-11 13:34:40 +00007099 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00007100 p->autoEQP = AUTOEQP_full;
7101 }else if( strcmp(azArg[1],"trigger")==0 ){
7102 p->autoEQP = AUTOEQP_trigger;
drhb4e50392019-01-26 15:40:04 +00007103#ifdef SQLITE_DEBUG
drhe2ca99c2018-05-02 00:33:43 +00007104 }else if( strcmp(azArg[1],"test")==0 ){
7105 p->autoEQP = AUTOEQP_on;
7106 p->autoEQPtest = 1;
drhb4e50392019-01-26 15:40:04 +00007107 }else if( strcmp(azArg[1],"trace")==0 ){
7108 p->autoEQP = AUTOEQP_full;
7109 p->autoEQPtrace = 1;
7110 open_db(p, 0);
drhc07eee72019-01-27 19:50:56 +00007111 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
drhb4e50392019-01-26 15:40:04 +00007112 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
7113#endif
drh2ce15c32017-07-11 13:34:40 +00007114 }else{
mistachkinb71aa092018-01-23 00:05:18 +00007115 p->autoEQP = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007116 }
7117 }else{
drhb4e50392019-01-26 15:40:04 +00007118 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00007119 rc = 1;
7120 }
7121 }else
7122
7123 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
7124 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
7125 rc = 2;
7126 }else
7127
7128 /* The ".explain" command is automatic now. It is largely pointless. It
7129 ** retained purely for backwards compatibility */
7130 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
7131 int val = 1;
7132 if( nArg>=2 ){
7133 if( strcmp(azArg[1],"auto")==0 ){
7134 val = 99;
7135 }else{
7136 val = booleanValue(azArg[1]);
7137 }
7138 }
7139 if( val==1 && p->mode!=MODE_Explain ){
7140 p->normalMode = p->mode;
7141 p->mode = MODE_Explain;
7142 p->autoExplain = 0;
7143 }else if( val==0 ){
7144 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7145 p->autoExplain = 0;
7146 }else if( val==99 ){
7147 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7148 p->autoExplain = 1;
7149 }
7150 }else
7151
dan6b046be2018-01-09 15:25:55 +00007152#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00007153 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
7154 open_db(p, 0);
7155 expertDotCommand(p, azArg, nArg);
7156 }else
dan6b046be2018-01-09 15:25:55 +00007157#endif
dan43efc182017-12-19 17:42:13 +00007158
drh2ce15c32017-07-11 13:34:40 +00007159 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
7160 ShellState data;
7161 char *zErrMsg = 0;
7162 int doStats = 0;
7163 memcpy(&data, p, sizeof(data));
7164 data.showHeader = 0;
7165 data.cMode = data.mode = MODE_Semi;
7166 if( nArg==2 && optionMatch(azArg[1], "indent") ){
7167 data.cMode = data.mode = MODE_Pretty;
7168 nArg = 1;
7169 }
7170 if( nArg!=1 ){
7171 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
7172 rc = 1;
7173 goto meta_command_exit;
7174 }
7175 open_db(p, 0);
7176 rc = sqlite3_exec(p->db,
7177 "SELECT sql FROM"
7178 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
7179 " FROM sqlite_master UNION ALL"
7180 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
7181 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
7182 "ORDER BY rowid",
7183 callback, &data, &zErrMsg
7184 );
7185 if( rc==SQLITE_OK ){
7186 sqlite3_stmt *pStmt;
7187 rc = sqlite3_prepare_v2(p->db,
7188 "SELECT rowid FROM sqlite_master"
7189 " WHERE name GLOB 'sqlite_stat[134]'",
7190 -1, &pStmt, 0);
7191 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
7192 sqlite3_finalize(pStmt);
7193 }
7194 if( doStats==0 ){
7195 raw_printf(p->out, "/* No STAT tables available */\n");
7196 }else{
7197 raw_printf(p->out, "ANALYZE sqlite_master;\n");
7198 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
7199 callback, &data, &zErrMsg);
7200 data.cMode = data.mode = MODE_Insert;
7201 data.zDestTable = "sqlite_stat1";
drh4c540452018-05-08 23:17:36 +00007202 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007203 data.zDestTable = "sqlite_stat3";
drh4c540452018-05-08 23:17:36 +00007204 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007205 data.zDestTable = "sqlite_stat4";
drh4c540452018-05-08 23:17:36 +00007206 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007207 raw_printf(p->out, "ANALYZE sqlite_master;\n");
7208 }
7209 }else
7210
7211 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
7212 if( nArg==2 ){
7213 p->showHeader = booleanValue(azArg[1]);
7214 }else{
7215 raw_printf(stderr, "Usage: .headers on|off\n");
7216 rc = 1;
7217 }
7218 }else
7219
7220 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
drh98aa2ab2018-09-26 16:53:51 +00007221 if( nArg>=2 ){
drhe93f8262018-10-11 16:53:37 +00007222 n = showHelp(p->out, azArg[1]);
drh98aa2ab2018-09-26 16:53:51 +00007223 if( n==0 ){
7224 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
7225 }
7226 }else{
7227 showHelp(p->out, 0);
7228 }
drh2ce15c32017-07-11 13:34:40 +00007229 }else
7230
7231 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
7232 char *zTable; /* Insert data into this table */
7233 char *zFile; /* Name of file to extra content from */
7234 sqlite3_stmt *pStmt = NULL; /* A statement */
7235 int nCol; /* Number of columns in the table */
7236 int nByte; /* Number of bytes in an SQL string */
7237 int i, j; /* Loop counters */
7238 int needCommit; /* True to COMMIT or ROLLBACK at end */
7239 int nSep; /* Number of bytes in p->colSeparator[] */
7240 char *zSql; /* An SQL statement */
7241 ImportCtx sCtx; /* Reader context */
7242 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
7243 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
7244
7245 if( nArg!=3 ){
7246 raw_printf(stderr, "Usage: .import FILE TABLE\n");
7247 goto meta_command_exit;
7248 }
7249 zFile = azArg[1];
7250 zTable = azArg[2];
7251 seenInterrupt = 0;
7252 memset(&sCtx, 0, sizeof(sCtx));
7253 open_db(p, 0);
7254 nSep = strlen30(p->colSeparator);
7255 if( nSep==0 ){
7256 raw_printf(stderr,
7257 "Error: non-null column separator required for import\n");
7258 return 1;
7259 }
7260 if( nSep>1 ){
7261 raw_printf(stderr, "Error: multi-character column separators not allowed"
7262 " for import\n");
7263 return 1;
7264 }
7265 nSep = strlen30(p->rowSeparator);
7266 if( nSep==0 ){
7267 raw_printf(stderr, "Error: non-null row separator required for import\n");
7268 return 1;
7269 }
7270 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
7271 /* When importing CSV (only), if the row separator is set to the
7272 ** default output row separator, change it to the default input
7273 ** row separator. This avoids having to maintain different input
7274 ** and output row separators. */
7275 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7276 nSep = strlen30(p->rowSeparator);
7277 }
7278 if( nSep>1 ){
7279 raw_printf(stderr, "Error: multi-character row separators not allowed"
7280 " for import\n");
7281 return 1;
7282 }
7283 sCtx.zFile = zFile;
7284 sCtx.nLine = 1;
7285 if( sCtx.zFile[0]=='|' ){
7286#ifdef SQLITE_OMIT_POPEN
7287 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7288 return 1;
7289#else
7290 sCtx.in = popen(sCtx.zFile+1, "r");
7291 sCtx.zFile = "<pipe>";
7292 xCloser = pclose;
7293#endif
7294 }else{
7295 sCtx.in = fopen(sCtx.zFile, "rb");
7296 xCloser = fclose;
7297 }
7298 if( p->mode==MODE_Ascii ){
7299 xRead = ascii_read_one_field;
7300 }else{
7301 xRead = csv_read_one_field;
7302 }
7303 if( sCtx.in==0 ){
7304 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
7305 return 1;
7306 }
7307 sCtx.cColSep = p->colSeparator[0];
7308 sCtx.cRowSep = p->rowSeparator[0];
7309 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
7310 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00007311 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00007312 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007313 }
7314 nByte = strlen30(zSql);
7315 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7316 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
7317 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
7318 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
7319 char cSep = '(';
7320 while( xRead(&sCtx) ){
7321 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
7322 cSep = ',';
7323 if( sCtx.cTerm!=sCtx.cColSep ) break;
7324 }
7325 if( cSep=='(' ){
7326 sqlite3_free(zCreate);
7327 sqlite3_free(sCtx.z);
7328 xCloser(sCtx.in);
7329 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
7330 return 1;
7331 }
7332 zCreate = sqlite3_mprintf("%z\n)", zCreate);
7333 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
7334 sqlite3_free(zCreate);
7335 if( rc ){
7336 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
7337 sqlite3_errmsg(p->db));
7338 sqlite3_free(sCtx.z);
7339 xCloser(sCtx.in);
7340 return 1;
7341 }
7342 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7343 }
7344 sqlite3_free(zSql);
7345 if( rc ){
7346 if (pStmt) sqlite3_finalize(pStmt);
7347 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
7348 xCloser(sCtx.in);
7349 return 1;
7350 }
7351 nCol = sqlite3_column_count(pStmt);
7352 sqlite3_finalize(pStmt);
7353 pStmt = 0;
7354 if( nCol==0 ) return 0; /* no columns, no error */
7355 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
7356 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00007357 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00007358 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007359 }
7360 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
7361 j = strlen30(zSql);
7362 for(i=1; i<nCol; i++){
7363 zSql[j++] = ',';
7364 zSql[j++] = '?';
7365 }
7366 zSql[j++] = ')';
7367 zSql[j] = 0;
7368 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7369 sqlite3_free(zSql);
7370 if( rc ){
7371 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7372 if (pStmt) sqlite3_finalize(pStmt);
7373 xCloser(sCtx.in);
7374 return 1;
7375 }
7376 needCommit = sqlite3_get_autocommit(p->db);
7377 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
7378 do{
7379 int startLine = sCtx.nLine;
7380 for(i=0; i<nCol; i++){
7381 char *z = xRead(&sCtx);
7382 /*
7383 ** Did we reach end-of-file before finding any columns?
7384 ** If so, stop instead of NULL filling the remaining columns.
7385 */
7386 if( z==0 && i==0 ) break;
7387 /*
7388 ** Did we reach end-of-file OR end-of-line before finding any
7389 ** columns in ASCII mode? If so, stop instead of NULL filling
7390 ** the remaining columns.
7391 */
7392 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
7393 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
7394 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
7395 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7396 "filling the rest with NULL\n",
7397 sCtx.zFile, startLine, nCol, i+1);
7398 i += 2;
7399 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
7400 }
7401 }
7402 if( sCtx.cTerm==sCtx.cColSep ){
7403 do{
7404 xRead(&sCtx);
7405 i++;
7406 }while( sCtx.cTerm==sCtx.cColSep );
7407 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7408 "extras ignored\n",
7409 sCtx.zFile, startLine, nCol, i);
7410 }
7411 if( i>=nCol ){
7412 sqlite3_step(pStmt);
7413 rc = sqlite3_reset(pStmt);
7414 if( rc!=SQLITE_OK ){
7415 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
7416 startLine, sqlite3_errmsg(p->db));
7417 }
7418 }
7419 }while( sCtx.cTerm!=EOF );
7420
7421 xCloser(sCtx.in);
7422 sqlite3_free(sCtx.z);
7423 sqlite3_finalize(pStmt);
7424 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
7425 }else
7426
7427#ifndef SQLITE_UNTESTABLE
7428 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
7429 char *zSql;
7430 char *zCollist = 0;
7431 sqlite3_stmt *pStmt;
7432 int tnum = 0;
7433 int i;
drh48d219a2018-04-23 18:38:48 +00007434 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
7435 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
7436 " .imposter off\n");
drh2ce15c32017-07-11 13:34:40 +00007437 rc = 1;
7438 goto meta_command_exit;
7439 }
7440 open_db(p, 0);
drh48d219a2018-04-23 18:38:48 +00007441 if( nArg==2 ){
7442 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
7443 goto meta_command_exit;
7444 }
drh2ce15c32017-07-11 13:34:40 +00007445 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
7446 " WHERE name='%q' AND type='index'", azArg[1]);
7447 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7448 sqlite3_free(zSql);
7449 if( sqlite3_step(pStmt)==SQLITE_ROW ){
7450 tnum = sqlite3_column_int(pStmt, 0);
7451 }
7452 sqlite3_finalize(pStmt);
7453 if( tnum==0 ){
7454 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
7455 rc = 1;
7456 goto meta_command_exit;
7457 }
7458 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
7459 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7460 sqlite3_free(zSql);
7461 i = 0;
7462 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7463 char zLabel[20];
7464 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
7465 i++;
7466 if( zCol==0 ){
7467 if( sqlite3_column_int(pStmt,1)==-1 ){
7468 zCol = "_ROWID_";
7469 }else{
7470 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
7471 zCol = zLabel;
7472 }
7473 }
7474 if( zCollist==0 ){
7475 zCollist = sqlite3_mprintf("\"%w\"", zCol);
7476 }else{
7477 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
7478 }
7479 }
7480 sqlite3_finalize(pStmt);
7481 zSql = sqlite3_mprintf(
7482 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
7483 azArg[2], zCollist, zCollist);
7484 sqlite3_free(zCollist);
7485 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
7486 if( rc==SQLITE_OK ){
7487 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
7488 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
7489 if( rc ){
7490 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
7491 }else{
7492 utf8_printf(stdout, "%s;\n", zSql);
7493 raw_printf(stdout,
7494 "WARNING: writing to an imposter table will corrupt the index!\n"
7495 );
7496 }
7497 }else{
7498 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
7499 rc = 1;
7500 }
7501 sqlite3_free(zSql);
7502 }else
7503#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
7504
7505#ifdef SQLITE_ENABLE_IOTRACE
7506 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
7507 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
7508 if( iotrace && iotrace!=stdout ) fclose(iotrace);
7509 iotrace = 0;
7510 if( nArg<2 ){
7511 sqlite3IoTrace = 0;
7512 }else if( strcmp(azArg[1], "-")==0 ){
7513 sqlite3IoTrace = iotracePrintf;
7514 iotrace = stdout;
7515 }else{
7516 iotrace = fopen(azArg[1], "w");
7517 if( iotrace==0 ){
7518 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
7519 sqlite3IoTrace = 0;
7520 rc = 1;
7521 }else{
7522 sqlite3IoTrace = iotracePrintf;
7523 }
7524 }
7525 }else
7526#endif
7527
7528 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
7529 static const struct {
7530 const char *zLimitName; /* Name of a limit */
7531 int limitCode; /* Integer code for that limit */
7532 } aLimit[] = {
7533 { "length", SQLITE_LIMIT_LENGTH },
7534 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
7535 { "column", SQLITE_LIMIT_COLUMN },
7536 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
7537 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
7538 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
7539 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
7540 { "attached", SQLITE_LIMIT_ATTACHED },
7541 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
7542 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
7543 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
7544 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
7545 };
7546 int i, n2;
7547 open_db(p, 0);
7548 if( nArg==1 ){
7549 for(i=0; i<ArraySize(aLimit); i++){
7550 printf("%20s %d\n", aLimit[i].zLimitName,
7551 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
7552 }
7553 }else if( nArg>3 ){
7554 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
7555 rc = 1;
7556 goto meta_command_exit;
7557 }else{
7558 int iLimit = -1;
7559 n2 = strlen30(azArg[1]);
7560 for(i=0; i<ArraySize(aLimit); i++){
7561 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
7562 if( iLimit<0 ){
7563 iLimit = i;
7564 }else{
7565 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
7566 rc = 1;
7567 goto meta_command_exit;
7568 }
7569 }
7570 }
7571 if( iLimit<0 ){
7572 utf8_printf(stderr, "unknown limit: \"%s\"\n"
7573 "enter \".limits\" with no arguments for a list.\n",
7574 azArg[1]);
7575 rc = 1;
7576 goto meta_command_exit;
7577 }
7578 if( nArg==3 ){
7579 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
7580 (int)integerValue(azArg[2]));
7581 }
7582 printf("%20s %d\n", aLimit[iLimit].zLimitName,
7583 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
7584 }
7585 }else
7586
7587 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
7588 open_db(p, 0);
7589 lintDotCommand(p, azArg, nArg);
7590 }else
7591
7592#ifndef SQLITE_OMIT_LOAD_EXTENSION
7593 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
7594 const char *zFile, *zProc;
7595 char *zErrMsg = 0;
7596 if( nArg<2 ){
7597 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
7598 rc = 1;
7599 goto meta_command_exit;
7600 }
7601 zFile = azArg[1];
7602 zProc = nArg>=3 ? azArg[2] : 0;
7603 open_db(p, 0);
7604 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
7605 if( rc!=SQLITE_OK ){
7606 utf8_printf(stderr, "Error: %s\n", zErrMsg);
7607 sqlite3_free(zErrMsg);
7608 rc = 1;
7609 }
7610 }else
7611#endif
7612
7613 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
7614 if( nArg!=2 ){
7615 raw_printf(stderr, "Usage: .log FILENAME\n");
7616 rc = 1;
7617 }else{
7618 const char *zFile = azArg[1];
7619 output_file_close(p->pLog);
drha92a01a2018-01-10 22:15:37 +00007620 p->pLog = output_file_open(zFile, 0);
drh2ce15c32017-07-11 13:34:40 +00007621 }
7622 }else
7623
7624 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
7625 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00007626 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00007627 int c2 = zMode[0];
7628 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
7629 p->mode = MODE_Line;
7630 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7631 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
7632 p->mode = MODE_Column;
7633 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7634 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
7635 p->mode = MODE_List;
7636 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
7637 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7638 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
7639 p->mode = MODE_Html;
7640 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
7641 p->mode = MODE_Tcl;
7642 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
7643 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7644 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
7645 p->mode = MODE_Csv;
7646 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
7647 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
7648 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
7649 p->mode = MODE_List;
7650 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
7651 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
7652 p->mode = MODE_Insert;
7653 set_table_name(p, nArg>=3 ? azArg[2] : "table");
7654 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
7655 p->mode = MODE_Quote;
7656 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
7657 p->mode = MODE_Ascii;
7658 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
7659 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
7660 }else if( nArg==1 ){
7661 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
7662 }else{
7663 raw_printf(stderr, "Error: mode should be one of: "
7664 "ascii column csv html insert line list quote tabs tcl\n");
7665 rc = 1;
7666 }
7667 p->cMode = p->mode;
7668 }else
7669
7670 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
7671 if( nArg==2 ){
7672 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
7673 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
7674 }else{
7675 raw_printf(stderr, "Usage: .nullvalue STRING\n");
7676 rc = 1;
7677 }
7678 }else
7679
7680 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
7681 char *zNewFilename; /* Name of the database file to open */
7682 int iName = 1; /* Index in azArg[] of the filename */
7683 int newFlag = 0; /* True to delete file before opening */
7684 /* Close the existing database */
7685 session_close_all(p);
drh9e804032018-05-18 17:11:50 +00007686 close_db(p->db);
drh2ce15c32017-07-11 13:34:40 +00007687 p->db = 0;
7688 p->zDbFilename = 0;
7689 sqlite3_free(p->zFreeOnClose);
7690 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00007691 p->openMode = SHELL_OPEN_UNSPEC;
drh6ca64482019-01-22 16:06:20 +00007692 p->szMax = 0;
drh2ce15c32017-07-11 13:34:40 +00007693 /* Check for command-line arguments */
7694 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
7695 const char *z = azArg[iName];
7696 if( optionMatch(z,"new") ){
7697 newFlag = 1;
drh3baed312018-03-08 18:14:41 +00007698#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00007699 }else if( optionMatch(z, "zip") ){
7700 p->openMode = SHELL_OPEN_ZIPFILE;
7701#endif
7702 }else if( optionMatch(z, "append") ){
7703 p->openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00007704 }else if( optionMatch(z, "readonly") ){
7705 p->openMode = SHELL_OPEN_READONLY;
drha751f392018-10-30 15:31:22 +00007706#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00007707 }else if( optionMatch(z, "deserialize") ){
7708 p->openMode = SHELL_OPEN_DESERIALIZE;
drh33746482018-12-13 15:06:26 +00007709 }else if( optionMatch(z, "hexdb") ){
7710 p->openMode = SHELL_OPEN_HEXDB;
drh6ca64482019-01-22 16:06:20 +00007711 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
7712 p->szMax = integerValue(azArg[++iName]);
drh33746482018-12-13 15:06:26 +00007713#endif /* SQLITE_ENABLE_DESERIALIZE */
drh2ce15c32017-07-11 13:34:40 +00007714 }else if( z[0]=='-' ){
7715 utf8_printf(stderr, "unknown option: %s\n", z);
7716 rc = 1;
7717 goto meta_command_exit;
7718 }
7719 }
7720 /* If a filename is specified, try to open it first */
7721 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
drh33746482018-12-13 15:06:26 +00007722 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
drh2ce15c32017-07-11 13:34:40 +00007723 if( newFlag ) shellDeleteFile(zNewFilename);
7724 p->zDbFilename = zNewFilename;
drhbe4ccb22018-05-17 20:04:24 +00007725 open_db(p, OPEN_DB_KEEPALIVE);
drh2ce15c32017-07-11 13:34:40 +00007726 if( p->db==0 ){
7727 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
7728 sqlite3_free(zNewFilename);
7729 }else{
7730 p->zFreeOnClose = zNewFilename;
7731 }
7732 }
7733 if( p->db==0 ){
7734 /* As a fall-back open a TEMP database */
7735 p->zDbFilename = 0;
7736 open_db(p, 0);
7737 }
7738 }else
7739
drh13c20932018-01-10 21:41:55 +00007740 if( (c=='o'
7741 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
7742 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
drh2ce15c32017-07-11 13:34:40 +00007743 ){
7744 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
drha92a01a2018-01-10 22:15:37 +00007745 int bTxtMode = 0;
drh13c20932018-01-10 21:41:55 +00007746 if( azArg[0][0]=='e' ){
7747 /* Transform the ".excel" command into ".once -x" */
7748 nArg = 2;
7749 azArg[0] = "once";
7750 zFile = azArg[1] = "-x";
7751 n = 4;
7752 }
drh2ce15c32017-07-11 13:34:40 +00007753 if( nArg>2 ){
drh13c20932018-01-10 21:41:55 +00007754 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00007755 rc = 1;
7756 goto meta_command_exit;
7757 }
7758 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
7759 if( nArg<2 ){
drh13c20932018-01-10 21:41:55 +00007760 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
drh2ce15c32017-07-11 13:34:40 +00007761 rc = 1;
7762 goto meta_command_exit;
7763 }
7764 p->outCount = 2;
7765 }else{
7766 p->outCount = 0;
7767 }
7768 output_reset(p);
drh13c20932018-01-10 21:41:55 +00007769 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
drh04a28c32018-01-31 01:38:44 +00007770#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00007771 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
drh3c484e82018-01-10 22:27:21 +00007772 p->doXdgOpen = 1;
7773 outputModePush(p);
drh13c20932018-01-10 21:41:55 +00007774 if( zFile[1]=='x' ){
7775 newTempFile(p, "csv");
7776 p->mode = MODE_Csv;
7777 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
7778 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
7779 }else{
7780 newTempFile(p, "txt");
drha92a01a2018-01-10 22:15:37 +00007781 bTxtMode = 1;
drh13c20932018-01-10 21:41:55 +00007782 }
7783 zFile = p->zTempFile;
7784 }
drh04a28c32018-01-31 01:38:44 +00007785#endif /* SQLITE_NOHAVE_SYSTEM */
drh2ce15c32017-07-11 13:34:40 +00007786 if( zFile[0]=='|' ){
7787#ifdef SQLITE_OMIT_POPEN
7788 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7789 rc = 1;
7790 p->out = stdout;
7791#else
7792 p->out = popen(zFile + 1, "w");
7793 if( p->out==0 ){
7794 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
7795 p->out = stdout;
7796 rc = 1;
7797 }else{
7798 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7799 }
7800#endif
7801 }else{
drha92a01a2018-01-10 22:15:37 +00007802 p->out = output_file_open(zFile, bTxtMode);
drh2ce15c32017-07-11 13:34:40 +00007803 if( p->out==0 ){
7804 if( strcmp(zFile,"off")!=0 ){
7805 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
7806 }
7807 p->out = stdout;
7808 rc = 1;
7809 } else {
7810 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7811 }
7812 }
7813 }else
7814
drh9cb02642019-02-28 20:10:52 +00007815 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
7816 open_db(p,0);
7817 if( nArg<=1 ) goto parameter_syntax_error;
7818
7819 /* .parameter clear
7820 ** Clear all bind parameters by dropping the TEMP table that holds them.
7821 */
7822 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
drh346f4e22019-03-25 21:35:41 +00007823 int wrSchema = 0;
7824 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
7825 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
drh65c29fd2019-03-25 21:56:26 +00007826 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
drh9cb02642019-02-28 20:10:52 +00007827 0, 0, 0);
drh346f4e22019-03-25 21:35:41 +00007828 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
drh9cb02642019-02-28 20:10:52 +00007829 }else
7830
7831 /* .parameter list
7832 ** List all bind parameters.
7833 */
7834 if( nArg==2 && strcmp(azArg[1],"list")==0 ){
7835 sqlite3_stmt *pStmt = 0;
7836 int rx;
7837 int len = 0;
7838 rx = sqlite3_prepare_v2(p->db,
7839 "SELECT max(length(key)) "
drh65c29fd2019-03-25 21:56:26 +00007840 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
drh9cb02642019-02-28 20:10:52 +00007841 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
7842 len = sqlite3_column_int(pStmt, 0);
7843 if( len>40 ) len = 40;
7844 }
7845 sqlite3_finalize(pStmt);
7846 pStmt = 0;
7847 if( len ){
7848 rx = sqlite3_prepare_v2(p->db,
7849 "SELECT key, quote(value) "
drh65c29fd2019-03-25 21:56:26 +00007850 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
drh9cb02642019-02-28 20:10:52 +00007851 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7852 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
7853 sqlite3_column_text(pStmt,1));
7854 }
7855 sqlite3_finalize(pStmt);
7856 }
7857 }else
7858
7859 /* .parameter init
7860 ** Make sure the TEMP table used to hold bind parameters exists.
7861 ** Create it if necessary.
7862 */
7863 if( nArg==2 && strcmp(azArg[1],"init")==0 ){
7864 bind_table_init(p);
7865 }else
7866
7867 /* .parameter set NAME VALUE
7868 ** Set or reset a bind parameter. NAME should be the full parameter
7869 ** name exactly as it appears in the query. (ex: $abc, @def). The
7870 ** VALUE can be in either SQL literal notation, or if not it will be
7871 ** understood to be a text string.
7872 */
7873 if( nArg==4 && strcmp(azArg[1],"set")==0 ){
7874 int rx;
7875 char *zSql;
7876 sqlite3_stmt *pStmt;
7877 const char *zKey = azArg[2];
7878 const char *zValue = azArg[3];
7879 bind_table_init(p);
7880 zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007881 "REPLACE INTO temp.sqlite_parameters(key,value)"
drh9cb02642019-02-28 20:10:52 +00007882 "VALUES(%Q,%s);", zKey, zValue);
7883 if( zSql==0 ) shell_out_of_memory();
7884 pStmt = 0;
7885 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7886 sqlite3_free(zSql);
7887 if( rx!=SQLITE_OK ){
7888 sqlite3_finalize(pStmt);
7889 pStmt = 0;
7890 zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007891 "REPLACE INTO temp.sqlite_parameters(key,value)"
drh9cb02642019-02-28 20:10:52 +00007892 "VALUES(%Q,%Q);", zKey, zValue);
7893 if( zSql==0 ) shell_out_of_memory();
7894 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7895 sqlite3_free(zSql);
7896 if( rx!=SQLITE_OK ){
7897 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
7898 sqlite3_finalize(pStmt);
7899 pStmt = 0;
7900 rc = 1;
7901 }
7902 }
7903 sqlite3_step(pStmt);
7904 sqlite3_finalize(pStmt);
7905 }else
7906
7907 /* .parameter unset NAME
7908 ** Remove the NAME binding from the parameter binding table, if it
7909 ** exists.
7910 */
7911 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
7912 char *zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007913 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
drh9cb02642019-02-28 20:10:52 +00007914 if( zSql==0 ) shell_out_of_memory();
7915 sqlite3_exec(p->db, zSql, 0, 0, 0);
7916 sqlite3_free(zSql);
7917 }else
7918 /* If no command name matches, show a syntax error */
7919 parameter_syntax_error:
7920 showHelp(p->out, "parameter");
7921 }else
7922
drh2ce15c32017-07-11 13:34:40 +00007923 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
7924 int i;
7925 for(i=1; i<nArg; i++){
7926 if( i>1 ) raw_printf(p->out, " ");
7927 utf8_printf(p->out, "%s", azArg[i]);
7928 }
7929 raw_printf(p->out, "\n");
7930 }else
7931
drh569b1d92019-02-05 20:51:41 +00007932#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00007933 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
7934 int i;
drhfc4eeef2019-02-05 19:48:46 +00007935 int nn = 0;
drh3f83f592019-02-04 14:53:18 +00007936 p->flgProgress = 0;
7937 p->mxProgress = 0;
7938 p->nProgress = 0;
7939 for(i=1; i<nArg; i++){
7940 const char *z = azArg[i];
7941 if( z[0]=='-' ){
7942 z++;
7943 if( z[0]=='-' ) z++;
7944 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007945 p->flgProgress |= SHELL_PROGRESS_QUIET;
drh3f83f592019-02-04 14:53:18 +00007946 continue;
7947 }
7948 if( strcmp(z,"reset")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007949 p->flgProgress |= SHELL_PROGRESS_RESET;
drh3f83f592019-02-04 14:53:18 +00007950 continue;
7951 }
7952 if( strcmp(z,"once")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00007953 p->flgProgress |= SHELL_PROGRESS_ONCE;
drh3f83f592019-02-04 14:53:18 +00007954 continue;
7955 }
7956 if( strcmp(z,"limit")==0 ){
7957 if( i+1>=nArg ){
7958 utf8_printf(stderr, "Error: missing argument on --limit\n");
7959 rc = 1;
7960 goto meta_command_exit;
7961 }else{
7962 p->mxProgress = (int)integerValue(azArg[++i]);
7963 }
7964 continue;
7965 }
7966 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
7967 rc = 1;
7968 goto meta_command_exit;
7969 }else{
drhfc4eeef2019-02-05 19:48:46 +00007970 nn = (int)integerValue(z);
drh3f83f592019-02-04 14:53:18 +00007971 }
7972 }
7973 open_db(p, 0);
drhfc4eeef2019-02-05 19:48:46 +00007974 sqlite3_progress_handler(p->db, nn, progress_handler, p);
drh3f83f592019-02-04 14:53:18 +00007975 }else
drh569b1d92019-02-05 20:51:41 +00007976#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00007977
drh2ce15c32017-07-11 13:34:40 +00007978 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
7979 if( nArg >= 2) {
7980 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
7981 }
7982 if( nArg >= 3) {
7983 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
7984 }
7985 }else
7986
7987 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
7988 rc = 2;
7989 }else
7990
7991 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
drh60379d42018-12-13 18:30:01 +00007992 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00007993 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00007994 if( nArg!=2 ){
7995 raw_printf(stderr, "Usage: .read FILE\n");
7996 rc = 1;
7997 goto meta_command_exit;
7998 }
drh60379d42018-12-13 18:30:01 +00007999 p->in = fopen(azArg[1], "rb");
8000 if( p->in==0 ){
drh2ce15c32017-07-11 13:34:40 +00008001 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
8002 rc = 1;
8003 }else{
drh60379d42018-12-13 18:30:01 +00008004 rc = process_input(p);
8005 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00008006 }
drh60379d42018-12-13 18:30:01 +00008007 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00008008 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00008009 }else
8010
8011 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
8012 const char *zSrcFile;
8013 const char *zDb;
8014 sqlite3 *pSrc;
8015 sqlite3_backup *pBackup;
8016 int nTimeout = 0;
8017
8018 if( nArg==2 ){
8019 zSrcFile = azArg[1];
8020 zDb = "main";
8021 }else if( nArg==3 ){
8022 zSrcFile = azArg[2];
8023 zDb = azArg[1];
8024 }else{
8025 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
8026 rc = 1;
8027 goto meta_command_exit;
8028 }
8029 rc = sqlite3_open(zSrcFile, &pSrc);
8030 if( rc!=SQLITE_OK ){
8031 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9e804032018-05-18 17:11:50 +00008032 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00008033 return 1;
8034 }
8035 open_db(p, 0);
8036 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
8037 if( pBackup==0 ){
8038 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9e804032018-05-18 17:11:50 +00008039 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00008040 return 1;
8041 }
8042 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
8043 || rc==SQLITE_BUSY ){
8044 if( rc==SQLITE_BUSY ){
8045 if( nTimeout++ >= 3 ) break;
8046 sqlite3_sleep(100);
8047 }
8048 }
8049 sqlite3_backup_finish(pBackup);
8050 if( rc==SQLITE_DONE ){
8051 rc = 0;
8052 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
8053 raw_printf(stderr, "Error: source database is busy\n");
8054 rc = 1;
8055 }else{
8056 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8057 rc = 1;
8058 }
drh9e804032018-05-18 17:11:50 +00008059 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00008060 }else
8061
drh2ce15c32017-07-11 13:34:40 +00008062 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
8063 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00008064 p->scanstatsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00008065#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
8066 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
8067#endif
8068 }else{
8069 raw_printf(stderr, "Usage: .scanstats on|off\n");
8070 rc = 1;
8071 }
8072 }else
8073
8074 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
8075 ShellText sSelect;
8076 ShellState data;
8077 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00008078 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00008079 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00008080 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00008081 int bDebug = 0;
8082 int ii;
drh2ce15c32017-07-11 13:34:40 +00008083
8084 open_db(p, 0);
8085 memcpy(&data, p, sizeof(data));
8086 data.showHeader = 0;
8087 data.cMode = data.mode = MODE_Semi;
8088 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00008089 for(ii=1; ii<nArg; ii++){
8090 if( optionMatch(azArg[ii],"indent") ){
8091 data.cMode = data.mode = MODE_Pretty;
8092 }else if( optionMatch(azArg[ii],"debug") ){
8093 bDebug = 1;
8094 }else if( zName==0 ){
8095 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00008096 }else{
drhceba7922018-01-01 21:28:25 +00008097 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
8098 rc = 1;
8099 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00008100 }
drh2ce15c32017-07-11 13:34:40 +00008101 }
drhceba7922018-01-01 21:28:25 +00008102 if( zName!=0 ){
mistachkin9d107262018-03-23 14:24:34 +00008103 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
8104 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
drh2ce15c32017-07-11 13:34:40 +00008105 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00008106 new_argv[0] = sqlite3_mprintf(
8107 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00008108 " type text,\n"
8109 " name text,\n"
8110 " tbl_name text,\n"
8111 " rootpage integer,\n"
8112 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00008113 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00008114 new_argv[1] = 0;
8115 new_colv[0] = "sql";
8116 new_colv[1] = 0;
8117 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00008118 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00008119 }
drh2ce15c32017-07-11 13:34:40 +00008120 }
8121 if( zDiv ){
8122 sqlite3_stmt *pStmt = 0;
8123 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
8124 -1, &pStmt, 0);
8125 if( rc ){
8126 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8127 sqlite3_finalize(pStmt);
8128 rc = 1;
8129 goto meta_command_exit;
8130 }
8131 appendText(&sSelect, "SELECT sql FROM", 0);
8132 iSchema = 0;
8133 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8134 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
8135 char zScNum[30];
8136 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
8137 appendText(&sSelect, zDiv, 0);
8138 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00008139 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
8140 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00008141 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00008142 }else{
drhceba7922018-01-01 21:28:25 +00008143 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00008144 }
drhceba7922018-01-01 21:28:25 +00008145 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
8146 appendText(&sSelect, zScNum, 0);
8147 appendText(&sSelect, " AS snum, ", 0);
8148 appendText(&sSelect, zDb, '\'');
8149 appendText(&sSelect, " AS sname FROM ", 0);
8150 appendText(&sSelect, zDb, '"');
8151 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00008152 }
8153 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00008154#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00008155 if( zName ){
8156 appendText(&sSelect,
8157 " UNION ALL SELECT shell_module_schema(name),"
8158 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
8159 }
drhcde7b772018-01-02 12:50:40 +00008160#endif
drh2ce15c32017-07-11 13:34:40 +00008161 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00008162 if( zName ){
8163 char *zQarg = sqlite3_mprintf("%Q", zName);
mistachkin9d107262018-03-23 14:24:34 +00008164 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
8165 strchr(zName, '[') != 0;
drhceba7922018-01-01 21:28:25 +00008166 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00008167 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
8168 }else{
8169 appendText(&sSelect, "lower(tbl_name)", 0);
8170 }
mistachkin9d107262018-03-23 14:24:34 +00008171 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00008172 appendText(&sSelect, zQarg, 0);
mistachkin9d107262018-03-23 14:24:34 +00008173 if( !bGlob ){
8174 appendText(&sSelect, " ESCAPE '\\' ", 0);
8175 }
drh2ce15c32017-07-11 13:34:40 +00008176 appendText(&sSelect, " AND ", 0);
8177 sqlite3_free(zQarg);
8178 }
8179 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
8180 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00008181 if( bDebug ){
8182 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
8183 }else{
8184 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
8185 }
drh2ce15c32017-07-11 13:34:40 +00008186 freeText(&sSelect);
8187 }
8188 if( zErrMsg ){
8189 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8190 sqlite3_free(zErrMsg);
8191 rc = 1;
8192 }else if( rc != SQLITE_OK ){
8193 raw_printf(stderr,"Error: querying schema information\n");
8194 rc = 1;
8195 }else{
8196 rc = 0;
8197 }
8198 }else
8199
8200#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
8201 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
8202 sqlite3SelectTrace = (int)integerValue(azArg[1]);
8203 }else
8204#endif
8205
8206#if defined(SQLITE_ENABLE_SESSION)
8207 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
8208 OpenSession *pSession = &p->aSession[0];
8209 char **azCmd = &azArg[1];
8210 int iSes = 0;
8211 int nCmd = nArg - 1;
8212 int i;
8213 if( nArg<=1 ) goto session_syntax_error;
8214 open_db(p, 0);
8215 if( nArg>=3 ){
8216 for(iSes=0; iSes<p->nSession; iSes++){
8217 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
8218 }
8219 if( iSes<p->nSession ){
8220 pSession = &p->aSession[iSes];
8221 azCmd++;
8222 nCmd--;
8223 }else{
8224 pSession = &p->aSession[0];
8225 iSes = 0;
8226 }
8227 }
8228
8229 /* .session attach TABLE
8230 ** Invoke the sqlite3session_attach() interface to attach a particular
8231 ** table so that it is never filtered.
8232 */
8233 if( strcmp(azCmd[0],"attach")==0 ){
8234 if( nCmd!=2 ) goto session_syntax_error;
8235 if( pSession->p==0 ){
8236 session_not_open:
8237 raw_printf(stderr, "ERROR: No sessions are open\n");
8238 }else{
8239 rc = sqlite3session_attach(pSession->p, azCmd[1]);
8240 if( rc ){
8241 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
8242 rc = 0;
8243 }
8244 }
8245 }else
8246
8247 /* .session changeset FILE
8248 ** .session patchset FILE
8249 ** Write a changeset or patchset into a file. The file is overwritten.
8250 */
8251 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
8252 FILE *out = 0;
8253 if( nCmd!=2 ) goto session_syntax_error;
8254 if( pSession->p==0 ) goto session_not_open;
8255 out = fopen(azCmd[1], "wb");
8256 if( out==0 ){
8257 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
8258 }else{
8259 int szChng;
8260 void *pChng;
8261 if( azCmd[0][0]=='c' ){
8262 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
8263 }else{
8264 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
8265 }
8266 if( rc ){
8267 printf("Error: error code %d\n", rc);
8268 rc = 0;
8269 }
8270 if( pChng
8271 && fwrite(pChng, szChng, 1, out)!=1 ){
8272 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
8273 szChng);
8274 }
8275 sqlite3_free(pChng);
8276 fclose(out);
8277 }
8278 }else
8279
8280 /* .session close
8281 ** Close the identified session
8282 */
8283 if( strcmp(azCmd[0], "close")==0 ){
8284 if( nCmd!=1 ) goto session_syntax_error;
8285 if( p->nSession ){
8286 session_close(pSession);
8287 p->aSession[iSes] = p->aSession[--p->nSession];
8288 }
8289 }else
8290
8291 /* .session enable ?BOOLEAN?
8292 ** Query or set the enable flag
8293 */
8294 if( strcmp(azCmd[0], "enable")==0 ){
8295 int ii;
8296 if( nCmd>2 ) goto session_syntax_error;
8297 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8298 if( p->nSession ){
8299 ii = sqlite3session_enable(pSession->p, ii);
8300 utf8_printf(p->out, "session %s enable flag = %d\n",
8301 pSession->zName, ii);
8302 }
8303 }else
8304
8305 /* .session filter GLOB ....
8306 ** Set a list of GLOB patterns of table names to be excluded.
8307 */
8308 if( strcmp(azCmd[0], "filter")==0 ){
8309 int ii, nByte;
8310 if( nCmd<2 ) goto session_syntax_error;
8311 if( p->nSession ){
8312 for(ii=0; ii<pSession->nFilter; ii++){
8313 sqlite3_free(pSession->azFilter[ii]);
8314 }
8315 sqlite3_free(pSession->azFilter);
8316 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
8317 pSession->azFilter = sqlite3_malloc( nByte );
8318 if( pSession->azFilter==0 ){
8319 raw_printf(stderr, "Error: out or memory\n");
8320 exit(1);
8321 }
8322 for(ii=1; ii<nCmd; ii++){
8323 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
8324 }
8325 pSession->nFilter = ii-1;
8326 }
8327 }else
8328
8329 /* .session indirect ?BOOLEAN?
8330 ** Query or set the indirect flag
8331 */
8332 if( strcmp(azCmd[0], "indirect")==0 ){
8333 int ii;
8334 if( nCmd>2 ) goto session_syntax_error;
8335 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8336 if( p->nSession ){
8337 ii = sqlite3session_indirect(pSession->p, ii);
8338 utf8_printf(p->out, "session %s indirect flag = %d\n",
8339 pSession->zName, ii);
8340 }
8341 }else
8342
8343 /* .session isempty
8344 ** Determine if the session is empty
8345 */
8346 if( strcmp(azCmd[0], "isempty")==0 ){
8347 int ii;
8348 if( nCmd!=1 ) goto session_syntax_error;
8349 if( p->nSession ){
8350 ii = sqlite3session_isempty(pSession->p);
8351 utf8_printf(p->out, "session %s isempty flag = %d\n",
8352 pSession->zName, ii);
8353 }
8354 }else
8355
8356 /* .session list
8357 ** List all currently open sessions
8358 */
8359 if( strcmp(azCmd[0],"list")==0 ){
8360 for(i=0; i<p->nSession; i++){
8361 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
8362 }
8363 }else
8364
8365 /* .session open DB NAME
8366 ** Open a new session called NAME on the attached database DB.
8367 ** DB is normally "main".
8368 */
8369 if( strcmp(azCmd[0],"open")==0 ){
8370 char *zName;
8371 if( nCmd!=3 ) goto session_syntax_error;
8372 zName = azCmd[2];
8373 if( zName[0]==0 ) goto session_syntax_error;
8374 for(i=0; i<p->nSession; i++){
8375 if( strcmp(p->aSession[i].zName,zName)==0 ){
8376 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
8377 goto meta_command_exit;
8378 }
8379 }
8380 if( p->nSession>=ArraySize(p->aSession) ){
8381 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
8382 goto meta_command_exit;
8383 }
8384 pSession = &p->aSession[p->nSession];
8385 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
8386 if( rc ){
8387 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
8388 rc = 0;
8389 goto meta_command_exit;
8390 }
8391 pSession->nFilter = 0;
8392 sqlite3session_table_filter(pSession->p, session_filter, pSession);
8393 p->nSession++;
8394 pSession->zName = sqlite3_mprintf("%s", zName);
8395 }else
8396 /* If no command name matches, show a syntax error */
8397 session_syntax_error:
drheb7f2a02018-09-26 18:02:32 +00008398 showHelp(p->out, "session");
drh2ce15c32017-07-11 13:34:40 +00008399 }else
8400#endif
8401
8402#ifdef SQLITE_DEBUG
8403 /* Undocumented commands for internal testing. Subject to change
8404 ** without notice. */
8405 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
8406 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
8407 int i, v;
8408 for(i=1; i<nArg; i++){
8409 v = booleanValue(azArg[i]);
8410 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
8411 }
8412 }
8413 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
8414 int i; sqlite3_int64 v;
8415 for(i=1; i<nArg; i++){
8416 char zBuf[200];
8417 v = integerValue(azArg[i]);
8418 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
8419 utf8_printf(p->out, "%s", zBuf);
8420 }
8421 }
8422 }else
8423#endif
8424
8425 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
8426 int bIsInit = 0; /* True to initialize the SELFTEST table */
8427 int bVerbose = 0; /* Verbose output */
8428 int bSelftestExists; /* True if SELFTEST already exists */
8429 int i, k; /* Loop counters */
8430 int nTest = 0; /* Number of tests runs */
8431 int nErr = 0; /* Number of errors seen */
8432 ShellText str; /* Answer for a query */
8433 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
8434
8435 open_db(p,0);
8436 for(i=1; i<nArg; i++){
8437 const char *z = azArg[i];
8438 if( z[0]=='-' && z[1]=='-' ) z++;
8439 if( strcmp(z,"-init")==0 ){
8440 bIsInit = 1;
8441 }else
8442 if( strcmp(z,"-v")==0 ){
8443 bVerbose++;
8444 }else
8445 {
8446 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8447 azArg[i], azArg[0]);
8448 raw_printf(stderr, "Should be one of: --init -v\n");
8449 rc = 1;
8450 goto meta_command_exit;
8451 }
8452 }
8453 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
8454 != SQLITE_OK ){
8455 bSelftestExists = 0;
8456 }else{
8457 bSelftestExists = 1;
8458 }
8459 if( bIsInit ){
8460 createSelftestTable(p);
8461 bSelftestExists = 1;
8462 }
8463 initText(&str);
8464 appendText(&str, "x", 0);
8465 for(k=bSelftestExists; k>=0; k--){
8466 if( k==1 ){
8467 rc = sqlite3_prepare_v2(p->db,
8468 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
8469 -1, &pStmt, 0);
8470 }else{
8471 rc = sqlite3_prepare_v2(p->db,
8472 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
8473 " (1,'run','PRAGMA integrity_check','ok')",
8474 -1, &pStmt, 0);
8475 }
8476 if( rc ){
8477 raw_printf(stderr, "Error querying the selftest table\n");
8478 rc = 1;
8479 sqlite3_finalize(pStmt);
8480 goto meta_command_exit;
8481 }
8482 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
8483 int tno = sqlite3_column_int(pStmt, 0);
8484 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
8485 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
8486 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
8487
8488 k = 0;
8489 if( bVerbose>0 ){
8490 char *zQuote = sqlite3_mprintf("%q", zSql);
8491 printf("%d: %s %s\n", tno, zOp, zSql);
8492 sqlite3_free(zQuote);
8493 }
8494 if( strcmp(zOp,"memo")==0 ){
8495 utf8_printf(p->out, "%s\n", zSql);
8496 }else
8497 if( strcmp(zOp,"run")==0 ){
8498 char *zErrMsg = 0;
8499 str.n = 0;
8500 str.z[0] = 0;
8501 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
8502 nTest++;
8503 if( bVerbose ){
8504 utf8_printf(p->out, "Result: %s\n", str.z);
8505 }
8506 if( rc || zErrMsg ){
8507 nErr++;
8508 rc = 1;
8509 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
8510 sqlite3_free(zErrMsg);
8511 }else if( strcmp(zAns,str.z)!=0 ){
8512 nErr++;
8513 rc = 1;
8514 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
8515 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
8516 }
8517 }else
8518 {
8519 utf8_printf(stderr,
8520 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
8521 rc = 1;
8522 break;
8523 }
8524 } /* End loop over rows of content from SELFTEST */
8525 sqlite3_finalize(pStmt);
8526 } /* End loop over k */
8527 freeText(&str);
8528 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
8529 }else
8530
8531 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
8532 if( nArg<2 || nArg>3 ){
8533 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
8534 rc = 1;
8535 }
8536 if( nArg>=2 ){
8537 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
8538 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
8539 }
8540 if( nArg>=3 ){
8541 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
8542 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
8543 }
8544 }else
8545
8546 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
8547 const char *zLike = 0; /* Which table to checksum. 0 means everything */
8548 int i; /* Loop counter */
8549 int bSchema = 0; /* Also hash the schema */
8550 int bSeparate = 0; /* Hash each table separately */
8551 int iSize = 224; /* Hash algorithm to use */
8552 int bDebug = 0; /* Only show the query that would have run */
8553 sqlite3_stmt *pStmt; /* For querying tables names */
8554 char *zSql; /* SQL to be run */
8555 char *zSep; /* Separator */
8556 ShellText sSql; /* Complete SQL for the query to run the hash */
8557 ShellText sQuery; /* Set of queries used to read all content */
8558 open_db(p, 0);
8559 for(i=1; i<nArg; i++){
8560 const char *z = azArg[i];
8561 if( z[0]=='-' ){
8562 z++;
8563 if( z[0]=='-' ) z++;
8564 if( strcmp(z,"schema")==0 ){
8565 bSchema = 1;
8566 }else
8567 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
8568 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
8569 ){
8570 iSize = atoi(&z[5]);
8571 }else
8572 if( strcmp(z,"debug")==0 ){
8573 bDebug = 1;
8574 }else
8575 {
8576 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8577 azArg[i], azArg[0]);
8578 raw_printf(stderr, "Should be one of: --schema"
drh003edba2018-05-11 15:10:43 +00008579 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
drh2ce15c32017-07-11 13:34:40 +00008580 rc = 1;
8581 goto meta_command_exit;
8582 }
8583 }else if( zLike ){
8584 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
8585 rc = 1;
8586 goto meta_command_exit;
8587 }else{
8588 zLike = z;
8589 bSeparate = 1;
drhcedfecf2018-03-23 12:59:10 +00008590 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
drh2ce15c32017-07-11 13:34:40 +00008591 }
8592 }
8593 if( bSchema ){
8594 zSql = "SELECT lower(name) FROM sqlite_master"
8595 " WHERE type='table' AND coalesce(rootpage,0)>1"
8596 " UNION ALL SELECT 'sqlite_master'"
8597 " ORDER BY 1 collate nocase";
8598 }else{
8599 zSql = "SELECT lower(name) FROM sqlite_master"
8600 " WHERE type='table' AND coalesce(rootpage,0)>1"
8601 " AND name NOT LIKE 'sqlite_%'"
8602 " ORDER BY 1 collate nocase";
8603 }
8604 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8605 initText(&sQuery);
8606 initText(&sSql);
8607 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
8608 zSep = "VALUES(";
8609 while( SQLITE_ROW==sqlite3_step(pStmt) ){
8610 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
8611 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
8612 if( strncmp(zTab, "sqlite_",7)!=0 ){
8613 appendText(&sQuery,"SELECT * FROM ", 0);
8614 appendText(&sQuery,zTab,'"');
8615 appendText(&sQuery," NOT INDEXED;", 0);
8616 }else if( strcmp(zTab, "sqlite_master")==0 ){
8617 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
8618 " ORDER BY name;", 0);
8619 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
8620 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
8621 " ORDER BY name;", 0);
8622 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
8623 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
8624 " ORDER BY tbl,idx;", 0);
8625 }else if( strcmp(zTab, "sqlite_stat3")==0
8626 || strcmp(zTab, "sqlite_stat4")==0 ){
8627 appendText(&sQuery, "SELECT * FROM ", 0);
8628 appendText(&sQuery, zTab, 0);
8629 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
8630 }
8631 appendText(&sSql, zSep, 0);
8632 appendText(&sSql, sQuery.z, '\'');
8633 sQuery.n = 0;
8634 appendText(&sSql, ",", 0);
8635 appendText(&sSql, zTab, '\'');
8636 zSep = "),(";
8637 }
8638 sqlite3_finalize(pStmt);
8639 if( bSeparate ){
8640 zSql = sqlite3_mprintf(
8641 "%s))"
8642 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
8643 " FROM [sha3sum$query]",
8644 sSql.z, iSize);
8645 }else{
8646 zSql = sqlite3_mprintf(
8647 "%s))"
8648 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
8649 " FROM [sha3sum$query]",
8650 sSql.z, iSize);
8651 }
8652 freeText(&sQuery);
8653 freeText(&sSql);
8654 if( bDebug ){
8655 utf8_printf(p->out, "%s\n", zSql);
8656 }else{
drha10b9992018-03-09 15:24:33 +00008657 shell_exec(p, zSql, 0);
drh2ce15c32017-07-11 13:34:40 +00008658 }
8659 sqlite3_free(zSql);
8660 }else
8661
drh04a28c32018-01-31 01:38:44 +00008662#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00008663 if( c=='s'
8664 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
8665 ){
8666 char *zCmd;
8667 int i, x;
8668 if( nArg<2 ){
8669 raw_printf(stderr, "Usage: .system COMMAND\n");
8670 rc = 1;
8671 goto meta_command_exit;
8672 }
8673 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
8674 for(i=2; i<nArg; i++){
8675 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
8676 zCmd, azArg[i]);
8677 }
8678 x = system(zCmd);
8679 sqlite3_free(zCmd);
8680 if( x ) raw_printf(stderr, "System command returns %d\n", x);
8681 }else
drh04a28c32018-01-31 01:38:44 +00008682#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00008683
8684 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00008685 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00008686 int i;
8687 if( nArg!=1 ){
8688 raw_printf(stderr, "Usage: .show\n");
8689 rc = 1;
8690 goto meta_command_exit;
8691 }
8692 utf8_printf(p->out, "%12.12s: %s\n","echo",
8693 azBool[ShellHasFlag(p, SHFLG_Echo)]);
8694 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
8695 utf8_printf(p->out, "%12.12s: %s\n","explain",
8696 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
8697 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
8698 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
8699 utf8_printf(p->out, "%12.12s: ", "nullvalue");
8700 output_c_string(p->out, p->nullValue);
8701 raw_printf(p->out, "\n");
8702 utf8_printf(p->out,"%12.12s: %s\n","output",
8703 strlen30(p->outfile) ? p->outfile : "stdout");
8704 utf8_printf(p->out,"%12.12s: ", "colseparator");
8705 output_c_string(p->out, p->colSeparator);
8706 raw_printf(p->out, "\n");
8707 utf8_printf(p->out,"%12.12s: ", "rowseparator");
8708 output_c_string(p->out, p->rowSeparator);
8709 raw_printf(p->out, "\n");
8710 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
8711 utf8_printf(p->out, "%12.12s: ", "width");
8712 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
8713 raw_printf(p->out, "%d ", p->colWidth[i]);
8714 }
8715 raw_printf(p->out, "\n");
8716 utf8_printf(p->out, "%12.12s: %s\n", "filename",
8717 p->zDbFilename ? p->zDbFilename : "");
8718 }else
8719
8720 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
8721 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00008722 p->statsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00008723 }else if( nArg==1 ){
8724 display_stats(p->db, p, 0);
8725 }else{
8726 raw_printf(stderr, "Usage: .stats ?on|off?\n");
8727 rc = 1;
8728 }
8729 }else
8730
8731 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
8732 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
8733 || strncmp(azArg[0], "indexes", n)==0) )
8734 ){
8735 sqlite3_stmt *pStmt;
8736 char **azResult;
8737 int nRow, nAlloc;
8738 int ii;
8739 ShellText s;
8740 initText(&s);
8741 open_db(p, 0);
8742 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
drh9e804032018-05-18 17:11:50 +00008743 if( rc ){
8744 sqlite3_finalize(pStmt);
8745 return shellDatabaseError(p->db);
8746 }
drh2ce15c32017-07-11 13:34:40 +00008747
8748 if( nArg>2 && c=='i' ){
8749 /* It is an historical accident that the .indexes command shows an error
8750 ** when called with the wrong number of arguments whereas the .tables
8751 ** command does not. */
8752 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
8753 rc = 1;
drh9e804032018-05-18 17:11:50 +00008754 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00008755 goto meta_command_exit;
8756 }
8757 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
8758 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
8759 if( zDbName==0 ) continue;
8760 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
8761 if( sqlite3_stricmp(zDbName, "main")==0 ){
8762 appendText(&s, "SELECT name FROM ", 0);
8763 }else{
8764 appendText(&s, "SELECT ", 0);
8765 appendText(&s, zDbName, '\'');
8766 appendText(&s, "||'.'||name FROM ", 0);
8767 }
8768 appendText(&s, zDbName, '"');
8769 appendText(&s, ".sqlite_master ", 0);
8770 if( c=='t' ){
8771 appendText(&s," WHERE type IN ('table','view')"
8772 " AND name NOT LIKE 'sqlite_%'"
8773 " AND name LIKE ?1", 0);
8774 }else{
8775 appendText(&s," WHERE type='index'"
8776 " AND tbl_name LIKE ?1", 0);
8777 }
8778 }
8779 rc = sqlite3_finalize(pStmt);
8780 appendText(&s, " ORDER BY 1", 0);
8781 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
8782 freeText(&s);
8783 if( rc ) return shellDatabaseError(p->db);
8784
8785 /* Run the SQL statement prepared by the above block. Store the results
8786 ** as an array of nul-terminated strings in azResult[]. */
8787 nRow = nAlloc = 0;
8788 azResult = 0;
8789 if( nArg>1 ){
8790 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
8791 }else{
8792 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
8793 }
8794 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8795 if( nRow>=nAlloc ){
8796 char **azNew;
8797 int n2 = nAlloc*2 + 10;
8798 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh4b5345c2018-04-24 13:07:40 +00008799 if( azNew==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008800 nAlloc = n2;
8801 azResult = azNew;
8802 }
8803 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
drh4b5345c2018-04-24 13:07:40 +00008804 if( 0==azResult[nRow] ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008805 nRow++;
8806 }
8807 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
8808 rc = shellDatabaseError(p->db);
8809 }
8810
8811 /* Pretty-print the contents of array azResult[] to the output */
8812 if( rc==0 && nRow>0 ){
8813 int len, maxlen = 0;
8814 int i, j;
8815 int nPrintCol, nPrintRow;
8816 for(i=0; i<nRow; i++){
8817 len = strlen30(azResult[i]);
8818 if( len>maxlen ) maxlen = len;
8819 }
8820 nPrintCol = 80/(maxlen+2);
8821 if( nPrintCol<1 ) nPrintCol = 1;
8822 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
8823 for(i=0; i<nPrintRow; i++){
8824 for(j=i; j<nRow; j+=nPrintRow){
8825 char *zSp = j<nPrintRow ? "" : " ";
8826 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
8827 azResult[j] ? azResult[j]:"");
8828 }
8829 raw_printf(p->out, "\n");
8830 }
8831 }
8832
8833 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
8834 sqlite3_free(azResult);
8835 }else
8836
8837 /* Begin redirecting output to the file "testcase-out.txt" */
8838 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
8839 output_reset(p);
drha92a01a2018-01-10 22:15:37 +00008840 p->out = output_file_open("testcase-out.txt", 0);
drh2ce15c32017-07-11 13:34:40 +00008841 if( p->out==0 ){
8842 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
8843 }
8844 if( nArg>=2 ){
8845 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
8846 }else{
8847 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
8848 }
8849 }else
8850
8851#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00008852 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00008853 static const struct {
8854 const char *zCtrlName; /* Name of a test-control option */
8855 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00008856 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00008857 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00008858 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
8859 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
8860 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
8861 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
8862 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
8863 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
8864 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
drheea8eb62018-11-26 18:09:15 +00008865 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" },
drhef302e82017-11-15 19:14:08 +00008866 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
8867 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
8868 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00008869#ifdef YYCOVERAGE
8870 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
8871#endif
drhef302e82017-11-15 19:14:08 +00008872 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
8873 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
8874 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
8875 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
8876 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00008877 };
8878 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00008879 int iCtrl = -1;
8880 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
8881 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00008882 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00008883 const char *zCmd = 0;
8884
drh2ce15c32017-07-11 13:34:40 +00008885 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00008886 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00008887
8888 /* The argument can optionally begin with "-" or "--" */
8889 if( zCmd[0]=='-' && zCmd[1] ){
8890 zCmd++;
8891 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8892 }
8893
8894 /* --help lists all test-controls */
8895 if( strcmp(zCmd,"help")==0 ){
8896 utf8_printf(p->out, "Available test-controls:\n");
8897 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00008898 utf8_printf(p->out, " .testctrl %s %s\n",
8899 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00008900 }
8901 rc = 1;
8902 goto meta_command_exit;
8903 }
drh2ce15c32017-07-11 13:34:40 +00008904
8905 /* convert testctrl text option to value. allow any unique prefix
8906 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00008907 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00008908 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00008909 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00008910 if( testctrl<0 ){
8911 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00008912 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00008913 }else{
drh35f51a42017-11-15 17:07:22 +00008914 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
8915 "Use \".testctrl --help\" for help\n", zCmd);
8916 rc = 1;
8917 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00008918 }
8919 }
8920 }
drhef302e82017-11-15 19:14:08 +00008921 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00008922 utf8_printf(stderr,"Error: unknown test-control: %s\n"
8923 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00008924 }else{
8925 switch(testctrl){
8926
8927 /* sqlite3_test_control(int, db, int) */
8928 case SQLITE_TESTCTRL_OPTIMIZATIONS:
8929 case SQLITE_TESTCTRL_RESERVE:
8930 if( nArg==3 ){
8931 int opt = (int)strtol(azArg[2], 0, 0);
8932 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00008933 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008934 }
8935 break;
8936
8937 /* sqlite3_test_control(int) */
8938 case SQLITE_TESTCTRL_PRNG_SAVE:
8939 case SQLITE_TESTCTRL_PRNG_RESTORE:
8940 case SQLITE_TESTCTRL_PRNG_RESET:
8941 case SQLITE_TESTCTRL_BYTEORDER:
8942 if( nArg==2 ){
8943 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00008944 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00008945 }
8946 break;
8947
8948 /* sqlite3_test_control(int, uint) */
8949 case SQLITE_TESTCTRL_PENDING_BYTE:
8950 if( nArg==3 ){
8951 unsigned int opt = (unsigned int)integerValue(azArg[2]);
8952 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00008953 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008954 }
8955 break;
8956
8957 /* sqlite3_test_control(int, int) */
8958 case SQLITE_TESTCTRL_ASSERT:
8959 case SQLITE_TESTCTRL_ALWAYS:
drheea8eb62018-11-26 18:09:15 +00008960 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
drhef302e82017-11-15 19:14:08 +00008961 if( nArg==3 ){
8962 int opt = booleanValue(azArg[2]);
8963 rc2 = sqlite3_test_control(testctrl, opt);
8964 isOk = 1;
8965 }
8966 break;
8967
8968 /* sqlite3_test_control(int, int) */
8969 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00008970 case SQLITE_TESTCTRL_NEVER_CORRUPT:
8971 if( nArg==3 ){
8972 int opt = booleanValue(azArg[2]);
8973 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00008974 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008975 }
8976 break;
8977
drh2ce15c32017-07-11 13:34:40 +00008978 case SQLITE_TESTCTRL_IMPOSTER:
8979 if( nArg==5 ){
8980 rc2 = sqlite3_test_control(testctrl, p->db,
8981 azArg[2],
8982 integerValue(azArg[3]),
8983 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00008984 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008985 }
8986 break;
drh0d9de992017-12-26 18:04:23 +00008987
8988#ifdef YYCOVERAGE
8989 case SQLITE_TESTCTRL_PARSER_COVERAGE:
8990 if( nArg==2 ){
8991 sqlite3_test_control(testctrl, p->out);
8992 isOk = 3;
8993 }
8994#endif
drh2ce15c32017-07-11 13:34:40 +00008995 }
8996 }
drhef302e82017-11-15 19:14:08 +00008997 if( isOk==0 && iCtrl>=0 ){
8998 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
8999 rc = 1;
9000 }else if( isOk==1 ){
9001 raw_printf(p->out, "%d\n", rc2);
9002 }else if( isOk==2 ){
9003 raw_printf(p->out, "0x%08x\n", rc2);
9004 }
drh2ce15c32017-07-11 13:34:40 +00009005 }else
9006#endif /* !defined(SQLITE_UNTESTABLE) */
9007
9008 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
9009 open_db(p, 0);
9010 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
9011 }else
9012
9013 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
9014 if( nArg==2 ){
9015 enableTimer = booleanValue(azArg[1]);
9016 if( enableTimer && !HAS_TIMER ){
9017 raw_printf(stderr, "Error: timer not available on this system.\n");
9018 enableTimer = 0;
9019 }
9020 }else{
9021 raw_printf(stderr, "Usage: .timer on|off\n");
9022 rc = 1;
9023 }
9024 }else
9025
drh707821f2018-12-05 13:39:06 +00009026#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00009027 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh707821f2018-12-05 13:39:06 +00009028 int mType = 0;
9029 int jj;
drh2ce15c32017-07-11 13:34:40 +00009030 open_db(p, 0);
drh707821f2018-12-05 13:39:06 +00009031 for(jj=1; jj<nArg; jj++){
9032 const char *z = azArg[jj];
9033 if( z[0]=='-' ){
9034 if( optionMatch(z, "expanded") ){
9035 p->eTraceType = SHELL_TRACE_EXPANDED;
9036 }
9037#ifdef SQLITE_ENABLE_NORMALIZE
9038 else if( optionMatch(z, "normalized") ){
9039 p->eTraceType = SHELL_TRACE_NORMALIZED;
9040 }
9041#endif
9042 else if( optionMatch(z, "plain") ){
9043 p->eTraceType = SHELL_TRACE_PLAIN;
9044 }
9045 else if( optionMatch(z, "profile") ){
9046 mType |= SQLITE_TRACE_PROFILE;
9047 }
9048 else if( optionMatch(z, "row") ){
9049 mType |= SQLITE_TRACE_ROW;
9050 }
9051 else if( optionMatch(z, "stmt") ){
9052 mType |= SQLITE_TRACE_STMT;
9053 }
9054 else if( optionMatch(z, "close") ){
9055 mType |= SQLITE_TRACE_CLOSE;
9056 }
9057 else {
9058 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
9059 rc = 1;
9060 goto meta_command_exit;
9061 }
9062 }else{
9063 output_file_close(p->traceOut);
9064 p->traceOut = output_file_open(azArg[1], 0);
9065 }
drh2ce15c32017-07-11 13:34:40 +00009066 }
drh2ce15c32017-07-11 13:34:40 +00009067 if( p->traceOut==0 ){
9068 sqlite3_trace_v2(p->db, 0, 0, 0);
9069 }else{
drh707821f2018-12-05 13:39:06 +00009070 if( mType==0 ) mType = SQLITE_TRACE_STMT;
9071 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
drh2ce15c32017-07-11 13:34:40 +00009072 }
drh2ce15c32017-07-11 13:34:40 +00009073 }else
drh707821f2018-12-05 13:39:06 +00009074#endif /* !defined(SQLITE_OMIT_TRACE) */
drh2ce15c32017-07-11 13:34:40 +00009075
9076#if SQLITE_USER_AUTHENTICATION
9077 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
9078 if( nArg<2 ){
9079 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
9080 rc = 1;
9081 goto meta_command_exit;
9082 }
9083 open_db(p, 0);
9084 if( strcmp(azArg[1],"login")==0 ){
9085 if( nArg!=4 ){
9086 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
9087 rc = 1;
9088 goto meta_command_exit;
9089 }
drhaf2770f2018-01-05 14:55:43 +00009090 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00009091 if( rc ){
9092 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
9093 rc = 1;
9094 }
9095 }else if( strcmp(azArg[1],"add")==0 ){
9096 if( nArg!=5 ){
9097 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
9098 rc = 1;
9099 goto meta_command_exit;
9100 }
drhaf2770f2018-01-05 14:55:43 +00009101 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00009102 booleanValue(azArg[4]));
9103 if( rc ){
9104 raw_printf(stderr, "User-Add failed: %d\n", rc);
9105 rc = 1;
9106 }
9107 }else if( strcmp(azArg[1],"edit")==0 ){
9108 if( nArg!=5 ){
9109 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
9110 rc = 1;
9111 goto meta_command_exit;
9112 }
drhaf2770f2018-01-05 14:55:43 +00009113 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00009114 booleanValue(azArg[4]));
9115 if( rc ){
9116 raw_printf(stderr, "User-Edit failed: %d\n", rc);
9117 rc = 1;
9118 }
9119 }else if( strcmp(azArg[1],"delete")==0 ){
9120 if( nArg!=3 ){
9121 raw_printf(stderr, "Usage: .user delete USER\n");
9122 rc = 1;
9123 goto meta_command_exit;
9124 }
9125 rc = sqlite3_user_delete(p->db, azArg[2]);
9126 if( rc ){
9127 raw_printf(stderr, "User-Delete failed: %d\n", rc);
9128 rc = 1;
9129 }
9130 }else{
9131 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
9132 rc = 1;
9133 goto meta_command_exit;
9134 }
9135 }else
9136#endif /* SQLITE_USER_AUTHENTICATION */
9137
9138 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
9139 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
9140 sqlite3_libversion(), sqlite3_sourceid());
drh0ed2fd82018-01-16 20:05:27 +00009141#if SQLITE_HAVE_ZLIB
9142 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
9143#endif
9144#define CTIMEOPT_VAL_(opt) #opt
9145#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
9146#if defined(__clang__) && defined(__clang_major__)
9147 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
9148 CTIMEOPT_VAL(__clang_minor__) "."
9149 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
9150#elif defined(_MSC_VER)
9151 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
9152#elif defined(__GNUC__) && defined(__VERSION__)
9153 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
9154#endif
drh2ce15c32017-07-11 13:34:40 +00009155 }else
9156
9157 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
9158 const char *zDbName = nArg==2 ? azArg[1] : "main";
9159 sqlite3_vfs *pVfs = 0;
9160 if( p->db ){
9161 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
9162 if( pVfs ){
9163 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
9164 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
9165 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
9166 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9167 }
9168 }
9169 }else
9170
9171 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
9172 sqlite3_vfs *pVfs;
9173 sqlite3_vfs *pCurrent = 0;
9174 if( p->db ){
9175 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
9176 }
9177 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
9178 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
9179 pVfs==pCurrent ? " <--- CURRENT" : "");
9180 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
9181 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
9182 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9183 if( pVfs->pNext ){
9184 raw_printf(p->out, "-----------------------------------\n");
9185 }
9186 }
9187 }else
9188
9189 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
9190 const char *zDbName = nArg==2 ? azArg[1] : "main";
9191 char *zVfsName = 0;
9192 if( p->db ){
9193 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
9194 if( zVfsName ){
9195 utf8_printf(p->out, "%s\n", zVfsName);
9196 sqlite3_free(zVfsName);
9197 }
9198 }
9199 }else
9200
9201#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
9202 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
9203 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
9204 }else
9205#endif
9206
9207 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
9208 int j;
9209 assert( nArg<=ArraySize(azArg) );
9210 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
9211 p->colWidth[j-1] = (int)integerValue(azArg[j]);
9212 }
9213 }else
9214
9215 {
9216 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
9217 " \"%s\". Enter \".help\" for help\n", azArg[0]);
9218 rc = 1;
9219 }
9220
9221meta_command_exit:
9222 if( p->outCount ){
9223 p->outCount--;
9224 if( p->outCount==0 ) output_reset(p);
9225 }
9226 return rc;
9227}
9228
9229/*
9230** Return TRUE if a semicolon occurs anywhere in the first N characters
9231** of string z[].
9232*/
9233static int line_contains_semicolon(const char *z, int N){
9234 int i;
9235 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
9236 return 0;
9237}
9238
9239/*
9240** Test to see if a line consists entirely of whitespace.
9241*/
9242static int _all_whitespace(const char *z){
9243 for(; *z; z++){
9244 if( IsSpace(z[0]) ) continue;
9245 if( *z=='/' && z[1]=='*' ){
9246 z += 2;
9247 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
9248 if( *z==0 ) return 0;
9249 z++;
9250 continue;
9251 }
9252 if( *z=='-' && z[1]=='-' ){
9253 z += 2;
9254 while( *z && *z!='\n' ){ z++; }
9255 if( *z==0 ) return 1;
9256 continue;
9257 }
9258 return 0;
9259 }
9260 return 1;
9261}
9262
9263/*
9264** Return TRUE if the line typed in is an SQL command terminator other
9265** than a semi-colon. The SQL Server style "go" command is understood
9266** as is the Oracle "/".
9267*/
9268static int line_is_command_terminator(const char *zLine){
9269 while( IsSpace(zLine[0]) ){ zLine++; };
9270 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
9271 return 1; /* Oracle */
9272 }
9273 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
9274 && _all_whitespace(&zLine[2]) ){
9275 return 1; /* SQL Server */
9276 }
9277 return 0;
9278}
9279
9280/*
drh56f17742018-01-24 01:58:49 +00009281** We need a default sqlite3_complete() implementation to use in case
9282** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
9283** any arbitrary text is a complete SQL statement. This is not very
9284** user-friendly, but it does seem to work.
9285*/
9286#ifdef SQLITE_OMIT_COMPLETE
danc86b23b2018-11-16 14:36:42 +00009287#define sqlite3_complete(x) 1
drh56f17742018-01-24 01:58:49 +00009288#endif
9289
9290/*
drh2ce15c32017-07-11 13:34:40 +00009291** Return true if zSql is a complete SQL statement. Return false if it
9292** ends in the middle of a string literal or C-style comment.
9293*/
9294static int line_is_complete(char *zSql, int nSql){
9295 int rc;
9296 if( zSql==0 ) return 1;
9297 zSql[nSql] = ';';
9298 zSql[nSql+1] = 0;
9299 rc = sqlite3_complete(zSql);
9300 zSql[nSql] = 0;
9301 return rc;
9302}
9303
9304/*
drhfc29a862018-05-11 19:11:18 +00009305** Run a single line of SQL. Return the number of errors.
drh2ce15c32017-07-11 13:34:40 +00009306*/
9307static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
9308 int rc;
9309 char *zErrMsg = 0;
9310
9311 open_db(p, 0);
9312 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drhfc4eeef2019-02-05 19:48:46 +00009313 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
drh2ce15c32017-07-11 13:34:40 +00009314 BEGIN_TIMER;
drha10b9992018-03-09 15:24:33 +00009315 rc = shell_exec(p, zSql, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00009316 END_TIMER;
9317 if( rc || zErrMsg ){
9318 char zPrefix[100];
9319 if( in!=0 || !stdin_is_interactive ){
9320 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
9321 "Error: near line %d:", startline);
9322 }else{
9323 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
9324 }
9325 if( zErrMsg!=0 ){
9326 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
9327 sqlite3_free(zErrMsg);
9328 zErrMsg = 0;
9329 }else{
9330 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
9331 }
9332 return 1;
9333 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
9334 raw_printf(p->out, "changes: %3d total_changes: %d\n",
9335 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
9336 }
9337 return 0;
9338}
9339
9340
9341/*
9342** Read input from *in and process it. If *in==0 then input
9343** is interactive - the user is typing it it. Otherwise, input
9344** is coming from a file or device. A prompt is issued and history
9345** is saved only if input is interactive. An interrupt signal will
9346** cause this routine to exit immediately, unless input is interactive.
9347**
9348** Return the number of errors.
9349*/
drh60379d42018-12-13 18:30:01 +00009350static int process_input(ShellState *p){
drh2ce15c32017-07-11 13:34:40 +00009351 char *zLine = 0; /* A single input line */
9352 char *zSql = 0; /* Accumulated SQL text */
9353 int nLine; /* Length of current line */
9354 int nSql = 0; /* Bytes of zSql[] used */
9355 int nAlloc = 0; /* Allocated zSql[] space */
9356 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
9357 int rc; /* Error code */
9358 int errCnt = 0; /* Number of errors seen */
drh2ce15c32017-07-11 13:34:40 +00009359 int startline = 0; /* Line number for start of current input */
9360
drh2c8ee022018-12-13 18:59:30 +00009361 p->lineno = 0;
drh60379d42018-12-13 18:30:01 +00009362 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
drh2ce15c32017-07-11 13:34:40 +00009363 fflush(p->out);
drh60379d42018-12-13 18:30:01 +00009364 zLine = one_input_line(p->in, zLine, nSql>0);
drh2ce15c32017-07-11 13:34:40 +00009365 if( zLine==0 ){
9366 /* End of input */
drh60379d42018-12-13 18:30:01 +00009367 if( p->in==0 && stdin_is_interactive ) printf("\n");
drh2ce15c32017-07-11 13:34:40 +00009368 break;
9369 }
9370 if( seenInterrupt ){
drh60379d42018-12-13 18:30:01 +00009371 if( p->in!=0 ) break;
drh2ce15c32017-07-11 13:34:40 +00009372 seenInterrupt = 0;
9373 }
drh2c8ee022018-12-13 18:59:30 +00009374 p->lineno++;
drh2ce15c32017-07-11 13:34:40 +00009375 if( nSql==0 && _all_whitespace(zLine) ){
9376 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
9377 continue;
9378 }
drh1615c372018-05-12 23:56:22 +00009379 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00009380 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh1615c372018-05-12 23:56:22 +00009381 if( zLine[0]=='.' ){
9382 rc = do_meta_command(zLine, p);
9383 if( rc==2 ){ /* exit requested */
9384 break;
9385 }else if( rc ){
9386 errCnt++;
9387 }
drh2ce15c32017-07-11 13:34:40 +00009388 }
9389 continue;
9390 }
9391 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
9392 memcpy(zLine,";",2);
9393 }
9394 nLine = strlen30(zLine);
9395 if( nSql+nLine+2>=nAlloc ){
9396 nAlloc = nSql+nLine+100;
9397 zSql = realloc(zSql, nAlloc);
drh4b5345c2018-04-24 13:07:40 +00009398 if( zSql==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009399 }
9400 nSqlPrior = nSql;
9401 if( nSql==0 ){
9402 int i;
9403 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
9404 assert( nAlloc>0 && zSql!=0 );
9405 memcpy(zSql, zLine+i, nLine+1-i);
drh2c8ee022018-12-13 18:59:30 +00009406 startline = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00009407 nSql = nLine-i;
9408 }else{
9409 zSql[nSql++] = '\n';
9410 memcpy(zSql+nSql, zLine, nLine+1);
9411 nSql += nLine;
9412 }
9413 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
9414 && sqlite3_complete(zSql) ){
drh60379d42018-12-13 18:30:01 +00009415 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00009416 nSql = 0;
9417 if( p->outCount ){
9418 output_reset(p);
9419 p->outCount = 0;
drh13c20932018-01-10 21:41:55 +00009420 }else{
9421 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00009422 }
9423 }else if( nSql && _all_whitespace(zSql) ){
9424 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
9425 nSql = 0;
9426 }
9427 }
9428 if( nSql && !_all_whitespace(zSql) ){
drh60379d42018-12-13 18:30:01 +00009429 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00009430 }
9431 free(zSql);
9432 free(zLine);
9433 return errCnt>0;
9434}
9435
9436/*
9437** Return a pathname which is the user's home directory. A
9438** 0 return indicates an error of some kind.
9439*/
9440static char *find_home_dir(int clearFlag){
9441 static char *home_dir = NULL;
9442 if( clearFlag ){
9443 free(home_dir);
9444 home_dir = 0;
9445 return 0;
9446 }
9447 if( home_dir ) return home_dir;
9448
9449#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
9450 && !defined(__RTP__) && !defined(_WRS_KERNEL)
9451 {
9452 struct passwd *pwent;
9453 uid_t uid = getuid();
9454 if( (pwent=getpwuid(uid)) != NULL) {
9455 home_dir = pwent->pw_dir;
9456 }
9457 }
9458#endif
9459
9460#if defined(_WIN32_WCE)
9461 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
9462 */
9463 home_dir = "/";
9464#else
9465
9466#if defined(_WIN32) || defined(WIN32)
9467 if (!home_dir) {
9468 home_dir = getenv("USERPROFILE");
9469 }
9470#endif
9471
9472 if (!home_dir) {
9473 home_dir = getenv("HOME");
9474 }
9475
9476#if defined(_WIN32) || defined(WIN32)
9477 if (!home_dir) {
9478 char *zDrive, *zPath;
9479 int n;
9480 zDrive = getenv("HOMEDRIVE");
9481 zPath = getenv("HOMEPATH");
9482 if( zDrive && zPath ){
9483 n = strlen30(zDrive) + strlen30(zPath) + 1;
9484 home_dir = malloc( n );
9485 if( home_dir==0 ) return 0;
9486 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
9487 return home_dir;
9488 }
9489 home_dir = "c:\\";
9490 }
9491#endif
9492
9493#endif /* !_WIN32_WCE */
9494
9495 if( home_dir ){
9496 int n = strlen30(home_dir) + 1;
9497 char *z = malloc( n );
9498 if( z ) memcpy(z, home_dir, n);
9499 home_dir = z;
9500 }
9501
9502 return home_dir;
9503}
9504
9505/*
9506** Read input from the file given by sqliterc_override. Or if that
9507** parameter is NULL, take input from ~/.sqliterc
9508**
9509** Returns the number of errors.
9510*/
9511static void process_sqliterc(
9512 ShellState *p, /* Configuration data */
9513 const char *sqliterc_override /* Name of config file. NULL to use default */
9514){
9515 char *home_dir = NULL;
9516 const char *sqliterc = sqliterc_override;
9517 char *zBuf = 0;
drh60379d42018-12-13 18:30:01 +00009518 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00009519 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00009520
9521 if (sqliterc == NULL) {
9522 home_dir = find_home_dir(0);
9523 if( home_dir==0 ){
9524 raw_printf(stderr, "-- warning: cannot find home directory;"
9525 " cannot read ~/.sqliterc\n");
9526 return;
9527 }
drh2ce15c32017-07-11 13:34:40 +00009528 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
9529 sqliterc = zBuf;
9530 }
drh60379d42018-12-13 18:30:01 +00009531 p->in = fopen(sqliterc,"rb");
9532 if( p->in ){
drh2ce15c32017-07-11 13:34:40 +00009533 if( stdin_is_interactive ){
9534 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
9535 }
drh60379d42018-12-13 18:30:01 +00009536 process_input(p);
9537 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00009538 }
drh60379d42018-12-13 18:30:01 +00009539 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00009540 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00009541 sqlite3_free(zBuf);
9542}
9543
9544/*
9545** Show available command line options
9546*/
9547static const char zOptions[] =
drhda57d962018-03-05 19:34:05 +00009548#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhad7fd5d2018-03-05 20:21:50 +00009549 " -A ARGS... run \".archive ARGS\" and exit\n"
drhda57d962018-03-05 19:34:05 +00009550#endif
drh3baed312018-03-08 18:14:41 +00009551 " -append append the database to the end of the file\n"
drh2ce15c32017-07-11 13:34:40 +00009552 " -ascii set output mode to 'ascii'\n"
9553 " -bail stop after hitting an error\n"
9554 " -batch force batch I/O\n"
9555 " -column set output mode to 'column'\n"
9556 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
9557 " -csv set output mode to 'csv'\n"
drh6ca64482019-01-22 16:06:20 +00009558#if defined(SQLITE_ENABLE_DESERIALIZE)
9559 " -deserialize open the database using sqlite3_deserialize()\n"
9560#endif
drh2ce15c32017-07-11 13:34:40 +00009561 " -echo print commands before execution\n"
9562 " -init FILENAME read/process named file\n"
9563 " -[no]header turn headers on or off\n"
9564#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
9565 " -heap SIZE Size of heap for memsys3 or memsys5\n"
9566#endif
9567 " -help show this message\n"
9568 " -html set output mode to HTML\n"
9569 " -interactive force interactive I/O\n"
9570 " -line set output mode to 'line'\n"
9571 " -list set output mode to 'list'\n"
9572 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh6ca64482019-01-22 16:06:20 +00009573#if defined(SQLITE_ENABLE_DESERIALIZE)
9574 " -maxsize N maximum size for a --deserialize database\n"
9575#endif
drhaf482572019-02-04 19:52:39 +00009576 " -memtrace trace all memory allocations and deallocations\n"
drh2ce15c32017-07-11 13:34:40 +00009577 " -mmap N default mmap size set to N\n"
9578#ifdef SQLITE_ENABLE_MULTIPLEX
9579 " -multiplex enable the multiplexor VFS\n"
9580#endif
9581 " -newline SEP set output row separator. Default: '\\n'\n"
9582 " -nullvalue TEXT set text string for NULL values. Default ''\n"
9583 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
9584 " -quote set output mode to 'quote'\n"
drhee269a62018-02-14 23:27:43 +00009585 " -readonly open the database read-only\n"
drh2ce15c32017-07-11 13:34:40 +00009586 " -separator SEP set output column separator. Default: '|'\n"
drha90d84f2018-04-18 15:21:13 +00009587#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9588 " -sorterref SIZE sorter references threshold size\n"
9589#endif
drh2ce15c32017-07-11 13:34:40 +00009590 " -stats print memory stats before each finalize\n"
9591 " -version show SQLite version\n"
9592 " -vfs NAME use NAME as the default VFS\n"
9593#ifdef SQLITE_ENABLE_VFSTRACE
9594 " -vfstrace enable tracing of all VFS calls\n"
9595#endif
drh3baed312018-03-08 18:14:41 +00009596#ifdef SQLITE_HAVE_ZLIB
9597 " -zip open the file as a ZIP Archive\n"
9598#endif
drh2ce15c32017-07-11 13:34:40 +00009599;
9600static void usage(int showDetail){
9601 utf8_printf(stderr,
9602 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
9603 "FILENAME is the name of an SQLite database. A new database is created\n"
9604 "if the file does not previously exist.\n", Argv0);
9605 if( showDetail ){
9606 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
9607 }else{
9608 raw_printf(stderr, "Use the -help option for additional information\n");
9609 }
9610 exit(1);
9611}
9612
9613/*
drhe7df8922018-04-18 10:44:58 +00009614** Internal check: Verify that the SQLite is uninitialized. Print a
9615** error message if it is initialized.
9616*/
9617static void verify_uninitialized(void){
9618 if( sqlite3_config(-1)==SQLITE_MISUSE ){
drh8e02a182018-05-30 07:24:41 +00009619 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
drhe7df8922018-04-18 10:44:58 +00009620 " initialization.\n");
9621 }
9622}
9623
9624/*
drh2ce15c32017-07-11 13:34:40 +00009625** Initialize the state information in data
9626*/
9627static void main_init(ShellState *data) {
9628 memset(data, 0, sizeof(*data));
9629 data->normalMode = data->cMode = data->mode = MODE_List;
9630 data->autoExplain = 1;
9631 memcpy(data->colSeparator,SEP_Column, 2);
9632 memcpy(data->rowSeparator,SEP_Row, 2);
9633 data->showHeader = 0;
9634 data->shellFlgs = SHFLG_Lookaside;
drhe7df8922018-04-18 10:44:58 +00009635 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00009636 sqlite3_config(SQLITE_CONFIG_URI, 1);
9637 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
9638 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
9639 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
9640 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
9641}
9642
9643/*
9644** Output text to the console in a font that attracts extra attention.
9645*/
9646#ifdef _WIN32
9647static void printBold(const char *zText){
9648 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
9649 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
9650 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
9651 SetConsoleTextAttribute(out,
9652 FOREGROUND_RED|FOREGROUND_INTENSITY
9653 );
9654 printf("%s", zText);
9655 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
9656}
9657#else
9658static void printBold(const char *zText){
9659 printf("\033[1m%s\033[0m", zText);
9660}
9661#endif
9662
9663/*
9664** Get the argument to an --option. Throw an error and die if no argument
9665** is available.
9666*/
9667static char *cmdline_option_value(int argc, char **argv, int i){
9668 if( i==argc ){
9669 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
9670 argv[0], argv[argc-1]);
9671 exit(1);
9672 }
9673 return argv[i];
9674}
9675
9676#ifndef SQLITE_SHELL_IS_UTF8
9677# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
9678# define SQLITE_SHELL_IS_UTF8 (0)
9679# else
9680# define SQLITE_SHELL_IS_UTF8 (1)
9681# endif
9682#endif
9683
9684#if SQLITE_SHELL_IS_UTF8
9685int SQLITE_CDECL main(int argc, char **argv){
9686#else
9687int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
9688 char **argv;
9689#endif
9690 char *zErrMsg = 0;
9691 ShellState data;
9692 const char *zInitFile = 0;
9693 int i;
9694 int rc = 0;
9695 int warnInmemoryDb = 0;
9696 int readStdin = 1;
9697 int nCmd = 0;
9698 char **azCmd = 0;
dan16a47422018-04-18 09:16:11 +00009699 const char *zVfs = 0; /* Value of -vfs command-line option */
drh1f22f622018-05-17 13:29:14 +00009700#if !SQLITE_SHELL_IS_UTF8
9701 char **argvToFree = 0;
9702 int argcToFree = 0;
9703#endif
drh2ce15c32017-07-11 13:34:40 +00009704
9705 setBinaryMode(stdin, 0);
9706 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
9707 stdin_is_interactive = isatty(0);
9708 stdout_is_console = isatty(1);
9709
mistachkin1e8487d2018-07-22 06:25:35 +00009710#if !defined(_WIN32_WCE)
9711 if( getenv("SQLITE_DEBUG_BREAK") ){
9712 if( isatty(0) && isatty(2) ){
9713 fprintf(stderr,
9714 "attach debugger to process %d and press any key to continue.\n",
9715 GETPID());
9716 fgetc(stdin);
9717 }else{
9718#if defined(_WIN32) || defined(WIN32)
9719 DebugBreak();
9720#elif defined(SIGTRAP)
9721 raise(SIGTRAP);
9722#endif
9723 }
9724 }
9725#endif
9726
drh2ce15c32017-07-11 13:34:40 +00009727#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00009728 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00009729 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
9730 sqlite3_sourceid(), SQLITE_SOURCE_ID);
9731 exit(1);
9732 }
9733#endif
9734 main_init(&data);
drh501ea052018-02-15 01:03:37 +00009735
9736 /* On Windows, we must translate command-line arguments into UTF-8.
9737 ** The SQLite memory allocator subsystem has to be enabled in order to
9738 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
9739 ** subsequent sqlite3_config() calls will work. So copy all results into
9740 ** memory that does not come from the SQLite memory allocator.
9741 */
drh4b18c1d2018-02-04 20:33:13 +00009742#if !SQLITE_SHELL_IS_UTF8
drh501ea052018-02-15 01:03:37 +00009743 sqlite3_initialize();
drh1f22f622018-05-17 13:29:14 +00009744 argvToFree = malloc(sizeof(argv[0])*argc*2);
9745 argcToFree = argc;
9746 argv = argvToFree + argc;
drh4b5345c2018-04-24 13:07:40 +00009747 if( argv==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009748 for(i=0; i<argc; i++){
drh501ea052018-02-15 01:03:37 +00009749 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
9750 int n;
drh4b5345c2018-04-24 13:07:40 +00009751 if( z==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00009752 n = (int)strlen(z);
9753 argv[i] = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00009754 if( argv[i]==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00009755 memcpy(argv[i], z, n+1);
drh1f22f622018-05-17 13:29:14 +00009756 argvToFree[i] = argv[i];
drh501ea052018-02-15 01:03:37 +00009757 sqlite3_free(z);
drh2ce15c32017-07-11 13:34:40 +00009758 }
drh501ea052018-02-15 01:03:37 +00009759 sqlite3_shutdown();
drh2ce15c32017-07-11 13:34:40 +00009760#endif
drh501ea052018-02-15 01:03:37 +00009761
drh2ce15c32017-07-11 13:34:40 +00009762 assert( argc>=1 && argv && argv[0] );
9763 Argv0 = argv[0];
9764
9765 /* Make sure we have a valid signal handler early, before anything
9766 ** else is done.
9767 */
9768#ifdef SIGINT
9769 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00009770#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
9771 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00009772#endif
9773
9774#ifdef SQLITE_SHELL_DBNAME_PROC
9775 {
9776 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
9777 ** of a C-function that will provide the name of the database file. Use
9778 ** this compile-time option to embed this shell program in larger
9779 ** applications. */
9780 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
9781 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
9782 warnInmemoryDb = 0;
9783 }
9784#endif
9785
9786 /* Do an initial pass through the command-line argument to locate
9787 ** the name of the database file, the name of the initialization file,
9788 ** the size of the alternative malloc heap,
9789 ** and the first command to execute.
9790 */
drhe7df8922018-04-18 10:44:58 +00009791 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00009792 for(i=1; i<argc; i++){
9793 char *z;
9794 z = argv[i];
9795 if( z[0]!='-' ){
9796 if( data.zDbFilename==0 ){
9797 data.zDbFilename = z;
9798 }else{
9799 /* Excesss arguments are interpreted as SQL (or dot-commands) and
9800 ** mean that nothing is read from stdin */
9801 readStdin = 0;
9802 nCmd++;
9803 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
drh4b5345c2018-04-24 13:07:40 +00009804 if( azCmd==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009805 azCmd[nCmd-1] = z;
9806 }
9807 }
9808 if( z[1]=='-' ) z++;
9809 if( strcmp(z,"-separator")==0
9810 || strcmp(z,"-nullvalue")==0
9811 || strcmp(z,"-newline")==0
9812 || strcmp(z,"-cmd")==0
9813 ){
9814 (void)cmdline_option_value(argc, argv, ++i);
9815 }else if( strcmp(z,"-init")==0 ){
9816 zInitFile = cmdline_option_value(argc, argv, ++i);
9817 }else if( strcmp(z,"-batch")==0 ){
9818 /* Need to check for batch mode here to so we can avoid printing
9819 ** informational messages (like from process_sqliterc) before
9820 ** we do the actual processing of arguments later in a second pass.
9821 */
9822 stdin_is_interactive = 0;
9823 }else if( strcmp(z,"-heap")==0 ){
9824#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
9825 const char *zSize;
9826 sqlite3_int64 szHeap;
9827
9828 zSize = cmdline_option_value(argc, argv, ++i);
9829 szHeap = integerValue(zSize);
9830 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
9831 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
9832#else
9833 (void)cmdline_option_value(argc, argv, ++i);
9834#endif
drh2ce15c32017-07-11 13:34:40 +00009835 }else if( strcmp(z,"-pagecache")==0 ){
9836 int n, sz;
9837 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
9838 if( sz>70000 ) sz = 70000;
9839 if( sz<0 ) sz = 0;
9840 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
9841 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
9842 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
9843 data.shellFlgs |= SHFLG_Pagecache;
9844 }else if( strcmp(z,"-lookaside")==0 ){
9845 int n, sz;
9846 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
9847 if( sz<0 ) sz = 0;
9848 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
9849 if( n<0 ) n = 0;
9850 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
9851 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
9852#ifdef SQLITE_ENABLE_VFSTRACE
9853 }else if( strcmp(z,"-vfstrace")==0 ){
9854 extern int vfstrace_register(
9855 const char *zTraceName,
9856 const char *zOldVfsName,
9857 int (*xOut)(const char*,void*),
9858 void *pOutArg,
9859 int makeDefault
9860 );
9861 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
9862#endif
9863#ifdef SQLITE_ENABLE_MULTIPLEX
9864 }else if( strcmp(z,"-multiplex")==0 ){
9865 extern int sqlite3_multiple_initialize(const char*,int);
9866 sqlite3_multiplex_initialize(0, 1);
9867#endif
9868 }else if( strcmp(z,"-mmap")==0 ){
9869 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
9870 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drha90d84f2018-04-18 15:21:13 +00009871#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9872 }else if( strcmp(z,"-sorterref")==0 ){
9873 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
9874 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
9875#endif
drh2ce15c32017-07-11 13:34:40 +00009876 }else if( strcmp(z,"-vfs")==0 ){
dan16a47422018-04-18 09:16:11 +00009877 zVfs = cmdline_option_value(argc, argv, ++i);
drh3baed312018-03-08 18:14:41 +00009878#ifdef SQLITE_HAVE_ZLIB
drh8682e122018-01-07 20:38:10 +00009879 }else if( strcmp(z,"-zip")==0 ){
9880 data.openMode = SHELL_OPEN_ZIPFILE;
9881#endif
9882 }else if( strcmp(z,"-append")==0 ){
9883 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +00009884#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00009885 }else if( strcmp(z,"-deserialize")==0 ){
9886 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +00009887 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
9888 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +00009889#endif
drhee269a62018-02-14 23:27:43 +00009890 }else if( strcmp(z,"-readonly")==0 ){
9891 data.openMode = SHELL_OPEN_READONLY;
drhda57d962018-03-05 19:34:05 +00009892#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00009893 }else if( strncmp(z, "-A",2)==0 ){
drhda57d962018-03-05 19:34:05 +00009894 /* All remaining command-line arguments are passed to the ".archive"
9895 ** command, so ignore them */
9896 break;
9897#endif
drh50b910a2019-01-21 14:55:03 +00009898 }else if( strcmp(z, "-memtrace")==0 ){
9899 sqlite3MemTraceActivate(stderr);
drh2ce15c32017-07-11 13:34:40 +00009900 }
9901 }
drhe7df8922018-04-18 10:44:58 +00009902 verify_uninitialized();
9903
dan16a47422018-04-18 09:16:11 +00009904
drhd11b8f62018-04-25 13:27:07 +00009905#ifdef SQLITE_SHELL_INIT_PROC
9906 {
9907 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
9908 ** of a C-function that will perform initialization actions on SQLite that
9909 ** occur just before or after sqlite3_initialize(). Use this compile-time
9910 ** option to embed this shell program in larger applications. */
9911 extern void SQLITE_SHELL_INIT_PROC(void);
9912 SQLITE_SHELL_INIT_PROC();
9913 }
9914#else
dan16a47422018-04-18 09:16:11 +00009915 /* All the sqlite3_config() calls have now been made. So it is safe
9916 ** to call sqlite3_initialize() and process any command line -vfs option. */
9917 sqlite3_initialize();
drhd11b8f62018-04-25 13:27:07 +00009918#endif
9919
dan16a47422018-04-18 09:16:11 +00009920 if( zVfs ){
9921 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
9922 if( pVfs ){
9923 sqlite3_vfs_register(pVfs, 1);
9924 }else{
9925 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
9926 exit(1);
9927 }
9928 }
9929
drh2ce15c32017-07-11 13:34:40 +00009930 if( data.zDbFilename==0 ){
9931#ifndef SQLITE_OMIT_MEMORYDB
9932 data.zDbFilename = ":memory:";
9933 warnInmemoryDb = argc==1;
9934#else
9935 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
9936 return 1;
9937#endif
9938 }
9939 data.out = stdout;
drh8682e122018-01-07 20:38:10 +00009940 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +00009941
9942 /* Go ahead and open the database file if it already exists. If the
9943 ** file does not exist, delay opening it. This prevents empty database
9944 ** files from being created if a user mistypes the database name argument
9945 ** to the sqlite command-line tool.
9946 */
9947 if( access(data.zDbFilename, 0)==0 ){
9948 open_db(&data, 0);
9949 }
9950
9951 /* Process the initialization file if there is one. If no -init option
9952 ** is given on the command line, look for a file named ~/.sqliterc and
9953 ** try to process it.
9954 */
9955 process_sqliterc(&data,zInitFile);
9956
9957 /* Make a second pass through the command-line argument and set
9958 ** options. This second pass is delayed until after the initialization
9959 ** file is processed so that the command-line arguments will override
9960 ** settings in the initialization file.
9961 */
9962 for(i=1; i<argc; i++){
9963 char *z = argv[i];
9964 if( z[0]!='-' ) continue;
9965 if( z[1]=='-' ){ z++; }
9966 if( strcmp(z,"-init")==0 ){
9967 i++;
9968 }else if( strcmp(z,"-html")==0 ){
9969 data.mode = MODE_Html;
9970 }else if( strcmp(z,"-list")==0 ){
9971 data.mode = MODE_List;
9972 }else if( strcmp(z,"-quote")==0 ){
9973 data.mode = MODE_Quote;
9974 }else if( strcmp(z,"-line")==0 ){
9975 data.mode = MODE_Line;
9976 }else if( strcmp(z,"-column")==0 ){
9977 data.mode = MODE_Column;
9978 }else if( strcmp(z,"-csv")==0 ){
9979 data.mode = MODE_Csv;
9980 memcpy(data.colSeparator,",",2);
drh3baed312018-03-08 18:14:41 +00009981#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00009982 }else if( strcmp(z,"-zip")==0 ){
9983 data.openMode = SHELL_OPEN_ZIPFILE;
9984#endif
9985 }else if( strcmp(z,"-append")==0 ){
9986 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +00009987#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00009988 }else if( strcmp(z,"-deserialize")==0 ){
9989 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +00009990 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
9991 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +00009992#endif
drh4aafe592018-03-23 16:08:30 +00009993 }else if( strcmp(z,"-readonly")==0 ){
9994 data.openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +00009995 }else if( strcmp(z,"-ascii")==0 ){
9996 data.mode = MODE_Ascii;
9997 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
9998 SEP_Unit);
9999 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
10000 SEP_Record);
10001 }else if( strcmp(z,"-separator")==0 ){
10002 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
10003 "%s",cmdline_option_value(argc,argv,++i));
10004 }else if( strcmp(z,"-newline")==0 ){
10005 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
10006 "%s",cmdline_option_value(argc,argv,++i));
10007 }else if( strcmp(z,"-nullvalue")==0 ){
10008 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
10009 "%s",cmdline_option_value(argc,argv,++i));
10010 }else if( strcmp(z,"-header")==0 ){
10011 data.showHeader = 1;
10012 }else if( strcmp(z,"-noheader")==0 ){
10013 data.showHeader = 0;
10014 }else if( strcmp(z,"-echo")==0 ){
10015 ShellSetFlag(&data, SHFLG_Echo);
10016 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +000010017 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +000010018 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +000010019 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +000010020 }else if( strcmp(z,"-stats")==0 ){
10021 data.statsOn = 1;
10022 }else if( strcmp(z,"-scanstats")==0 ){
10023 data.scanstatsOn = 1;
10024 }else if( strcmp(z,"-backslash")==0 ){
10025 /* Undocumented command-line option: -backslash
10026 ** Causes C-style backslash escapes to be evaluated in SQL statements
10027 ** prior to sending the SQL into SQLite. Useful for injecting
10028 ** crazy bytes in the middle of SQL statements for testing and debugging.
10029 */
10030 ShellSetFlag(&data, SHFLG_Backslash);
10031 }else if( strcmp(z,"-bail")==0 ){
10032 bail_on_error = 1;
10033 }else if( strcmp(z,"-version")==0 ){
10034 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
10035 return 0;
10036 }else if( strcmp(z,"-interactive")==0 ){
10037 stdin_is_interactive = 1;
10038 }else if( strcmp(z,"-batch")==0 ){
10039 stdin_is_interactive = 0;
10040 }else if( strcmp(z,"-heap")==0 ){
10041 i++;
drh2ce15c32017-07-11 13:34:40 +000010042 }else if( strcmp(z,"-pagecache")==0 ){
10043 i+=2;
10044 }else if( strcmp(z,"-lookaside")==0 ){
10045 i+=2;
10046 }else if( strcmp(z,"-mmap")==0 ){
10047 i++;
drh50b910a2019-01-21 14:55:03 +000010048 }else if( strcmp(z,"-memtrace")==0 ){
10049 i++;
drha90d84f2018-04-18 15:21:13 +000010050#ifdef SQLITE_ENABLE_SORTER_REFERENCES
10051 }else if( strcmp(z,"-sorterref")==0 ){
10052 i++;
10053#endif
drh2ce15c32017-07-11 13:34:40 +000010054 }else if( strcmp(z,"-vfs")==0 ){
10055 i++;
10056#ifdef SQLITE_ENABLE_VFSTRACE
10057 }else if( strcmp(z,"-vfstrace")==0 ){
10058 i++;
10059#endif
10060#ifdef SQLITE_ENABLE_MULTIPLEX
10061 }else if( strcmp(z,"-multiplex")==0 ){
10062 i++;
10063#endif
10064 }else if( strcmp(z,"-help")==0 ){
10065 usage(1);
10066 }else if( strcmp(z,"-cmd")==0 ){
10067 /* Run commands that follow -cmd first and separately from commands
10068 ** that simply appear on the command-line. This seems goofy. It would
10069 ** be better if all commands ran in the order that they appear. But
10070 ** we retain the goofy behavior for historical compatibility. */
10071 if( i==argc-1 ) break;
10072 z = cmdline_option_value(argc,argv,++i);
10073 if( z[0]=='.' ){
10074 rc = do_meta_command(z, &data);
10075 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
10076 }else{
10077 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +000010078 rc = shell_exec(&data, z, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +000010079 if( zErrMsg!=0 ){
10080 utf8_printf(stderr,"Error: %s\n", zErrMsg);
10081 if( bail_on_error ) return rc!=0 ? rc : 1;
10082 }else if( rc!=0 ){
10083 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
10084 if( bail_on_error ) return rc;
10085 }
10086 }
drhda57d962018-03-05 19:34:05 +000010087#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +000010088 }else if( strncmp(z, "-A", 2)==0 ){
drhda57d962018-03-05 19:34:05 +000010089 if( nCmd>0 ){
10090 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
10091 " with \"%s\"\n", z);
10092 return 1;
10093 }
drhbe4ccb22018-05-17 20:04:24 +000010094 open_db(&data, OPEN_DB_ZIPFILE);
drh93b77312018-03-05 20:20:22 +000010095 if( z[2] ){
10096 argv[i] = &z[2];
drhd0f9cdc2018-05-17 14:09:06 +000010097 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
drh93b77312018-03-05 20:20:22 +000010098 }else{
drhd0f9cdc2018-05-17 14:09:06 +000010099 arDotCommand(&data, 1, argv+i, argc-i);
drh93b77312018-03-05 20:20:22 +000010100 }
drhda57d962018-03-05 19:34:05 +000010101 readStdin = 0;
10102 break;
10103#endif
drh2ce15c32017-07-11 13:34:40 +000010104 }else{
10105 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
10106 raw_printf(stderr,"Use -help for a list of options.\n");
10107 return 1;
10108 }
10109 data.cMode = data.mode;
10110 }
10111
10112 if( !readStdin ){
10113 /* Run all arguments that do not begin with '-' as if they were separate
10114 ** command-line inputs, except for the argToSkip argument which contains
10115 ** the database filename.
10116 */
10117 for(i=0; i<nCmd; i++){
10118 if( azCmd[i][0]=='.' ){
10119 rc = do_meta_command(azCmd[i], &data);
10120 if( rc ) return rc==2 ? 0 : rc;
10121 }else{
10122 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +000010123 rc = shell_exec(&data, azCmd[i], &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +000010124 if( zErrMsg!=0 ){
10125 utf8_printf(stderr,"Error: %s\n", zErrMsg);
10126 return rc!=0 ? rc : 1;
10127 }else if( rc!=0 ){
10128 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
10129 return rc;
10130 }
10131 }
10132 }
10133 free(azCmd);
10134 }else{
10135 /* Run commands received from standard input
10136 */
10137 if( stdin_is_interactive ){
10138 char *zHome;
drha9e4be32018-10-10 18:56:40 +000010139 char *zHistory;
drh2ce15c32017-07-11 13:34:40 +000010140 int nHistory;
10141 printf(
10142 "SQLite version %s %.19s\n" /*extra-version-info*/
10143 "Enter \".help\" for usage hints.\n",
10144 sqlite3_libversion(), sqlite3_sourceid()
10145 );
10146 if( warnInmemoryDb ){
10147 printf("Connected to a ");
10148 printBold("transient in-memory database");
10149 printf(".\nUse \".open FILENAME\" to reopen on a "
10150 "persistent database.\n");
10151 }
drha9e4be32018-10-10 18:56:40 +000010152 zHistory = getenv("SQLITE_HISTORY");
10153 if( zHistory ){
10154 zHistory = strdup(zHistory);
10155 }else if( (zHome = find_home_dir(0))!=0 ){
drh2ce15c32017-07-11 13:34:40 +000010156 nHistory = strlen30(zHome) + 20;
10157 if( (zHistory = malloc(nHistory))!=0 ){
10158 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
10159 }
10160 }
10161 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +000010162#if HAVE_READLINE || HAVE_EDITLINE
10163 rl_attempted_completion_function = readline_completion;
10164#elif HAVE_LINENOISE
10165 linenoiseSetCompletionCallback(linenoise_completion);
10166#endif
drh60379d42018-12-13 18:30:01 +000010167 data.in = 0;
10168 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +000010169 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +000010170 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +000010171 shell_write_history(zHistory);
10172 free(zHistory);
10173 }
10174 }else{
drh60379d42018-12-13 18:30:01 +000010175 data.in = stdin;
10176 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +000010177 }
10178 }
10179 set_table_name(&data, 0);
10180 if( data.db ){
10181 session_close_all(&data);
drh9e804032018-05-18 17:11:50 +000010182 close_db(data.db);
drh2ce15c32017-07-11 13:34:40 +000010183 }
10184 sqlite3_free(data.zFreeOnClose);
10185 find_home_dir(1);
drh536c3452018-01-11 00:38:39 +000010186 output_reset(&data);
10187 data.doXdgOpen = 0;
drh13c20932018-01-10 21:41:55 +000010188 clearTempFile(&data);
drh2ce15c32017-07-11 13:34:40 +000010189#if !SQLITE_SHELL_IS_UTF8
drh1f22f622018-05-17 13:29:14 +000010190 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
10191 free(argvToFree);
drh2ce15c32017-07-11 13:34:40 +000010192#endif
drh9e804032018-05-18 17:11:50 +000010193 /* Clear the global data structure so that valgrind will detect memory
10194 ** leaks */
10195 memset(&data, 0, sizeof(data));
drh2ce15c32017-07-11 13:34:40 +000010196 return rc;
10197}