blob: f2473ce1554996523fb2308f34e0ee701861e1d8 [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
dan1b162162019-04-27 20:15:15 +0000951#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
dan68cb86e2019-04-20 20:57:28 +0000952INCLUDE ../ext/misc/dbdata.c
dan1b162162019-04-27 20:15:15 +0000953#endif
dan68cb86e2019-04-20 20:57:28 +0000954
drh2ce15c32017-07-11 13:34:40 +0000955#if defined(SQLITE_ENABLE_SESSION)
956/*
957** State information for a single open session
958*/
959typedef struct OpenSession OpenSession;
960struct OpenSession {
961 char *zName; /* Symbolic name for this session */
962 int nFilter; /* Number of xFilter rejection GLOB patterns */
963 char **azFilter; /* Array of xFilter rejection GLOB patterns */
964 sqlite3_session *p; /* The open session */
965};
966#endif
967
968/*
969** Shell output mode information from before ".explain on",
970** saved so that it can be restored by ".explain off"
971*/
972typedef struct SavedModeInfo SavedModeInfo;
973struct SavedModeInfo {
974 int valid; /* Is there legit data in here? */
975 int mode; /* Mode prior to ".explain on" */
976 int showHeader; /* The ".header" setting prior to ".explain on" */
977 int colWidth[100]; /* Column widths prior to ".explain on" */
978};
979
dan43efc182017-12-19 17:42:13 +0000980typedef struct ExpertInfo ExpertInfo;
981struct ExpertInfo {
982 sqlite3expert *pExpert;
983 int bVerbose;
984};
985
drh4b5345c2018-04-24 13:07:40 +0000986/* A single line in the EQP output */
987typedef struct EQPGraphRow EQPGraphRow;
988struct EQPGraphRow {
drhe2ca99c2018-05-02 00:33:43 +0000989 int iEqpId; /* ID for this row */
990 int iParentId; /* ID of the parent row */
drh4b5345c2018-04-24 13:07:40 +0000991 EQPGraphRow *pNext; /* Next row in sequence */
992 char zText[1]; /* Text to display for this row */
993};
994
995/* All EQP output is collected into an instance of the following */
996typedef struct EQPGraph EQPGraph;
997struct EQPGraph {
998 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
999 EQPGraphRow *pLast; /* Last element of the pRow list */
1000 char zPrefix[100]; /* Graph prefix */
1001};
1002
drh2ce15c32017-07-11 13:34:40 +00001003/*
1004** State information about the database connection is contained in an
1005** instance of the following structure.
1006*/
1007typedef struct ShellState ShellState;
1008struct ShellState {
1009 sqlite3 *db; /* The database */
drh1fa6d9f2018-01-06 21:46:01 +00001010 u8 autoExplain; /* Automatically turn on .explain mode */
1011 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
drhe2ca99c2018-05-02 00:33:43 +00001012 u8 autoEQPtest; /* autoEQP is in test mode */
drhb4e50392019-01-26 15:40:04 +00001013 u8 autoEQPtrace; /* autoEQP is in trace mode */
drh1fa6d9f2018-01-06 21:46:01 +00001014 u8 statsOn; /* True to display memory stats before each finalize */
1015 u8 scanstatsOn; /* True to display scan stats before each finalize */
1016 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
drh13c20932018-01-10 21:41:55 +00001017 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
drh4b5345c2018-04-24 13:07:40 +00001018 u8 nEqpLevel; /* Depth of the EQP output graph */
drh707821f2018-12-05 13:39:06 +00001019 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
drh4b5345c2018-04-24 13:07:40 +00001020 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
drh2ce15c32017-07-11 13:34:40 +00001021 int outCount; /* Revert to stdout when reaching zero */
1022 int cnt; /* Number of records displayed so far */
drh2c8ee022018-12-13 18:59:30 +00001023 int lineno; /* Line number of last line read from in */
drh60379d42018-12-13 18:30:01 +00001024 FILE *in; /* Read commands from this stream */
drh2ce15c32017-07-11 13:34:40 +00001025 FILE *out; /* Write results here */
1026 FILE *traceOut; /* Output for sqlite3_trace() */
1027 int nErr; /* Number of errors seen */
1028 int mode; /* An output mode setting */
drh3c484e82018-01-10 22:27:21 +00001029 int modePrior; /* Saved mode */
drh2ce15c32017-07-11 13:34:40 +00001030 int cMode; /* temporary output mode for the current query */
1031 int normalMode; /* Output mode before ".explain on" */
1032 int writableSchema; /* True if PRAGMA writable_schema=ON */
1033 int showHeader; /* True to show column names in List or Column mode */
1034 int nCheck; /* Number of ".check" commands run */
drh3f83f592019-02-04 14:53:18 +00001035 unsigned nProgress; /* Number of progress callbacks encountered */
1036 unsigned mxProgress; /* Maximum progress callbacks before failing */
1037 unsigned flgProgress; /* Flags for the progress callback */
drh2ce15c32017-07-11 13:34:40 +00001038 unsigned shellFlgs; /* Various flags */
drh6ca64482019-01-22 16:06:20 +00001039 sqlite3_int64 szMax; /* --maxsize argument to .open */
drh2ce15c32017-07-11 13:34:40 +00001040 char *zDestTable; /* Name of destination table when MODE_Insert */
drh13c20932018-01-10 21:41:55 +00001041 char *zTempFile; /* Temporary file that might need deleting */
drh2ce15c32017-07-11 13:34:40 +00001042 char zTestcase[30]; /* Name of current test case */
1043 char colSeparator[20]; /* Column separator character for several modes */
1044 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drh3c484e82018-01-10 22:27:21 +00001045 char colSepPrior[20]; /* Saved column separator */
1046 char rowSepPrior[20]; /* Saved row separator */
drh2ce15c32017-07-11 13:34:40 +00001047 int colWidth[100]; /* Requested width of each column when in column mode*/
1048 int actualWidth[100]; /* Actual width of each column */
1049 char nullValue[20]; /* The text to print when a NULL comes back from
1050 ** the database */
1051 char outfile[FILENAME_MAX]; /* Filename for *out */
1052 const char *zDbFilename; /* name of the database file */
1053 char *zFreeOnClose; /* Filename to free when closing */
1054 const char *zVfs; /* Name of VFS to use */
1055 sqlite3_stmt *pStmt; /* Current statement if any. */
1056 FILE *pLog; /* Write log output here */
1057 int *aiIndent; /* Array of indents used in MODE_Explain */
1058 int nIndent; /* Size of array aiIndent[] */
1059 int iIndent; /* Index of current op in aiIndent[] */
drh4b5345c2018-04-24 13:07:40 +00001060 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
drh2ce15c32017-07-11 13:34:40 +00001061#if defined(SQLITE_ENABLE_SESSION)
1062 int nSession; /* Number of active sessions */
1063 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1064#endif
dan43efc182017-12-19 17:42:13 +00001065 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
drh2ce15c32017-07-11 13:34:40 +00001066};
1067
drh1fa6d9f2018-01-06 21:46:01 +00001068
drhada70452017-12-21 21:02:27 +00001069/* Allowed values for ShellState.autoEQP
1070*/
drhe2ca99c2018-05-02 00:33:43 +00001071#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1072#define AUTOEQP_on 1 /* Automatic EQP is on */
1073#define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1074#define AUTOEQP_full 3 /* Show full EXPLAIN */
drhada70452017-12-21 21:02:27 +00001075
drh1fa6d9f2018-01-06 21:46:01 +00001076/* Allowed values for ShellState.openMode
1077*/
drh60f34ae2018-10-30 13:19:49 +00001078#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1079#define SHELL_OPEN_NORMAL 1 /* Normal database file */
1080#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1081#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1082#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1083#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
drh33746482018-12-13 15:06:26 +00001084#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
drh1fa6d9f2018-01-06 21:46:01 +00001085
drh707821f2018-12-05 13:39:06 +00001086/* Allowed values for ShellState.eTraceType
1087*/
1088#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1089#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1090#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1091
drh3f83f592019-02-04 14:53:18 +00001092/* Bits in the ShellState.flgProgress variable */
drhfc4eeef2019-02-05 19:48:46 +00001093#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1094#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1095 ** callback limit is reached, and for each
1096 ** top-level SQL statement */
1097#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
drh3f83f592019-02-04 14:53:18 +00001098
drh2ce15c32017-07-11 13:34:40 +00001099/*
1100** These are the allowed shellFlgs values
1101*/
drhb2a0f752017-08-28 15:51:35 +00001102#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1103#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1104#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1105#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1106#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1107#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1108#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
drh2ce15c32017-07-11 13:34:40 +00001109
1110/*
1111** Macros for testing and setting shellFlgs
1112*/
1113#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1114#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1115#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1116
1117/*
1118** These are the allowed modes.
1119*/
1120#define MODE_Line 0 /* One column per line. Blank line between records */
1121#define MODE_Column 1 /* One record per line in neat columns */
1122#define MODE_List 2 /* One record per line with a separator */
1123#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1124#define MODE_Html 4 /* Generate an XHTML table */
1125#define MODE_Insert 5 /* Generate SQL "insert" statements */
1126#define MODE_Quote 6 /* Quote values as for SQL */
1127#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1128#define MODE_Csv 8 /* Quote strings, numbers are plain */
1129#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1130#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1131#define MODE_Pretty 11 /* Pretty-print schemas */
drh4b5345c2018-04-24 13:07:40 +00001132#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
drh2ce15c32017-07-11 13:34:40 +00001133
1134static const char *modeDescr[] = {
1135 "line",
1136 "column",
1137 "list",
1138 "semi",
1139 "html",
1140 "insert",
1141 "quote",
1142 "tcl",
1143 "csv",
1144 "explain",
1145 "ascii",
1146 "prettyprint",
drh4b5345c2018-04-24 13:07:40 +00001147 "eqp"
drh2ce15c32017-07-11 13:34:40 +00001148};
1149
1150/*
1151** These are the column/row/line separators used by the various
1152** import/export modes.
1153*/
1154#define SEP_Column "|"
1155#define SEP_Row "\n"
1156#define SEP_Tab "\t"
1157#define SEP_Space " "
1158#define SEP_Comma ","
1159#define SEP_CrLf "\r\n"
1160#define SEP_Unit "\x1F"
1161#define SEP_Record "\x1E"
1162
1163/*
drh2ce15c32017-07-11 13:34:40 +00001164** A callback for the sqlite3_log() interface.
1165*/
1166static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1167 ShellState *p = (ShellState*)pArg;
1168 if( p->pLog==0 ) return;
1169 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1170 fflush(p->pLog);
1171}
1172
1173/*
drh634c70f2018-01-10 16:50:18 +00001174** SQL function: shell_putsnl(X)
1175**
1176** Write the text X to the screen (or whatever output is being directed)
1177** adding a newline at the end, and then return X.
1178*/
1179static void shellPutsFunc(
1180 sqlite3_context *pCtx,
1181 int nVal,
1182 sqlite3_value **apVal
1183){
1184 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
drhb9685182018-01-17 13:15:23 +00001185 (void)nVal;
drh634c70f2018-01-10 16:50:18 +00001186 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1187 sqlite3_result_value(pCtx, apVal[0]);
1188}
1189
1190/*
drh97913132018-01-11 00:04:00 +00001191** SQL function: edit(VALUE)
1192** edit(VALUE,EDITOR)
1193**
1194** These steps:
1195**
1196** (1) Write VALUE into a temporary file.
1197** (2) Run program EDITOR on that temporary file.
1198** (3) Read the temporary file back and return its content as the result.
1199** (4) Delete the temporary file
1200**
1201** If the EDITOR argument is omitted, use the value in the VISUAL
1202** environment variable. If still there is no EDITOR, through an error.
1203**
1204** Also throw an error if the EDITOR program returns a non-zero exit code.
1205*/
drh04a28c32018-01-31 01:38:44 +00001206#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00001207static void editFunc(
1208 sqlite3_context *context,
1209 int argc,
1210 sqlite3_value **argv
1211){
1212 const char *zEditor;
1213 char *zTempFile = 0;
1214 sqlite3 *db;
1215 char *zCmd = 0;
1216 int bBin;
1217 int rc;
drhf018fd52018-08-06 02:08:53 +00001218 int hasCRNL = 0;
drh97913132018-01-11 00:04:00 +00001219 FILE *f = 0;
1220 sqlite3_int64 sz;
1221 sqlite3_int64 x;
1222 unsigned char *p = 0;
1223
1224 if( argc==2 ){
1225 zEditor = (const char*)sqlite3_value_text(argv[1]);
1226 }else{
1227 zEditor = getenv("VISUAL");
1228 }
1229 if( zEditor==0 ){
1230 sqlite3_result_error(context, "no editor for edit()", -1);
1231 return;
1232 }
1233 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1234 sqlite3_result_error(context, "NULL input to edit()", -1);
1235 return;
1236 }
1237 db = sqlite3_context_db_handle(context);
1238 zTempFile = 0;
1239 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1240 if( zTempFile==0 ){
1241 sqlite3_uint64 r = 0;
1242 sqlite3_randomness(sizeof(r), &r);
1243 zTempFile = sqlite3_mprintf("temp%llx", r);
1244 if( zTempFile==0 ){
1245 sqlite3_result_error_nomem(context);
1246 return;
1247 }
1248 }
1249 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
drhf018fd52018-08-06 02:08:53 +00001250 /* When writing the file to be edited, do \n to \r\n conversions on systems
1251 ** that want \r\n line endings */
drh97913132018-01-11 00:04:00 +00001252 f = fopen(zTempFile, bBin ? "wb" : "w");
1253 if( f==0 ){
1254 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1255 goto edit_func_end;
1256 }
1257 sz = sqlite3_value_bytes(argv[0]);
1258 if( bBin ){
dan4d02b5f2019-07-17 07:23:06 +00001259 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f);
drh97913132018-01-11 00:04:00 +00001260 }else{
drhf018fd52018-08-06 02:08:53 +00001261 const char *z = (const char*)sqlite3_value_text(argv[0]);
1262 /* Remember whether or not the value originally contained \r\n */
1263 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
dan4d02b5f2019-07-17 07:23:06 +00001264 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f);
drh97913132018-01-11 00:04:00 +00001265 }
1266 fclose(f);
1267 f = 0;
1268 if( x!=sz ){
1269 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1270 goto edit_func_end;
1271 }
1272 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1273 if( zCmd==0 ){
1274 sqlite3_result_error_nomem(context);
1275 goto edit_func_end;
1276 }
1277 rc = system(zCmd);
1278 sqlite3_free(zCmd);
1279 if( rc ){
1280 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1281 goto edit_func_end;
1282 }
drhf018fd52018-08-06 02:08:53 +00001283 f = fopen(zTempFile, "rb");
drh97913132018-01-11 00:04:00 +00001284 if( f==0 ){
1285 sqlite3_result_error(context,
1286 "edit() cannot reopen temp file after edit", -1);
1287 goto edit_func_end;
1288 }
1289 fseek(f, 0, SEEK_END);
1290 sz = ftell(f);
1291 rewind(f);
drhee37f8b2019-08-23 23:05:32 +00001292 p = sqlite3_malloc64( sz+1 );
drh97913132018-01-11 00:04:00 +00001293 if( p==0 ){
1294 sqlite3_result_error_nomem(context);
1295 goto edit_func_end;
1296 }
dan4d02b5f2019-07-17 07:23:06 +00001297 x = fread(p, 1, (size_t)sz, f);
drh97913132018-01-11 00:04:00 +00001298 fclose(f);
1299 f = 0;
1300 if( x!=sz ){
1301 sqlite3_result_error(context, "could not read back the whole file", -1);
1302 goto edit_func_end;
1303 }
1304 if( bBin ){
mistachkinb71aa092018-01-23 00:05:18 +00001305 sqlite3_result_blob64(context, p, sz, sqlite3_free);
drh97913132018-01-11 00:04:00 +00001306 }else{
dan60bdcf52018-10-03 11:13:30 +00001307 sqlite3_int64 i, j;
drhf018fd52018-08-06 02:08:53 +00001308 if( hasCRNL ){
1309 /* If the original contains \r\n then do no conversions back to \n */
1310 j = sz;
1311 }else{
1312 /* If the file did not originally contain \r\n then convert any new
1313 ** \r\n back into \n */
1314 for(i=j=0; i<sz; i++){
1315 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1316 p[j++] = p[i];
1317 }
1318 sz = j;
1319 p[sz] = 0;
1320 }
mistachkinb71aa092018-01-23 00:05:18 +00001321 sqlite3_result_text64(context, (const char*)p, sz,
1322 sqlite3_free, SQLITE_UTF8);
drh97913132018-01-11 00:04:00 +00001323 }
1324 p = 0;
1325
1326edit_func_end:
1327 if( f ) fclose(f);
1328 unlink(zTempFile);
1329 sqlite3_free(zTempFile);
1330 sqlite3_free(p);
1331}
drh04a28c32018-01-31 01:38:44 +00001332#endif /* SQLITE_NOHAVE_SYSTEM */
drh97913132018-01-11 00:04:00 +00001333
1334/*
drh3c484e82018-01-10 22:27:21 +00001335** Save or restore the current output mode
1336*/
1337static void outputModePush(ShellState *p){
1338 p->modePrior = p->mode;
1339 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1340 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1341}
1342static void outputModePop(ShellState *p){
1343 p->mode = p->modePrior;
1344 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1345 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1346}
1347
1348/*
drh2ce15c32017-07-11 13:34:40 +00001349** Output the given string as a hex-encoded blob (eg. X'1234' )
1350*/
1351static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1352 int i;
1353 char *zBlob = (char *)pBlob;
1354 raw_printf(out,"X'");
1355 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1356 raw_printf(out,"'");
1357}
1358
1359/*
1360** Find a string that is not found anywhere in z[]. Return a pointer
1361** to that string.
1362**
1363** Try to use zA and zB first. If both of those are already found in z[]
1364** then make up some string and store it in the buffer zBuf.
1365*/
1366static const char *unused_string(
1367 const char *z, /* Result must not appear anywhere in z */
1368 const char *zA, const char *zB, /* Try these first */
1369 char *zBuf /* Space to store a generated string */
1370){
1371 unsigned i = 0;
1372 if( strstr(z, zA)==0 ) return zA;
1373 if( strstr(z, zB)==0 ) return zB;
1374 do{
1375 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1376 }while( strstr(z,zBuf)!=0 );
1377 return zBuf;
1378}
1379
1380/*
1381** Output the given string as a quoted string using SQL quoting conventions.
1382**
1383** See also: output_quoted_escaped_string()
1384*/
1385static void output_quoted_string(FILE *out, const char *z){
1386 int i;
1387 char c;
1388 setBinaryMode(out, 1);
1389 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1390 if( c==0 ){
1391 utf8_printf(out,"'%s'",z);
1392 }else{
1393 raw_printf(out, "'");
1394 while( *z ){
1395 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1396 if( c=='\'' ) i++;
1397 if( i ){
1398 utf8_printf(out, "%.*s", i, z);
1399 z += i;
1400 }
1401 if( c=='\'' ){
1402 raw_printf(out, "'");
1403 continue;
1404 }
1405 if( c==0 ){
1406 break;
1407 }
1408 z++;
1409 }
1410 raw_printf(out, "'");
1411 }
1412 setTextMode(out, 1);
1413}
1414
1415/*
1416** Output the given string as a quoted string using SQL quoting conventions.
1417** Additionallly , escape the "\n" and "\r" characters so that they do not
1418** get corrupted by end-of-line translation facilities in some operating
1419** systems.
1420**
1421** This is like output_quoted_string() but with the addition of the \r\n
1422** escape mechanism.
1423*/
1424static void output_quoted_escaped_string(FILE *out, const char *z){
1425 int i;
1426 char c;
1427 setBinaryMode(out, 1);
1428 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1429 if( c==0 ){
1430 utf8_printf(out,"'%s'",z);
1431 }else{
1432 const char *zNL = 0;
1433 const char *zCR = 0;
1434 int nNL = 0;
1435 int nCR = 0;
1436 char zBuf1[20], zBuf2[20];
1437 for(i=0; z[i]; i++){
1438 if( z[i]=='\n' ) nNL++;
1439 if( z[i]=='\r' ) nCR++;
1440 }
1441 if( nNL ){
1442 raw_printf(out, "replace(");
1443 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1444 }
1445 if( nCR ){
1446 raw_printf(out, "replace(");
1447 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1448 }
1449 raw_printf(out, "'");
1450 while( *z ){
1451 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1452 if( c=='\'' ) i++;
1453 if( i ){
1454 utf8_printf(out, "%.*s", i, z);
1455 z += i;
1456 }
1457 if( c=='\'' ){
1458 raw_printf(out, "'");
1459 continue;
1460 }
1461 if( c==0 ){
1462 break;
1463 }
1464 z++;
1465 if( c=='\n' ){
1466 raw_printf(out, "%s", zNL);
1467 continue;
1468 }
1469 raw_printf(out, "%s", zCR);
1470 }
1471 raw_printf(out, "'");
1472 if( nCR ){
1473 raw_printf(out, ",'%s',char(13))", zCR);
1474 }
1475 if( nNL ){
1476 raw_printf(out, ",'%s',char(10))", zNL);
1477 }
1478 }
1479 setTextMode(out, 1);
1480}
1481
1482/*
1483** Output the given string as a quoted according to C or TCL quoting rules.
1484*/
1485static void output_c_string(FILE *out, const char *z){
1486 unsigned int c;
1487 fputc('"', out);
1488 while( (c = *(z++))!=0 ){
1489 if( c=='\\' ){
1490 fputc(c, out);
1491 fputc(c, out);
1492 }else if( c=='"' ){
1493 fputc('\\', out);
1494 fputc('"', out);
1495 }else if( c=='\t' ){
1496 fputc('\\', out);
1497 fputc('t', out);
1498 }else if( c=='\n' ){
1499 fputc('\\', out);
1500 fputc('n', out);
1501 }else if( c=='\r' ){
1502 fputc('\\', out);
1503 fputc('r', out);
1504 }else if( !isprint(c&0xff) ){
1505 raw_printf(out, "\\%03o", c&0xff);
1506 }else{
1507 fputc(c, out);
1508 }
1509 }
1510 fputc('"', out);
1511}
1512
1513/*
1514** Output the given string with characters that are special to
1515** HTML escaped.
1516*/
1517static void output_html_string(FILE *out, const char *z){
1518 int i;
1519 if( z==0 ) z = "";
1520 while( *z ){
1521 for(i=0; z[i]
1522 && z[i]!='<'
1523 && z[i]!='&'
1524 && z[i]!='>'
1525 && z[i]!='\"'
1526 && z[i]!='\'';
1527 i++){}
1528 if( i>0 ){
1529 utf8_printf(out,"%.*s",i,z);
1530 }
1531 if( z[i]=='<' ){
1532 raw_printf(out,"&lt;");
1533 }else if( z[i]=='&' ){
1534 raw_printf(out,"&amp;");
1535 }else if( z[i]=='>' ){
1536 raw_printf(out,"&gt;");
1537 }else if( z[i]=='\"' ){
1538 raw_printf(out,"&quot;");
1539 }else if( z[i]=='\'' ){
1540 raw_printf(out,"&#39;");
1541 }else{
1542 break;
1543 }
1544 z += i + 1;
1545 }
1546}
1547
1548/*
1549** If a field contains any character identified by a 1 in the following
1550** array, then the string must be quoted for CSV.
1551*/
1552static const char needCsvQuote[] = {
1553 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1554 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1555 1, 0, 1, 0, 0, 0, 0, 1, 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, 0,
1560 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1569};
1570
1571/*
1572** Output a single term of CSV. Actually, p->colSeparator is used for
1573** the separator, which may or may not be a comma. p->nullValue is
1574** the null value. Strings are quoted if necessary. The separator
1575** is only issued if bSep is true.
1576*/
1577static void output_csv(ShellState *p, const char *z, int bSep){
1578 FILE *out = p->out;
1579 if( z==0 ){
1580 utf8_printf(out,"%s",p->nullValue);
1581 }else{
1582 int i;
1583 int nSep = strlen30(p->colSeparator);
1584 for(i=0; z[i]; i++){
1585 if( needCsvQuote[((unsigned char*)z)[i]]
1586 || (z[i]==p->colSeparator[0] &&
1587 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1588 i = 0;
1589 break;
1590 }
1591 }
1592 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001593 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1594 utf8_printf(out, "%s", zQuoted);
1595 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001596 }else{
1597 utf8_printf(out, "%s", z);
1598 }
1599 }
1600 if( bSep ){
1601 utf8_printf(p->out, "%s", p->colSeparator);
1602 }
1603}
1604
drh2ce15c32017-07-11 13:34:40 +00001605/*
1606** This routine runs when the user presses Ctrl-C
1607*/
1608static void interrupt_handler(int NotUsed){
1609 UNUSED_PARAMETER(NotUsed);
1610 seenInterrupt++;
1611 if( seenInterrupt>2 ) exit(1);
1612 if( globalDb ) sqlite3_interrupt(globalDb);
1613}
mistachkinb4bab902017-10-27 17:09:44 +00001614
1615#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1616/*
1617** This routine runs for console events (e.g. Ctrl-C) on Win32
1618*/
1619static BOOL WINAPI ConsoleCtrlHandler(
1620 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1621){
1622 if( dwCtrlType==CTRL_C_EVENT ){
1623 interrupt_handler(0);
1624 return TRUE;
1625 }
1626 return FALSE;
1627}
drh2ce15c32017-07-11 13:34:40 +00001628#endif
1629
1630#ifndef SQLITE_OMIT_AUTHORIZATION
1631/*
1632** When the ".auth ON" is set, the following authorizer callback is
1633** invoked. It always returns SQLITE_OK.
1634*/
1635static int shellAuth(
1636 void *pClientData,
1637 int op,
1638 const char *zA1,
1639 const char *zA2,
1640 const char *zA3,
1641 const char *zA4
1642){
1643 ShellState *p = (ShellState*)pClientData;
1644 static const char *azAction[] = { 0,
1645 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1646 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1647 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1648 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1649 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1650 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1651 "PRAGMA", "READ", "SELECT",
1652 "TRANSACTION", "UPDATE", "ATTACH",
1653 "DETACH", "ALTER_TABLE", "REINDEX",
1654 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1655 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1656 };
1657 int i;
1658 const char *az[4];
1659 az[0] = zA1;
1660 az[1] = zA2;
1661 az[2] = zA3;
1662 az[3] = zA4;
1663 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1664 for(i=0; i<4; i++){
1665 raw_printf(p->out, " ");
1666 if( az[i] ){
1667 output_c_string(p->out, az[i]);
1668 }else{
1669 raw_printf(p->out, "NULL");
1670 }
1671 }
1672 raw_printf(p->out, "\n");
1673 return SQLITE_OK;
1674}
1675#endif
1676
1677/*
1678** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1679**
1680** This routine converts some CREATE TABLE statements for shadow tables
1681** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1682*/
1683static void printSchemaLine(FILE *out, const char *z, const char *zTail){
drh0a0536a2019-05-09 18:13:30 +00001684 if( z==0 ) return;
1685 if( zTail==0 ) return;
drh2ce15c32017-07-11 13:34:40 +00001686 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1687 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1688 }else{
1689 utf8_printf(out, "%s%s", z, zTail);
1690 }
1691}
1692static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1693 char c = z[n];
1694 z[n] = 0;
1695 printSchemaLine(out, z, zTail);
1696 z[n] = c;
1697}
1698
1699/*
drh11be81d2018-01-06 15:46:20 +00001700** Return true if string z[] has nothing but whitespace and comments to the
1701** end of the first line.
1702*/
1703static int wsToEol(const char *z){
1704 int i;
1705 for(i=0; z[i]; i++){
1706 if( z[i]=='\n' ) return 1;
1707 if( IsSpace(z[i]) ) continue;
1708 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1709 return 0;
1710 }
1711 return 1;
1712}
drh4b5345c2018-04-24 13:07:40 +00001713
1714/*
1715** Add a new entry to the EXPLAIN QUERY PLAN data
1716*/
drhe2ca99c2018-05-02 00:33:43 +00001717static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
drh4b5345c2018-04-24 13:07:40 +00001718 EQPGraphRow *pNew;
1719 int nText = strlen30(zText);
drhe2ca99c2018-05-02 00:33:43 +00001720 if( p->autoEQPtest ){
1721 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1722 }
drh4b5345c2018-04-24 13:07:40 +00001723 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1724 if( pNew==0 ) shell_out_of_memory();
drhe2ca99c2018-05-02 00:33:43 +00001725 pNew->iEqpId = iEqpId;
1726 pNew->iParentId = p2;
drh4b5345c2018-04-24 13:07:40 +00001727 memcpy(pNew->zText, zText, nText+1);
1728 pNew->pNext = 0;
1729 if( p->sGraph.pLast ){
1730 p->sGraph.pLast->pNext = pNew;
1731 }else{
1732 p->sGraph.pRow = pNew;
1733 }
1734 p->sGraph.pLast = pNew;
1735}
1736
1737/*
1738** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1739** in p->sGraph.
1740*/
1741static void eqp_reset(ShellState *p){
1742 EQPGraphRow *pRow, *pNext;
1743 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1744 pNext = pRow->pNext;
1745 sqlite3_free(pRow);
1746 }
1747 memset(&p->sGraph, 0, sizeof(p->sGraph));
1748}
1749
drhe2ca99c2018-05-02 00:33:43 +00001750/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
drh4b5345c2018-04-24 13:07:40 +00001751** pOld, or return the first such line if pOld is NULL
1752*/
drhe2ca99c2018-05-02 00:33:43 +00001753static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
drh4b5345c2018-04-24 13:07:40 +00001754 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
drhe2ca99c2018-05-02 00:33:43 +00001755 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
drh4b5345c2018-04-24 13:07:40 +00001756 return pRow;
1757}
1758
drhe2ca99c2018-05-02 00:33:43 +00001759/* Render a single level of the graph that has iEqpId as its parent. Called
drh4b5345c2018-04-24 13:07:40 +00001760** recursively to render sublevels.
1761*/
drhe2ca99c2018-05-02 00:33:43 +00001762static void eqp_render_level(ShellState *p, int iEqpId){
drh4b5345c2018-04-24 13:07:40 +00001763 EQPGraphRow *pRow, *pNext;
drh4b5345c2018-04-24 13:07:40 +00001764 int n = strlen30(p->sGraph.zPrefix);
1765 char *z;
drhe2ca99c2018-05-02 00:33:43 +00001766 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1767 pNext = eqp_next_row(p, iEqpId, pRow);
drh4b5345c2018-04-24 13:07:40 +00001768 z = pRow->zText;
drhe2754c12019-08-26 12:50:01 +00001769 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix,
1770 pNext ? "|--" : "`--", z);
drhe2188f02018-05-07 11:37:34 +00001771 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
drh4b5345c2018-04-24 13:07:40 +00001772 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
drhe2ca99c2018-05-02 00:33:43 +00001773 eqp_render_level(p, pRow->iEqpId);
drh4b5345c2018-04-24 13:07:40 +00001774 p->sGraph.zPrefix[n] = 0;
1775 }
1776 }
1777}
1778
1779/*
1780** Display and reset the EXPLAIN QUERY PLAN data
1781*/
1782static void eqp_render(ShellState *p){
1783 EQPGraphRow *pRow = p->sGraph.pRow;
1784 if( pRow ){
1785 if( pRow->zText[0]=='-' ){
1786 if( pRow->pNext==0 ){
1787 eqp_reset(p);
1788 return;
1789 }
1790 utf8_printf(p->out, "%s\n", pRow->zText+3);
1791 p->sGraph.pRow = pRow->pNext;
1792 sqlite3_free(pRow);
1793 }else{
1794 utf8_printf(p->out, "QUERY PLAN\n");
1795 }
1796 p->sGraph.zPrefix[0] = 0;
1797 eqp_render_level(p, 0);
1798 eqp_reset(p);
1799 }
1800}
drh11be81d2018-01-06 15:46:20 +00001801
drh569b1d92019-02-05 20:51:41 +00001802#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh11be81d2018-01-06 15:46:20 +00001803/*
drh3f83f592019-02-04 14:53:18 +00001804** Progress handler callback.
1805*/
1806static int progress_handler(void *pClientData) {
1807 ShellState *p = (ShellState*)pClientData;
1808 p->nProgress++;
1809 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1810 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
drhfc4eeef2019-02-05 19:48:46 +00001811 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
1812 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
drh3f83f592019-02-04 14:53:18 +00001813 return 1;
1814 }
drhfc4eeef2019-02-05 19:48:46 +00001815 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
drh3f83f592019-02-04 14:53:18 +00001816 raw_printf(p->out, "Progress %u\n", p->nProgress);
1817 }
1818 return 0;
1819}
drh569b1d92019-02-05 20:51:41 +00001820#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00001821
1822/*
drh2ce15c32017-07-11 13:34:40 +00001823** This is the callback routine that the shell
1824** invokes for each row of a query result.
1825*/
1826static int shell_callback(
1827 void *pArg,
1828 int nArg, /* Number of result columns */
1829 char **azArg, /* Text of each result column */
1830 char **azCol, /* Column names */
1831 int *aiType /* Column types */
1832){
1833 int i;
1834 ShellState *p = (ShellState*)pArg;
1835
drhb3c45232017-08-28 14:33:27 +00001836 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001837 switch( p->cMode ){
1838 case MODE_Line: {
1839 int w = 5;
1840 if( azArg==0 ) break;
1841 for(i=0; i<nArg; i++){
1842 int len = strlen30(azCol[i] ? azCol[i] : "");
1843 if( len>w ) w = len;
1844 }
1845 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1846 for(i=0; i<nArg; i++){
1847 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1848 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1849 }
1850 break;
1851 }
1852 case MODE_Explain:
1853 case MODE_Column: {
1854 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1855 const int *colWidth;
1856 int showHdr;
1857 char *rowSep;
1858 if( p->cMode==MODE_Column ){
1859 colWidth = p->colWidth;
1860 showHdr = p->showHeader;
1861 rowSep = p->rowSeparator;
1862 }else{
1863 colWidth = aExplainWidths;
1864 showHdr = 1;
1865 rowSep = SEP_Row;
1866 }
1867 if( p->cnt++==0 ){
1868 for(i=0; i<nArg; i++){
1869 int w, n;
1870 if( i<ArraySize(p->colWidth) ){
1871 w = colWidth[i];
1872 }else{
1873 w = 0;
1874 }
1875 if( w==0 ){
1876 w = strlenChar(azCol[i] ? azCol[i] : "");
1877 if( w<10 ) w = 10;
1878 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1879 if( w<n ) w = n;
1880 }
1881 if( i<ArraySize(p->actualWidth) ){
1882 p->actualWidth[i] = w;
1883 }
1884 if( showHdr ){
1885 utf8_width_print(p->out, w, azCol[i]);
1886 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1887 }
1888 }
1889 if( showHdr ){
1890 for(i=0; i<nArg; i++){
1891 int w;
1892 if( i<ArraySize(p->actualWidth) ){
1893 w = p->actualWidth[i];
1894 if( w<0 ) w = -w;
1895 }else{
1896 w = 10;
1897 }
1898 utf8_printf(p->out,"%-*.*s%s",w,w,
1899 "----------------------------------------------------------"
1900 "----------------------------------------------------------",
1901 i==nArg-1 ? rowSep : " ");
1902 }
1903 }
1904 }
1905 if( azArg==0 ) break;
1906 for(i=0; i<nArg; i++){
1907 int w;
1908 if( i<ArraySize(p->actualWidth) ){
1909 w = p->actualWidth[i];
1910 }else{
1911 w = 10;
1912 }
1913 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1914 w = strlenChar(azArg[i]);
1915 }
1916 if( i==1 && p->aiIndent && p->pStmt ){
1917 if( p->iIndent<p->nIndent ){
1918 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1919 }
1920 p->iIndent++;
1921 }
1922 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1923 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1924 }
1925 break;
1926 }
1927 case MODE_Semi: { /* .schema and .fullschema output */
1928 printSchemaLine(p->out, azArg[0], ";\n");
1929 break;
1930 }
1931 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1932 char *z;
1933 int j;
1934 int nParen = 0;
1935 char cEnd = 0;
1936 char c;
1937 int nLine = 0;
1938 assert( nArg==1 );
1939 if( azArg[0]==0 ) break;
1940 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1941 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1942 ){
1943 utf8_printf(p->out, "%s;\n", azArg[0]);
1944 break;
1945 }
1946 z = sqlite3_mprintf("%s", azArg[0]);
1947 j = 0;
1948 for(i=0; IsSpace(z[i]); i++){}
1949 for(; (c = z[i])!=0; i++){
1950 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001951 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001952 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1953 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1954 j--;
1955 }
1956 z[j++] = c;
1957 }
1958 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1959 z[j] = 0;
1960 if( strlen30(z)>=79 ){
drhe2754c12019-08-26 12:50:01 +00001961 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001962 if( c==cEnd ){
1963 cEnd = 0;
1964 }else if( c=='"' || c=='\'' || c=='`' ){
1965 cEnd = c;
1966 }else if( c=='[' ){
1967 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001968 }else if( c=='-' && z[i+1]=='-' ){
1969 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001970 }else if( c=='(' ){
1971 nParen++;
1972 }else if( c==')' ){
1973 nParen--;
1974 if( nLine>0 && nParen==0 && j>0 ){
1975 printSchemaLineN(p->out, z, j, "\n");
1976 j = 0;
1977 }
1978 }
1979 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001980 if( nParen==1 && cEnd==0
1981 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1982 ){
drh2ce15c32017-07-11 13:34:40 +00001983 if( c=='\n' ) j--;
1984 printSchemaLineN(p->out, z, j, "\n ");
1985 j = 0;
1986 nLine++;
1987 while( IsSpace(z[i+1]) ){ i++; }
1988 }
1989 }
1990 z[j] = 0;
1991 }
1992 printSchemaLine(p->out, z, ";\n");
1993 sqlite3_free(z);
1994 break;
1995 }
1996 case MODE_List: {
1997 if( p->cnt++==0 && p->showHeader ){
1998 for(i=0; i<nArg; i++){
1999 utf8_printf(p->out,"%s%s",azCol[i],
2000 i==nArg-1 ? p->rowSeparator : p->colSeparator);
2001 }
2002 }
2003 if( azArg==0 ) break;
2004 for(i=0; i<nArg; i++){
2005 char *z = azArg[i];
2006 if( z==0 ) z = p->nullValue;
2007 utf8_printf(p->out, "%s", z);
2008 if( i<nArg-1 ){
2009 utf8_printf(p->out, "%s", p->colSeparator);
2010 }else{
2011 utf8_printf(p->out, "%s", p->rowSeparator);
2012 }
2013 }
2014 break;
2015 }
2016 case MODE_Html: {
2017 if( p->cnt++==0 && p->showHeader ){
2018 raw_printf(p->out,"<TR>");
2019 for(i=0; i<nArg; i++){
2020 raw_printf(p->out,"<TH>");
2021 output_html_string(p->out, azCol[i]);
2022 raw_printf(p->out,"</TH>\n");
2023 }
2024 raw_printf(p->out,"</TR>\n");
2025 }
2026 if( azArg==0 ) break;
2027 raw_printf(p->out,"<TR>");
2028 for(i=0; i<nArg; i++){
2029 raw_printf(p->out,"<TD>");
2030 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2031 raw_printf(p->out,"</TD>\n");
2032 }
2033 raw_printf(p->out,"</TR>\n");
2034 break;
2035 }
2036 case MODE_Tcl: {
2037 if( p->cnt++==0 && p->showHeader ){
2038 for(i=0; i<nArg; i++){
2039 output_c_string(p->out,azCol[i] ? azCol[i] : "");
2040 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2041 }
2042 utf8_printf(p->out, "%s", p->rowSeparator);
2043 }
2044 if( azArg==0 ) break;
2045 for(i=0; i<nArg; i++){
2046 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2047 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2048 }
2049 utf8_printf(p->out, "%s", p->rowSeparator);
2050 break;
2051 }
2052 case MODE_Csv: {
2053 setBinaryMode(p->out, 1);
2054 if( p->cnt++==0 && p->showHeader ){
2055 for(i=0; i<nArg; i++){
2056 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2057 }
2058 utf8_printf(p->out, "%s", p->rowSeparator);
2059 }
2060 if( nArg>0 ){
2061 for(i=0; i<nArg; i++){
2062 output_csv(p, azArg[i], i<nArg-1);
2063 }
2064 utf8_printf(p->out, "%s", p->rowSeparator);
2065 }
2066 setTextMode(p->out, 1);
2067 break;
2068 }
2069 case MODE_Insert: {
2070 if( azArg==0 ) break;
2071 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2072 if( p->showHeader ){
2073 raw_printf(p->out,"(");
2074 for(i=0; i<nArg; i++){
2075 if( i>0 ) raw_printf(p->out, ",");
2076 if( quoteChar(azCol[i]) ){
2077 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2078 utf8_printf(p->out, "%s", z);
2079 sqlite3_free(z);
2080 }else{
2081 raw_printf(p->out, "%s", azCol[i]);
2082 }
2083 }
2084 raw_printf(p->out,")");
2085 }
2086 p->cnt++;
2087 for(i=0; i<nArg; i++){
2088 raw_printf(p->out, i>0 ? "," : " VALUES(");
2089 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2090 utf8_printf(p->out,"NULL");
2091 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2092 if( ShellHasFlag(p, SHFLG_Newlines) ){
2093 output_quoted_string(p->out, azArg[i]);
2094 }else{
2095 output_quoted_escaped_string(p->out, azArg[i]);
2096 }
2097 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2098 utf8_printf(p->out,"%s", azArg[i]);
2099 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2100 char z[50];
2101 double r = sqlite3_column_double(p->pStmt, i);
drh2f1f8802018-06-13 17:19:20 +00002102 sqlite3_uint64 ur;
2103 memcpy(&ur,&r,sizeof(r));
2104 if( ur==0x7ff0000000000000LL ){
2105 raw_printf(p->out, "1e999");
2106 }else if( ur==0xfff0000000000000LL ){
2107 raw_printf(p->out, "-1e999");
2108 }else{
2109 sqlite3_snprintf(50,z,"%!.20g", r);
2110 raw_printf(p->out, "%s", z);
2111 }
drh2ce15c32017-07-11 13:34:40 +00002112 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2113 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2114 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2115 output_hex_blob(p->out, pBlob, nBlob);
2116 }else if( isNumber(azArg[i], 0) ){
2117 utf8_printf(p->out,"%s", azArg[i]);
2118 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2119 output_quoted_string(p->out, azArg[i]);
2120 }else{
2121 output_quoted_escaped_string(p->out, azArg[i]);
2122 }
2123 }
2124 raw_printf(p->out,");\n");
2125 break;
2126 }
2127 case MODE_Quote: {
2128 if( azArg==0 ) break;
2129 if( p->cnt==0 && p->showHeader ){
2130 for(i=0; i<nArg; i++){
2131 if( i>0 ) raw_printf(p->out, ",");
2132 output_quoted_string(p->out, azCol[i]);
2133 }
2134 raw_printf(p->out,"\n");
2135 }
2136 p->cnt++;
2137 for(i=0; i<nArg; i++){
2138 if( i>0 ) raw_printf(p->out, ",");
2139 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2140 utf8_printf(p->out,"NULL");
2141 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2142 output_quoted_string(p->out, azArg[i]);
2143 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2144 utf8_printf(p->out,"%s", azArg[i]);
2145 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2146 char z[50];
2147 double r = sqlite3_column_double(p->pStmt, i);
2148 sqlite3_snprintf(50,z,"%!.20g", r);
2149 raw_printf(p->out, "%s", z);
2150 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2151 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2152 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2153 output_hex_blob(p->out, pBlob, nBlob);
2154 }else if( isNumber(azArg[i], 0) ){
2155 utf8_printf(p->out,"%s", azArg[i]);
2156 }else{
2157 output_quoted_string(p->out, azArg[i]);
2158 }
2159 }
2160 raw_printf(p->out,"\n");
2161 break;
2162 }
2163 case MODE_Ascii: {
2164 if( p->cnt++==0 && p->showHeader ){
2165 for(i=0; i<nArg; i++){
2166 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2167 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2168 }
2169 utf8_printf(p->out, "%s", p->rowSeparator);
2170 }
2171 if( azArg==0 ) break;
2172 for(i=0; i<nArg; i++){
2173 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2174 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2175 }
2176 utf8_printf(p->out, "%s", p->rowSeparator);
2177 break;
2178 }
drh4b5345c2018-04-24 13:07:40 +00002179 case MODE_EQP: {
drhe2ca99c2018-05-02 00:33:43 +00002180 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
drh4b5345c2018-04-24 13:07:40 +00002181 break;
2182 }
drh2ce15c32017-07-11 13:34:40 +00002183 }
2184 return 0;
2185}
2186
2187/*
2188** This is the callback routine that the SQLite library
2189** invokes for each row of a query result.
2190*/
2191static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2192 /* since we don't have type info, call the shell_callback with a NULL value */
2193 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2194}
2195
2196/*
2197** This is the callback routine from sqlite3_exec() that appends all
2198** output onto the end of a ShellText object.
2199*/
2200static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2201 ShellText *p = (ShellText*)pArg;
2202 int i;
2203 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00002204 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002205 if( p->n ) appendText(p, "|", 0);
2206 for(i=0; i<nArg; i++){
2207 if( i ) appendText(p, ",", 0);
2208 if( azArg[i] ) appendText(p, azArg[i], 0);
2209 }
2210 return 0;
2211}
2212
2213/*
2214** Generate an appropriate SELFTEST table in the main database.
2215*/
2216static void createSelftestTable(ShellState *p){
2217 char *zErrMsg = 0;
2218 sqlite3_exec(p->db,
2219 "SAVEPOINT selftest_init;\n"
2220 "CREATE TABLE IF NOT EXISTS selftest(\n"
2221 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2222 " op TEXT,\n" /* Operator: memo run */
2223 " cmd TEXT,\n" /* Command text */
2224 " ans TEXT\n" /* Desired answer */
2225 ");"
2226 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2227 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2228 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2229 " 'memo','Tests generated by --init');\n"
2230 "INSERT INTO [_shell$self]\n"
2231 " SELECT 'run',\n"
2232 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2233 "FROM sqlite_master ORDER BY 2'',224))',\n"
2234 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2235 "FROM sqlite_master ORDER BY 2',224));\n"
2236 "INSERT INTO [_shell$self]\n"
2237 " SELECT 'run',"
2238 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2239 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2240 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2241 " FROM (\n"
2242 " SELECT name FROM sqlite_master\n"
2243 " WHERE type='table'\n"
2244 " AND name<>'selftest'\n"
2245 " AND coalesce(rootpage,0)>0\n"
2246 " )\n"
2247 " ORDER BY name;\n"
2248 "INSERT INTO [_shell$self]\n"
2249 " VALUES('run','PRAGMA integrity_check','ok');\n"
2250 "INSERT INTO selftest(tno,op,cmd,ans)"
2251 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2252 "DROP TABLE [_shell$self];"
2253 ,0,0,&zErrMsg);
2254 if( zErrMsg ){
2255 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2256 sqlite3_free(zErrMsg);
2257 }
2258 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2259}
2260
2261
2262/*
2263** Set the destination table field of the ShellState structure to
2264** the name of the table given. Escape any quote characters in the
2265** table name.
2266*/
2267static void set_table_name(ShellState *p, const char *zName){
2268 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00002269 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00002270 char *z;
2271
2272 if( p->zDestTable ){
2273 free(p->zDestTable);
2274 p->zDestTable = 0;
2275 }
2276 if( zName==0 ) return;
2277 cQuote = quoteChar(zName);
2278 n = strlen30(zName);
2279 if( cQuote ) n += n+2;
2280 z = p->zDestTable = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00002281 if( z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002282 n = 0;
2283 if( cQuote ) z[n++] = cQuote;
2284 for(i=0; zName[i]; i++){
2285 z[n++] = zName[i];
2286 if( zName[i]==cQuote ) z[n++] = cQuote;
2287 }
2288 if( cQuote ) z[n++] = cQuote;
2289 z[n] = 0;
2290}
2291
2292
2293/*
2294** Execute a query statement that will generate SQL output. Print
2295** the result columns, comma-separated, on a line and then add a
2296** semicolon terminator to the end of that line.
2297**
2298** If the number of columns is 1 and that column contains text "--"
2299** then write the semicolon on a separate line. That way, if a
2300** "--" comment occurs at the end of the statement, the comment
2301** won't consume the semicolon terminator.
2302*/
2303static int run_table_dump_query(
2304 ShellState *p, /* Query context */
2305 const char *zSelect, /* SELECT statement to extract content */
2306 const char *zFirstRow /* Print before first row, if not NULL */
2307){
2308 sqlite3_stmt *pSelect;
2309 int rc;
2310 int nResult;
2311 int i;
2312 const char *z;
2313 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2314 if( rc!=SQLITE_OK || !pSelect ){
2315 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2316 sqlite3_errmsg(p->db));
2317 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2318 return rc;
2319 }
2320 rc = sqlite3_step(pSelect);
2321 nResult = sqlite3_column_count(pSelect);
2322 while( rc==SQLITE_ROW ){
2323 if( zFirstRow ){
2324 utf8_printf(p->out, "%s", zFirstRow);
2325 zFirstRow = 0;
2326 }
2327 z = (const char*)sqlite3_column_text(pSelect, 0);
2328 utf8_printf(p->out, "%s", z);
2329 for(i=1; i<nResult; i++){
2330 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2331 }
2332 if( z==0 ) z = "";
2333 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2334 if( z[0] ){
2335 raw_printf(p->out, "\n;\n");
2336 }else{
2337 raw_printf(p->out, ";\n");
2338 }
2339 rc = sqlite3_step(pSelect);
2340 }
2341 rc = sqlite3_finalize(pSelect);
2342 if( rc!=SQLITE_OK ){
2343 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2344 sqlite3_errmsg(p->db));
2345 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2346 }
2347 return rc;
2348}
2349
2350/*
2351** Allocate space and save off current error string.
2352*/
2353static char *save_err_msg(
2354 sqlite3 *db /* Database to query */
2355){
2356 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2357 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2358 if( zErrMsg ){
2359 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2360 }
2361 return zErrMsg;
2362}
2363
2364#ifdef __linux__
2365/*
2366** Attempt to display I/O stats on Linux using /proc/PID/io
2367*/
2368static void displayLinuxIoStats(FILE *out){
2369 FILE *in;
2370 char z[200];
2371 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2372 in = fopen(z, "rb");
2373 if( in==0 ) return;
2374 while( fgets(z, sizeof(z), in)!=0 ){
2375 static const struct {
2376 const char *zPattern;
2377 const char *zDesc;
2378 } aTrans[] = {
2379 { "rchar: ", "Bytes received by read():" },
2380 { "wchar: ", "Bytes sent to write():" },
2381 { "syscr: ", "Read() system calls:" },
2382 { "syscw: ", "Write() system calls:" },
2383 { "read_bytes: ", "Bytes read from storage:" },
2384 { "write_bytes: ", "Bytes written to storage:" },
2385 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2386 };
2387 int i;
2388 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00002389 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00002390 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2391 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2392 break;
2393 }
2394 }
2395 }
2396 fclose(in);
2397}
2398#endif
2399
2400/*
2401** Display a single line of status using 64-bit values.
2402*/
2403static void displayStatLine(
2404 ShellState *p, /* The shell context */
2405 char *zLabel, /* Label for this one line */
2406 char *zFormat, /* Format for the result */
2407 int iStatusCtrl, /* Which status to display */
2408 int bReset /* True to reset the stats */
2409){
2410 sqlite3_int64 iCur = -1;
2411 sqlite3_int64 iHiwtr = -1;
2412 int i, nPercent;
2413 char zLine[200];
2414 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2415 for(i=0, nPercent=0; zFormat[i]; i++){
2416 if( zFormat[i]=='%' ) nPercent++;
2417 }
2418 if( nPercent>1 ){
2419 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2420 }else{
2421 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2422 }
2423 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2424}
2425
2426/*
2427** Display memory stats.
2428*/
2429static int display_stats(
2430 sqlite3 *db, /* Database to query */
2431 ShellState *pArg, /* Pointer to ShellState */
2432 int bReset /* True to reset the stats */
2433){
2434 int iCur;
2435 int iHiwtr;
drh393344f2018-03-09 16:37:05 +00002436 FILE *out;
2437 if( pArg==0 || pArg->out==0 ) return 0;
2438 out = pArg->out;
drh2ce15c32017-07-11 13:34:40 +00002439
drh393344f2018-03-09 16:37:05 +00002440 if( pArg->pStmt && (pArg->statsOn & 2) ){
2441 int nCol, i, x;
2442 sqlite3_stmt *pStmt = pArg->pStmt;
2443 char z[100];
2444 nCol = sqlite3_column_count(pStmt);
2445 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2446 for(i=0; i<nCol; i++){
2447 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2448 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002449#ifndef SQLITE_OMIT_DECLTYPE
drh393344f2018-03-09 16:37:05 +00002450 sqlite3_snprintf(30, z+x, "declared type:");
2451 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
drh929cce82018-03-17 16:26:36 +00002452#endif
2453#ifdef SQLITE_ENABLE_COLUMN_METADATA
drh393344f2018-03-09 16:37:05 +00002454 sqlite3_snprintf(30, z+x, "database name:");
2455 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2456 sqlite3_snprintf(30, z+x, "table name:");
2457 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2458 sqlite3_snprintf(30, z+x, "origin name:");
2459 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002460#endif
drh2ce15c32017-07-11 13:34:40 +00002461 }
drh929cce82018-03-17 16:26:36 +00002462 }
drh2ce15c32017-07-11 13:34:40 +00002463
drh393344f2018-03-09 16:37:05 +00002464 displayStatLine(pArg, "Memory Used:",
2465 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2466 displayStatLine(pArg, "Number of Outstanding Allocations:",
2467 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2468 if( pArg->shellFlgs & SHFLG_Pagecache ){
2469 displayStatLine(pArg, "Number of Pcache Pages Used:",
2470 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2471 }
2472 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2473 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2474 displayStatLine(pArg, "Largest Allocation:",
2475 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2476 displayStatLine(pArg, "Largest Pcache Allocation:",
2477 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2478#ifdef YYTRACKMAXSTACKDEPTH
2479 displayStatLine(pArg, "Deepest Parser Stack:",
2480 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2481#endif
2482
2483 if( db ){
drh2ce15c32017-07-11 13:34:40 +00002484 if( pArg->shellFlgs & SHFLG_Lookaside ){
2485 iHiwtr = iCur = -1;
2486 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2487 &iCur, &iHiwtr, bReset);
2488 raw_printf(pArg->out,
2489 "Lookaside Slots Used: %d (max %d)\n",
2490 iCur, iHiwtr);
2491 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2492 &iCur, &iHiwtr, bReset);
2493 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2494 iHiwtr);
2495 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2496 &iCur, &iHiwtr, bReset);
2497 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2498 iHiwtr);
2499 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2500 &iCur, &iHiwtr, bReset);
2501 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2502 iHiwtr);
2503 }
2504 iHiwtr = iCur = -1;
2505 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2506 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2507 iCur);
2508 iHiwtr = iCur = -1;
2509 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2510 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2511 iHiwtr = iCur = -1;
2512 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2513 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2514 iHiwtr = iCur = -1;
2515 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2516 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2517 iHiwtr = iCur = -1;
drhffc78a42018-03-14 14:53:50 +00002518 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2519 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2520 iHiwtr = iCur = -1;
drh2ce15c32017-07-11 13:34:40 +00002521 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2522 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2523 iCur);
2524 iHiwtr = iCur = -1;
2525 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2526 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2527 iCur);
2528 }
2529
drh393344f2018-03-09 16:37:05 +00002530 if( pArg->pStmt ){
drh2ce15c32017-07-11 13:34:40 +00002531 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2532 bReset);
2533 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2534 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2535 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2536 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2537 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2538 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2539 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
drhe2754c12019-08-26 12:50:01 +00002540 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset);
drh393344f2018-03-09 16:37:05 +00002541 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2542 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2543 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2544 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2545 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
drh2ce15c32017-07-11 13:34:40 +00002546 }
2547
2548#ifdef __linux__
2549 displayLinuxIoStats(pArg->out);
2550#endif
2551
2552 /* Do not remove this machine readable comment: extra-stats-output-here */
2553
2554 return 0;
2555}
2556
2557/*
2558** Display scan stats.
2559*/
2560static void display_scanstats(
2561 sqlite3 *db, /* Database to query */
2562 ShellState *pArg /* Pointer to ShellState */
2563){
2564#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2565 UNUSED_PARAMETER(db);
2566 UNUSED_PARAMETER(pArg);
2567#else
2568 int i, k, n, mx;
2569 raw_printf(pArg->out, "-------- scanstats --------\n");
2570 mx = 0;
2571 for(k=0; k<=mx; k++){
2572 double rEstLoop = 1.0;
2573 for(i=n=0; 1; i++){
2574 sqlite3_stmt *p = pArg->pStmt;
2575 sqlite3_int64 nLoop, nVisit;
2576 double rEst;
2577 int iSid;
2578 const char *zExplain;
2579 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2580 break;
2581 }
2582 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2583 if( iSid>mx ) mx = iSid;
2584 if( iSid!=k ) continue;
2585 if( n==0 ){
2586 rEstLoop = (double)nLoop;
2587 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2588 }
2589 n++;
2590 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2591 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2592 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2593 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2594 rEstLoop *= rEst;
2595 raw_printf(pArg->out,
2596 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2597 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2598 );
2599 }
2600 }
2601 raw_printf(pArg->out, "---------------------------\n");
2602#endif
2603}
2604
2605/*
2606** Parameter azArray points to a zero-terminated array of strings. zStr
2607** points to a single nul-terminated string. Return non-zero if zStr
2608** is equal, according to strcmp(), to any of the strings in the array.
2609** Otherwise, return zero.
2610*/
2611static int str_in_array(const char *zStr, const char **azArray){
2612 int i;
2613 for(i=0; azArray[i]; i++){
2614 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2615 }
2616 return 0;
2617}
2618
2619/*
2620** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2621** and populate the ShellState.aiIndent[] array with the number of
2622** spaces each opcode should be indented before it is output.
2623**
2624** The indenting rules are:
2625**
2626** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2627** all opcodes that occur between the p2 jump destination and the opcode
2628** itself by 2 spaces.
2629**
2630** * For each "Goto", if the jump destination is earlier in the program
2631** and ends on one of:
2632** Yield SeekGt SeekLt RowSetRead Rewind
2633** or if the P1 parameter is one instead of zero,
2634** then indent all opcodes between the earlier instruction
2635** and "Goto" by 2 spaces.
2636*/
2637static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2638 const char *zSql; /* The text of the SQL statement */
2639 const char *z; /* Used to check if this is an EXPLAIN */
2640 int *abYield = 0; /* True if op is an OP_Yield */
2641 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2642 int iOp; /* Index of operation in p->aiIndent[] */
2643
drhf1949b62018-06-07 17:32:59 +00002644 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
drh2ce15c32017-07-11 13:34:40 +00002645 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2646 "Rewind", 0 };
2647 const char *azGoto[] = { "Goto", 0 };
2648
2649 /* Try to figure out if this is really an EXPLAIN statement. If this
2650 ** cannot be verified, return early. */
2651 if( sqlite3_column_count(pSql)!=8 ){
2652 p->cMode = p->mode;
2653 return;
2654 }
2655 zSql = sqlite3_sql(pSql);
2656 if( zSql==0 ) return;
2657 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2658 if( sqlite3_strnicmp(z, "explain", 7) ){
2659 p->cMode = p->mode;
2660 return;
2661 }
2662
2663 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2664 int i;
2665 int iAddr = sqlite3_column_int(pSql, 0);
2666 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2667
2668 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2669 ** p2 is an instruction address, set variable p2op to the index of that
2670 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2671 ** the current instruction is part of a sub-program generated by an
2672 ** SQL trigger or foreign key. */
2673 int p2 = sqlite3_column_int(pSql, 3);
2674 int p2op = (p2 + (iOp-iAddr));
2675
2676 /* Grow the p->aiIndent array as required */
2677 if( iOp>=nAlloc ){
2678 if( iOp==0 ){
2679 /* Do further verfication that this is explain output. Abort if
2680 ** it is not */
2681 static const char *explainCols[] = {
2682 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2683 int jj;
2684 for(jj=0; jj<ArraySize(explainCols); jj++){
2685 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2686 p->cMode = p->mode;
2687 sqlite3_reset(pSql);
2688 return;
2689 }
2690 }
2691 }
2692 nAlloc += 100;
2693 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002694 if( p->aiIndent==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002695 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002696 if( abYield==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002697 }
2698 abYield[iOp] = str_in_array(zOp, azYield);
2699 p->aiIndent[iOp] = 0;
2700 p->nIndent = iOp+1;
2701
2702 if( str_in_array(zOp, azNext) ){
2703 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2704 }
2705 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2706 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2707 ){
2708 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2709 }
2710 }
2711
2712 p->iIndent = 0;
2713 sqlite3_free(abYield);
2714 sqlite3_reset(pSql);
2715}
2716
2717/*
2718** Free the array allocated by explain_data_prepare().
2719*/
2720static void explain_data_delete(ShellState *p){
2721 sqlite3_free(p->aiIndent);
2722 p->aiIndent = 0;
2723 p->nIndent = 0;
2724 p->iIndent = 0;
2725}
2726
2727/*
2728** Disable and restore .wheretrace and .selecttrace settings.
2729*/
2730#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2731extern int sqlite3SelectTrace;
2732static int savedSelectTrace;
2733#endif
2734#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2735extern int sqlite3WhereTrace;
2736static int savedWhereTrace;
2737#endif
2738static void disable_debug_trace_modes(void){
2739#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2740 savedSelectTrace = sqlite3SelectTrace;
2741 sqlite3SelectTrace = 0;
2742#endif
2743#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2744 savedWhereTrace = sqlite3WhereTrace;
2745 sqlite3WhereTrace = 0;
2746#endif
2747}
2748static void restore_debug_trace_modes(void){
2749#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2750 sqlite3SelectTrace = savedSelectTrace;
2751#endif
2752#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2753 sqlite3WhereTrace = savedWhereTrace;
2754#endif
2755}
2756
drh9cb02642019-02-28 20:10:52 +00002757/* Create the TEMP table used to store parameter bindings */
2758static void bind_table_init(ShellState *p){
drh346f4e22019-03-25 21:35:41 +00002759 int wrSchema = 0;
2760 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
2761 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
drh9cb02642019-02-28 20:10:52 +00002762 sqlite3_exec(p->db,
drh65c29fd2019-03-25 21:56:26 +00002763 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
drh9cb02642019-02-28 20:10:52 +00002764 " key TEXT PRIMARY KEY,\n"
2765 " value ANY\n"
2766 ") WITHOUT ROWID;",
2767 0, 0, 0);
drh346f4e22019-03-25 21:35:41 +00002768 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
drh9cb02642019-02-28 20:10:52 +00002769}
2770
drh8b738d02019-02-25 18:43:54 +00002771/*
2772** Bind parameters on a prepared statement.
2773**
2774** Parameter bindings are taken from a TEMP table of the form:
2775**
drh1cb02632019-03-25 22:05:22 +00002776** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
drh8b738d02019-02-25 18:43:54 +00002777** WITHOUT ROWID;
2778**
2779** No bindings occur if this table does not exist. The special character '$'
2780** is included in the table name to help prevent collisions with actual tables.
2781** The table must be in the TEMP schema.
2782*/
2783static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2784 int nVar;
2785 int i;
2786 int rc;
2787 sqlite3_stmt *pQ = 0;
2788
2789 nVar = sqlite3_bind_parameter_count(pStmt);
2790 if( nVar==0 ) return; /* Nothing to do */
drh65c29fd2019-03-25 21:56:26 +00002791 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
drh8b738d02019-02-25 18:43:54 +00002792 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2793 return; /* Parameter table does not exist */
2794 }
2795 rc = sqlite3_prepare_v2(pArg->db,
drh65c29fd2019-03-25 21:56:26 +00002796 "SELECT value FROM temp.sqlite_parameters"
drh8b738d02019-02-25 18:43:54 +00002797 " WHERE key=?1", -1, &pQ, 0);
2798 if( rc || pQ==0 ) return;
2799 for(i=1; i<=nVar; i++){
2800 char zNum[30];
2801 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2802 if( zVar==0 ){
2803 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2804 zVar = zNum;
2805 }
2806 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2807 if( sqlite3_step(pQ)==SQLITE_ROW ){
2808 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2809 }else{
2810 sqlite3_bind_null(pStmt, i);
2811 }
2812 sqlite3_reset(pQ);
2813 }
2814 sqlite3_finalize(pQ);
2815}
2816
drh2ce15c32017-07-11 13:34:40 +00002817/*
2818** Run a prepared statement
2819*/
2820static void exec_prepared_stmt(
2821 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002822 sqlite3_stmt *pStmt /* Statment to run */
drh2ce15c32017-07-11 13:34:40 +00002823){
2824 int rc;
2825
2826 /* perform the first step. this will tell us if we
2827 ** have a result set or not and how wide it is.
2828 */
2829 rc = sqlite3_step(pStmt);
2830 /* if we have a result set... */
2831 if( SQLITE_ROW == rc ){
drha10b9992018-03-09 15:24:33 +00002832 /* allocate space for col name ptr, value ptr, and type */
2833 int nCol = sqlite3_column_count(pStmt);
2834 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2835 if( !pData ){
2836 rc = SQLITE_NOMEM;
drh2ce15c32017-07-11 13:34:40 +00002837 }else{
drha10b9992018-03-09 15:24:33 +00002838 char **azCols = (char **)pData; /* Names of result columns */
2839 char **azVals = &azCols[nCol]; /* Results */
2840 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2841 int i, x;
2842 assert(sizeof(int) <= sizeof(char *));
2843 /* save off ptrs to column names */
2844 for(i=0; i<nCol; i++){
2845 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2846 }
drh2ce15c32017-07-11 13:34:40 +00002847 do{
drha10b9992018-03-09 15:24:33 +00002848 /* extract the data and data types */
2849 for(i=0; i<nCol; i++){
2850 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2851 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2852 azVals[i] = "";
2853 }else{
2854 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2855 }
2856 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2857 rc = SQLITE_NOMEM;
2858 break; /* from for */
2859 }
2860 } /* end for */
2861
2862 /* if data and types extracted successfully... */
2863 if( SQLITE_ROW == rc ){
2864 /* call the supplied callback with the result row data */
2865 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2866 rc = SQLITE_ABORT;
2867 }else{
2868 rc = sqlite3_step(pStmt);
2869 }
2870 }
2871 } while( SQLITE_ROW == rc );
2872 sqlite3_free(pData);
drh2ce15c32017-07-11 13:34:40 +00002873 }
2874 }
2875}
2876
dan6b046be2018-01-09 15:25:55 +00002877#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002878/*
dan43efc182017-12-19 17:42:13 +00002879** This function is called to process SQL if the previous shell command
2880** was ".expert". It passes the SQL in the second argument directly to
2881** the sqlite3expert object.
2882**
2883** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2884** code. In this case, (*pzErr) may be set to point to a buffer containing
2885** an English language error message. It is the responsibility of the
2886** caller to eventually free this buffer using sqlite3_free().
2887*/
2888static int expertHandleSQL(
2889 ShellState *pState,
2890 const char *zSql,
2891 char **pzErr
2892){
2893 assert( pState->expert.pExpert );
2894 assert( pzErr==0 || *pzErr==0 );
2895 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2896}
2897
2898/*
2899** This function is called either to silently clean up the object
2900** created by the ".expert" command (if bCancel==1), or to generate a
2901** report from it and then clean it up (if bCancel==0).
2902**
2903** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2904** code. In this case, (*pzErr) may be set to point to a buffer containing
2905** an English language error message. It is the responsibility of the
2906** caller to eventually free this buffer using sqlite3_free().
2907*/
2908static int expertFinish(
2909 ShellState *pState,
2910 int bCancel,
2911 char **pzErr
2912){
2913 int rc = SQLITE_OK;
2914 sqlite3expert *p = pState->expert.pExpert;
2915 assert( p );
2916 assert( bCancel || pzErr==0 || *pzErr==0 );
2917 if( bCancel==0 ){
2918 FILE *out = pState->out;
2919 int bVerbose = pState->expert.bVerbose;
2920
2921 rc = sqlite3_expert_analyze(p, pzErr);
2922 if( rc==SQLITE_OK ){
2923 int nQuery = sqlite3_expert_count(p);
2924 int i;
2925
2926 if( bVerbose ){
2927 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2928 raw_printf(out, "-- Candidates -----------------------------\n");
2929 raw_printf(out, "%s\n", zCand);
2930 }
2931 for(i=0; i<nQuery; i++){
2932 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2933 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2934 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2935 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2936 if( bVerbose ){
2937 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2938 raw_printf(out, "%s\n\n", zSql);
2939 }
2940 raw_printf(out, "%s\n", zIdx);
2941 raw_printf(out, "%s\n", zEQP);
2942 }
2943 }
2944 }
2945 sqlite3_expert_destroy(p);
2946 pState->expert.pExpert = 0;
2947 return rc;
2948}
2949
dan6b046be2018-01-09 15:25:55 +00002950/*
2951** Implementation of ".expert" dot command.
2952*/
2953static int expertDotCommand(
2954 ShellState *pState, /* Current shell tool state */
2955 char **azArg, /* Array of arguments passed to dot command */
2956 int nArg /* Number of entries in azArg[] */
2957){
2958 int rc = SQLITE_OK;
2959 char *zErr = 0;
2960 int i;
2961 int iSample = 0;
2962
2963 assert( pState->expert.pExpert==0 );
2964 memset(&pState->expert, 0, sizeof(ExpertInfo));
2965
2966 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2967 char *z = azArg[i];
2968 int n;
2969 if( z[0]=='-' && z[1]=='-' ) z++;
2970 n = strlen30(z);
2971 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2972 pState->expert.bVerbose = 1;
2973 }
2974 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2975 if( i==(nArg-1) ){
2976 raw_printf(stderr, "option requires an argument: %s\n", z);
2977 rc = SQLITE_ERROR;
2978 }else{
2979 iSample = (int)integerValue(azArg[++i]);
2980 if( iSample<0 || iSample>100 ){
2981 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2982 rc = SQLITE_ERROR;
2983 }
2984 }
2985 }
2986 else{
2987 raw_printf(stderr, "unknown option: %s\n", z);
2988 rc = SQLITE_ERROR;
2989 }
2990 }
2991
2992 if( rc==SQLITE_OK ){
2993 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2994 if( pState->expert.pExpert==0 ){
2995 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2996 rc = SQLITE_ERROR;
2997 }else{
2998 sqlite3_expert_config(
2999 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
3000 );
3001 }
3002 }
3003
3004 return rc;
3005}
3006#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00003007
3008/*
drh2ce15c32017-07-11 13:34:40 +00003009** Execute a statement or set of statements. Print
3010** any result rows/columns depending on the current mode
3011** set via the supplied callback.
3012**
3013** This is very similar to SQLite's built-in sqlite3_exec()
3014** function except it takes a slightly different callback
3015** and callback data argument.
3016*/
3017static int shell_exec(
drh2ce15c32017-07-11 13:34:40 +00003018 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00003019 const char *zSql, /* SQL to be evaluated */
drh2ce15c32017-07-11 13:34:40 +00003020 char **pzErrMsg /* Error msg written here */
3021){
3022 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
3023 int rc = SQLITE_OK; /* Return Code */
3024 int rc2;
3025 const char *zLeftover; /* Tail of unprocessed SQL */
drha10b9992018-03-09 15:24:33 +00003026 sqlite3 *db = pArg->db;
drh2ce15c32017-07-11 13:34:40 +00003027
3028 if( pzErrMsg ){
3029 *pzErrMsg = NULL;
3030 }
3031
dan6b046be2018-01-09 15:25:55 +00003032#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00003033 if( pArg->expert.pExpert ){
3034 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3035 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3036 }
dan6b046be2018-01-09 15:25:55 +00003037#endif
dan43efc182017-12-19 17:42:13 +00003038
drh2ce15c32017-07-11 13:34:40 +00003039 while( zSql[0] && (SQLITE_OK == rc) ){
3040 static const char *zStmtSql;
3041 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3042 if( SQLITE_OK != rc ){
3043 if( pzErrMsg ){
3044 *pzErrMsg = save_err_msg(db);
3045 }
3046 }else{
3047 if( !pStmt ){
3048 /* this happens for a comment or white-space */
3049 zSql = zLeftover;
3050 while( IsSpace(zSql[0]) ) zSql++;
3051 continue;
3052 }
3053 zStmtSql = sqlite3_sql(pStmt);
3054 if( zStmtSql==0 ) zStmtSql = "";
3055 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3056
3057 /* save off the prepared statment handle and reset row count */
3058 if( pArg ){
3059 pArg->pStmt = pStmt;
3060 pArg->cnt = 0;
3061 }
3062
3063 /* echo the sql statement if echo on */
3064 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3065 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3066 }
3067
3068 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drh39c5c4a2019-03-06 14:53:27 +00003069 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
drh2ce15c32017-07-11 13:34:40 +00003070 sqlite3_stmt *pExplain;
3071 char *zEQP;
drhada70452017-12-21 21:02:27 +00003072 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00003073 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00003074 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3075 if( pArg->autoEQP>=AUTOEQP_trigger ){
3076 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3077 }
drh2ce15c32017-07-11 13:34:40 +00003078 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3079 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3080 if( rc==SQLITE_OK ){
3081 while( sqlite3_step(pExplain)==SQLITE_ROW ){
drh4b5345c2018-04-24 13:07:40 +00003082 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
drhe2ca99c2018-05-02 00:33:43 +00003083 int iEqpId = sqlite3_column_int(pExplain, 0);
3084 int iParentId = sqlite3_column_int(pExplain, 1);
drh4b5345c2018-04-24 13:07:40 +00003085 if( zEQPLine[0]=='-' ) eqp_render(pArg);
drhe2ca99c2018-05-02 00:33:43 +00003086 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
drh2ce15c32017-07-11 13:34:40 +00003087 }
drh4b5345c2018-04-24 13:07:40 +00003088 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003089 }
3090 sqlite3_finalize(pExplain);
3091 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00003092 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00003093 /* Also do an EXPLAIN for ".eqp full" mode */
3094 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3095 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3096 if( rc==SQLITE_OK ){
3097 pArg->cMode = MODE_Explain;
3098 explain_data_prepare(pArg, pExplain);
drha10b9992018-03-09 15:24:33 +00003099 exec_prepared_stmt(pArg, pExplain);
drh2ce15c32017-07-11 13:34:40 +00003100 explain_data_delete(pArg);
3101 }
3102 sqlite3_finalize(pExplain);
3103 sqlite3_free(zEQP);
3104 }
drh51efe092018-03-20 12:04:38 +00003105 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3106 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3107 /* Reprepare pStmt before reactiving trace modes */
3108 sqlite3_finalize(pStmt);
3109 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
drh3c49eaf2018-06-07 15:23:43 +00003110 if( pArg ) pArg->pStmt = pStmt;
drh51efe092018-03-20 12:04:38 +00003111 }
drh2ce15c32017-07-11 13:34:40 +00003112 restore_debug_trace_modes();
3113 }
3114
3115 if( pArg ){
3116 pArg->cMode = pArg->mode;
drh4b5345c2018-04-24 13:07:40 +00003117 if( pArg->autoExplain ){
drh39c5c4a2019-03-06 14:53:27 +00003118 if( sqlite3_stmt_isexplain(pStmt)==1 ){
drh4b5345c2018-04-24 13:07:40 +00003119 pArg->cMode = MODE_Explain;
3120 }
drh39c5c4a2019-03-06 14:53:27 +00003121 if( sqlite3_stmt_isexplain(pStmt)==2 ){
drh4b5345c2018-04-24 13:07:40 +00003122 pArg->cMode = MODE_EQP;
3123 }
drh2ce15c32017-07-11 13:34:40 +00003124 }
3125
3126 /* If the shell is currently in ".explain" mode, gather the extra
3127 ** data required to add indents to the output.*/
3128 if( pArg->cMode==MODE_Explain ){
3129 explain_data_prepare(pArg, pStmt);
3130 }
3131 }
3132
drh8b738d02019-02-25 18:43:54 +00003133 bind_prepared_stmt(pArg, pStmt);
drha10b9992018-03-09 15:24:33 +00003134 exec_prepared_stmt(pArg, pStmt);
drh2ce15c32017-07-11 13:34:40 +00003135 explain_data_delete(pArg);
drh4b5345c2018-04-24 13:07:40 +00003136 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003137
3138 /* print usage stats if stats on */
3139 if( pArg && pArg->statsOn ){
3140 display_stats(db, pArg, 0);
3141 }
3142
3143 /* print loop-counters if required */
3144 if( pArg && pArg->scanstatsOn ){
3145 display_scanstats(db, pArg);
3146 }
3147
3148 /* Finalize the statement just executed. If this fails, save a
3149 ** copy of the error message. Otherwise, set zSql to point to the
3150 ** next statement to execute. */
3151 rc2 = sqlite3_finalize(pStmt);
3152 if( rc!=SQLITE_NOMEM ) rc = rc2;
3153 if( rc==SQLITE_OK ){
3154 zSql = zLeftover;
3155 while( IsSpace(zSql[0]) ) zSql++;
3156 }else if( pzErrMsg ){
3157 *pzErrMsg = save_err_msg(db);
3158 }
3159
3160 /* clear saved stmt handle */
3161 if( pArg ){
3162 pArg->pStmt = NULL;
3163 }
3164 }
3165 } /* end while */
3166
3167 return rc;
3168}
3169
3170/*
3171** Release memory previously allocated by tableColumnList().
3172*/
3173static void freeColumnList(char **azCol){
3174 int i;
3175 for(i=1; azCol[i]; i++){
3176 sqlite3_free(azCol[i]);
3177 }
3178 /* azCol[0] is a static string */
3179 sqlite3_free(azCol);
3180}
3181
3182/*
3183** Return a list of pointers to strings which are the names of all
3184** columns in table zTab. The memory to hold the names is dynamically
3185** allocated and must be released by the caller using a subsequent call
3186** to freeColumnList().
3187**
3188** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3189** value that needs to be preserved, then azCol[0] is filled in with the
3190** name of the rowid column.
3191**
3192** The first regular column in the table is azCol[1]. The list is terminated
3193** by an entry with azCol[i]==0.
3194*/
3195static char **tableColumnList(ShellState *p, const char *zTab){
3196 char **azCol = 0;
3197 sqlite3_stmt *pStmt;
3198 char *zSql;
3199 int nCol = 0;
3200 int nAlloc = 0;
3201 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3202 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3203 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3204 int rc;
3205
3206 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3207 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3208 sqlite3_free(zSql);
3209 if( rc ) return 0;
3210 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3211 if( nCol>=nAlloc-2 ){
3212 nAlloc = nAlloc*2 + nCol + 10;
3213 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
drh4b5345c2018-04-24 13:07:40 +00003214 if( azCol==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00003215 }
3216 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3217 if( sqlite3_column_int(pStmt, 5) ){
3218 nPK++;
3219 if( nPK==1
3220 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3221 "INTEGER")==0
3222 ){
3223 isIPK = 1;
3224 }else{
3225 isIPK = 0;
3226 }
3227 }
3228 }
3229 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00003230 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003231 azCol[0] = 0;
3232 azCol[nCol+1] = 0;
3233
3234 /* The decision of whether or not a rowid really needs to be preserved
3235 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3236 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3237 ** rowids on tables where the rowid is inaccessible because there are other
3238 ** columns in the table named "rowid", "_rowid_", and "oid".
3239 */
3240 if( preserveRowid && isIPK ){
3241 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3242 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3243 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3244 ** ROWID aliases. To distinguish these cases, check to see if
3245 ** there is a "pk" entry in "PRAGMA index_list". There will be
3246 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3247 */
3248 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3249 " WHERE origin='pk'", zTab);
3250 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3251 sqlite3_free(zSql);
3252 if( rc ){
3253 freeColumnList(azCol);
3254 return 0;
3255 }
3256 rc = sqlite3_step(pStmt);
3257 sqlite3_finalize(pStmt);
3258 preserveRowid = rc==SQLITE_ROW;
3259 }
3260 if( preserveRowid ){
3261 /* Only preserve the rowid if we can find a name to use for the
3262 ** rowid */
3263 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3264 int i, j;
3265 for(j=0; j<3; j++){
3266 for(i=1; i<=nCol; i++){
3267 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3268 }
3269 if( i>nCol ){
3270 /* At this point, we know that azRowid[j] is not the name of any
3271 ** ordinary column in the table. Verify that azRowid[j] is a valid
3272 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3273 ** tables will fail this last check */
3274 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3275 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3276 break;
3277 }
3278 }
3279 }
3280 return azCol;
3281}
3282
3283/*
3284** Toggle the reverse_unordered_selects setting.
3285*/
3286static void toggleSelectOrder(sqlite3 *db){
3287 sqlite3_stmt *pStmt = 0;
3288 int iSetting = 0;
3289 char zStmt[100];
3290 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3291 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3292 iSetting = sqlite3_column_int(pStmt, 0);
3293 }
3294 sqlite3_finalize(pStmt);
3295 sqlite3_snprintf(sizeof(zStmt), zStmt,
3296 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3297 sqlite3_exec(db, zStmt, 0, 0, 0);
3298}
3299
3300/*
3301** This is a different callback routine used for dumping the database.
3302** Each row received by this callback consists of a table name,
3303** the table type ("index" or "table") and SQL to create the table.
3304** This routine should print text sufficient to recreate the table.
3305*/
3306static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3307 int rc;
3308 const char *zTable;
3309 const char *zType;
3310 const char *zSql;
3311 ShellState *p = (ShellState *)pArg;
3312
3313 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00003314 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003315 zTable = azArg[0];
3316 zType = azArg[1];
3317 zSql = azArg[2];
3318
3319 if( strcmp(zTable, "sqlite_sequence")==0 ){
3320 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3321 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3322 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3323 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3324 return 0;
3325 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3326 char *zIns;
3327 if( !p->writableSchema ){
3328 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3329 p->writableSchema = 1;
3330 }
3331 zIns = sqlite3_mprintf(
3332 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3333 "VALUES('table','%q','%q',0,'%q');",
3334 zTable, zTable, zSql);
3335 utf8_printf(p->out, "%s\n", zIns);
3336 sqlite3_free(zIns);
3337 return 0;
3338 }else{
3339 printSchemaLine(p->out, zSql, ";\n");
3340 }
3341
3342 if( strcmp(zType, "table")==0 ){
3343 ShellText sSelect;
3344 ShellText sTable;
3345 char **azCol;
3346 int i;
3347 char *savedDestTable;
3348 int savedMode;
3349
3350 azCol = tableColumnList(p, zTable);
3351 if( azCol==0 ){
3352 p->nErr++;
3353 return 0;
3354 }
3355
3356 /* Always quote the table name, even if it appears to be pure ascii,
3357 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3358 initText(&sTable);
3359 appendText(&sTable, zTable, quoteChar(zTable));
3360 /* If preserving the rowid, add a column list after the table name.
3361 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3362 ** instead of the usual "INSERT INTO tab VALUES(...)".
3363 */
3364 if( azCol[0] ){
3365 appendText(&sTable, "(", 0);
3366 appendText(&sTable, azCol[0], 0);
3367 for(i=1; azCol[i]; i++){
3368 appendText(&sTable, ",", 0);
3369 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3370 }
3371 appendText(&sTable, ")", 0);
3372 }
3373
3374 /* Build an appropriate SELECT statement */
3375 initText(&sSelect);
3376 appendText(&sSelect, "SELECT ", 0);
3377 if( azCol[0] ){
3378 appendText(&sSelect, azCol[0], 0);
3379 appendText(&sSelect, ",", 0);
3380 }
3381 for(i=1; azCol[i]; i++){
3382 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3383 if( azCol[i+1] ){
3384 appendText(&sSelect, ",", 0);
3385 }
3386 }
3387 freeColumnList(azCol);
3388 appendText(&sSelect, " FROM ", 0);
3389 appendText(&sSelect, zTable, quoteChar(zTable));
3390
3391 savedDestTable = p->zDestTable;
3392 savedMode = p->mode;
3393 p->zDestTable = sTable.z;
3394 p->mode = p->cMode = MODE_Insert;
drha10b9992018-03-09 15:24:33 +00003395 rc = shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003396 if( (rc&0xff)==SQLITE_CORRUPT ){
3397 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3398 toggleSelectOrder(p->db);
drha10b9992018-03-09 15:24:33 +00003399 shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003400 toggleSelectOrder(p->db);
3401 }
3402 p->zDestTable = savedDestTable;
3403 p->mode = savedMode;
3404 freeText(&sTable);
3405 freeText(&sSelect);
3406 if( rc ) p->nErr++;
3407 }
3408 return 0;
3409}
3410
3411/*
3412** Run zQuery. Use dump_callback() as the callback routine so that
3413** the contents of the query are output as SQL statements.
3414**
3415** If we get a SQLITE_CORRUPT error, rerun the query after appending
3416** "ORDER BY rowid DESC" to the end.
3417*/
3418static int run_schema_dump_query(
3419 ShellState *p,
3420 const char *zQuery
3421){
3422 int rc;
3423 char *zErr = 0;
3424 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3425 if( rc==SQLITE_CORRUPT ){
3426 char *zQ2;
3427 int len = strlen30(zQuery);
3428 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3429 if( zErr ){
3430 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3431 sqlite3_free(zErr);
3432 zErr = 0;
3433 }
3434 zQ2 = malloc( len+100 );
3435 if( zQ2==0 ) return rc;
3436 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3437 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3438 if( rc ){
3439 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3440 }else{
3441 rc = SQLITE_CORRUPT;
3442 }
3443 sqlite3_free(zErr);
3444 free(zQ2);
3445 }
3446 return rc;
3447}
3448
3449/*
drh98aa2ab2018-09-26 16:53:51 +00003450** Text of help messages.
3451**
3452** The help text for each individual command begins with a line that starts
3453** with ".". Subsequent lines are supplimental information.
3454**
3455** There must be two or more spaces between the end of the command and the
3456** start of the description of what that command does.
drh2ce15c32017-07-11 13:34:40 +00003457*/
drh98aa2ab2018-09-26 16:53:51 +00003458static const char *(azHelp[]) = {
drhe37c0e12018-01-06 19:19:50 +00003459#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drh98aa2ab2018-09-26 16:53:51 +00003460 ".archive ... Manage SQL archives",
3461 " Each command must have exactly one of the following options:",
3462 " -c, --create Create a new archive",
drhe2754c12019-08-26 12:50:01 +00003463 " -u, --update Add or update files with changed mtime",
3464 " -i, --insert Like -u but always add even if unchanged",
drh98aa2ab2018-09-26 16:53:51 +00003465 " -t, --list List contents of archive",
3466 " -x, --extract Extract files from archive",
3467 " Optional arguments:",
3468 " -v, --verbose Print each filename as it is processed",
drhe2754c12019-08-26 12:50:01 +00003469 " -f FILE, --file FILE Use archive FILE (default is current db)",
3470 " -a FILE, --append FILE Open FILE using the apndvfs VFS",
3471 " -C DIR, --directory DIR Read/extract files from directory DIR",
drh98aa2ab2018-09-26 16:53:51 +00003472 " -n, --dryrun Show the SQL that would have occurred",
3473 " Examples:",
drhe2754c12019-08-26 12:50:01 +00003474 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar",
3475 " .ar -tf ARCHIVE # List members of ARCHIVE",
3476 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE",
drh98aa2ab2018-09-26 16:53:51 +00003477 " See also:",
3478 " http://sqlite.org/cli.html#sqlar_archive_support",
drhe37c0e12018-01-06 19:19:50 +00003479#endif
drh2ce15c32017-07-11 13:34:40 +00003480#ifndef SQLITE_OMIT_AUTHORIZATION
drh98aa2ab2018-09-26 16:53:51 +00003481 ".auth ON|OFF Show authorizer callbacks",
drh2ce15c32017-07-11 13:34:40 +00003482#endif
drh98aa2ab2018-09-26 16:53:51 +00003483 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3484 " --append Use the appendvfs",
drhe2754c12019-08-26 12:50:01 +00003485 " --async Write to FILE without journal and fsync()",
drh98aa2ab2018-09-26 16:53:51 +00003486 ".bail on|off Stop after hitting an error. Default OFF",
3487 ".binary on|off Turn binary output on or off. Default OFF",
3488 ".cd DIRECTORY Change the working directory to DIRECTORY",
3489 ".changes on|off Show number of rows changed by SQL",
3490 ".check GLOB Fail if output since .testcase does not match",
3491 ".clone NEWDB Clone data into NEWDB from the existing database",
3492 ".databases List names and files of attached databases",
3493 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3494 ".dbinfo ?DB? Show status information about the database",
drheb7f2a02018-09-26 18:02:32 +00003495 ".dump ?TABLE? ... Render all database content as SQL",
3496 " Options:",
3497 " --preserve-rowids Include ROWID values in the output",
3498 " --newlines Allow unescaped newline characters in output",
drhe551b512019-04-17 13:58:07 +00003499 " TABLE is a LIKE pattern for the tables to dump",
drh98aa2ab2018-09-26 16:53:51 +00003500 ".echo on|off Turn command echo on or off",
drhb4e50392019-01-26 15:40:04 +00003501 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
3502 " Other Modes:",
3503#ifdef SQLITE_DEBUG
3504 " test Show raw EXPLAIN QUERY PLAN output",
drhe2754c12019-08-26 12:50:01 +00003505 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"",
drhb4e50392019-01-26 15:40:04 +00003506#endif
3507 " trigger Like \"full\" but also show trigger bytecode",
drhe2754c12019-08-26 12:50:01 +00003508 ".excel Display the output of next command in spreadsheet",
drheb7f2a02018-09-26 18:02:32 +00003509 ".exit ?CODE? Exit this program with return-code CODE",
drhe2754c12019-08-26 12:50:01 +00003510 ".expert EXPERIMENTAL. Suggest indexes for queries",
drh2ce15c32017-07-11 13:34:40 +00003511/* Because explain mode comes on automatically now, the ".explain" mode
drhe2754c12019-08-26 12:50:01 +00003512** is removed from the help screen. It is still supported for legacy, however */
3513/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off",*/
drhd985f722019-06-05 14:29:53 +00003514 ".filectrl CMD ... Run various sqlite3_file_control() operations",
3515 " Run \".filectrl\" with no arguments for details",
drh98aa2ab2018-09-26 16:53:51 +00003516 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3517 ".headers on|off Turn display of headers on or off",
3518 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3519 ".import FILE TABLE Import data from FILE into TABLE",
drh2ce15c32017-07-11 13:34:40 +00003520#ifndef SQLITE_OMIT_TEST_CONTROL
drh98aa2ab2018-09-26 16:53:51 +00003521 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
drh2ce15c32017-07-11 13:34:40 +00003522#endif
drh98aa2ab2018-09-26 16:53:51 +00003523 ".indexes ?TABLE? Show names of indexes",
3524 " If TABLE is specified, only show indexes for",
3525 " tables matching TABLE using the LIKE operator.",
drh2ce15c32017-07-11 13:34:40 +00003526#ifdef SQLITE_ENABLE_IOTRACE
drh98aa2ab2018-09-26 16:53:51 +00003527 ".iotrace FILE Enable I/O diagnostic logging to FILE",
drh2ce15c32017-07-11 13:34:40 +00003528#endif
drh98aa2ab2018-09-26 16:53:51 +00003529 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3530 ".lint OPTIONS Report potential schema issues.",
3531 " Options:",
3532 " fkey-indexes Find missing foreign key indexes",
drh2ce15c32017-07-11 13:34:40 +00003533#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh98aa2ab2018-09-26 16:53:51 +00003534 ".load FILE ?ENTRY? Load an extension library",
drh2ce15c32017-07-11 13:34:40 +00003535#endif
drh98aa2ab2018-09-26 16:53:51 +00003536 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3537 ".mode MODE ?TABLE? Set output mode",
3538 " MODE is one of:",
3539 " ascii Columns/rows delimited by 0x1F and 0x1E",
3540 " csv Comma-separated values",
3541 " column Left-aligned columns. (See .width)",
3542 " html HTML <table> code",
3543 " insert SQL insert statements for TABLE",
3544 " line One value per line",
3545 " list Values delimited by \"|\"",
3546 " quote Escape answers as for SQL",
3547 " tabs Tab-separated values",
3548 " tcl TCL list elements",
3549 ".nullvalue STRING Use STRING in place of NULL values",
3550 ".once (-e|-x|FILE) Output for the next SQL command only to FILE",
3551 " If FILE begins with '|' then open as a pipe",
3552 " Other options:",
3553 " -e Invoke system text editor",
3554 " -x Open in a spreadsheet",
3555 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3556 " Options:",
drh60f34ae2018-10-30 13:19:49 +00003557 " --append Use appendvfs to append database to the end of FILE",
drha751f392018-10-30 15:31:22 +00003558#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00003559 " --deserialize Load into memory useing sqlite3_deserialize()",
drhe2754c12019-08-26 12:50:01 +00003560 " --hexdb Load the output of \"dbtotxt\" as an in-memory db",
drh6ca64482019-01-22 16:06:20 +00003561 " --maxsize N Maximum size for --hexdb or --deserialized database",
drha751f392018-10-30 15:31:22 +00003562#endif
drh60f34ae2018-10-30 13:19:49 +00003563 " --new Initialize FILE to an empty database",
3564 " --readonly Open FILE readonly",
3565 " --zip FILE is a ZIP archive",
drh98aa2ab2018-09-26 16:53:51 +00003566 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
3567 " If FILE begins with '|' then open it as a pipe.",
drh9cb02642019-02-28 20:10:52 +00003568 ".parameter CMD ... Manage SQL parameter bindings",
3569 " clear Erase all bindings",
3570 " init Initialize the TEMP table that holds bindings",
3571 " list List the current parameter bindings",
3572 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
drhe2754c12019-08-26 12:50:01 +00003573 " PARAMETER should start with one of: $ : @ ?",
drh9cb02642019-02-28 20:10:52 +00003574 " unset PARAMETER Remove PARAMETER from the binding table",
drh98aa2ab2018-09-26 16:53:51 +00003575 ".print STRING... Print literal STRING",
drh569b1d92019-02-05 20:51:41 +00003576#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00003577 ".progress N Invoke progress handler after every N opcodes",
3578 " --limit N Interrupt after N progress callbacks",
3579 " --once Do no more than one progress interrupt",
3580 " --quiet|-q No output except at interrupts",
3581 " --reset Reset the count for each input and interrupt",
drh569b1d92019-02-05 20:51:41 +00003582#endif
drh98aa2ab2018-09-26 16:53:51 +00003583 ".prompt MAIN CONTINUE Replace the standard prompts",
3584 ".quit Exit this program",
3585 ".read FILE Read input from FILE",
dan1b162162019-04-27 20:15:15 +00003586#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
dan42ebb012019-04-27 18:47:03 +00003587 ".recover Recover as much data as possible from corrupt db.",
drhe2754c12019-08-26 12:50:01 +00003588 " --freelist-corrupt Assume the freelist is corrupt",
3589 " --recovery-db NAME Store recovery metadata in database file NAME",
3590 " --lost-and-found TABLE Alternative name for the lost-and-found table",
dan8cce6b82019-09-14 16:44:51 +00003591 " --no-rowids Do not attempt to recover rowid values",
3592 " that are not also INTEGER PRIMARY KEYs",
dan1b162162019-04-27 20:15:15 +00003593#endif
drh98aa2ab2018-09-26 16:53:51 +00003594 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
3595 ".save FILE Write in-memory database into FILE",
3596 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
3597 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
3598 " Options:",
3599 " --indent Try to pretty-print the schema",
drheb7f2a02018-09-26 18:02:32 +00003600 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
3601 " Options:",
3602 " --init Create a new SELFTEST table",
3603 " -v Verbose output",
drh98aa2ab2018-09-26 16:53:51 +00003604 ".separator COL ?ROW? Change the column and row separators",
drh2ce15c32017-07-11 13:34:40 +00003605#if defined(SQLITE_ENABLE_SESSION)
drheb7f2a02018-09-26 18:02:32 +00003606 ".session ?NAME? CMD ... Create or control sessions",
3607 " Subcommands:",
3608 " attach TABLE Attach TABLE",
3609 " changeset FILE Write a changeset into FILE",
3610 " close Close one session",
3611 " enable ?BOOLEAN? Set or query the enable bit",
3612 " filter GLOB... Reject tables matching GLOBs",
3613 " indirect ?BOOLEAN? Mark or query the indirect status",
3614 " isempty Query whether the session is empty",
3615 " list List currently open session names",
3616 " open DB NAME Open a new session on DB",
3617 " patchset FILE Write a patchset into FILE",
3618 " If ?NAME? is omitted, the first defined session is used.",
drh2ce15c32017-07-11 13:34:40 +00003619#endif
drheb7f2a02018-09-26 18:02:32 +00003620 ".sha3sum ... Compute a SHA3 hash of database content",
3621 " Options:",
3622 " --schema Also hash the sqlite_master table",
3623 " --sha3-224 Use the sha3-224 algorithm",
drhe2754c12019-08-26 12:50:01 +00003624 " --sha3-256 Use the sha3-256 algorithm (default)",
drheb7f2a02018-09-26 18:02:32 +00003625 " --sha3-384 Use the sha3-384 algorithm",
3626 " --sha3-512 Use the sha3-512 algorithm",
3627 " Any other argument is a LIKE pattern for tables to hash",
drh04a28c32018-01-31 01:38:44 +00003628#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003629 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003630#endif
drh98aa2ab2018-09-26 16:53:51 +00003631 ".show Show the current values for various settings",
3632 ".stats ?on|off? Show stats or turn stats on or off",
drh04a28c32018-01-31 01:38:44 +00003633#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003634 ".system CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003635#endif
drh98aa2ab2018-09-26 16:53:51 +00003636 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
3637 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
drhd985f722019-06-05 14:29:53 +00003638 ".testctrl CMD ... Run various sqlite3_test_control() operations",
3639 " Run \".testctrl\" with no arguments for details",
drh98aa2ab2018-09-26 16:53:51 +00003640 ".timeout MS Try opening locked tables for MS milliseconds",
3641 ".timer on|off Turn SQL timer on or off",
drh707821f2018-12-05 13:39:06 +00003642#ifndef SQLITE_OMIT_TRACE
3643 ".trace ?OPTIONS? Output each SQL statement as it is run",
3644 " FILE Send output to FILE",
3645 " stdout Send output to stdout",
3646 " stderr Send output to stderr",
3647 " off Disable tracing",
3648 " --expanded Expand query parameters",
3649#ifdef SQLITE_ENABLE_NORMALIZE
3650 " --normalized Normal the SQL statements",
3651#endif
3652 " --plain Show SQL as it is input",
3653 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
3654 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
3655 " --row Trace each row (SQLITE_TRACE_ROW)",
3656 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
3657#endif /* SQLITE_OMIT_TRACE */
drhcc5979d2019-08-16 22:58:29 +00003658#ifdef SQLITE_DEBUG
3659 ".unmodule NAME ... Unregister virtual table modules",
drh5df84282019-08-17 19:45:25 +00003660 " --allexcept Unregister everything except those named",
drhcc5979d2019-08-16 22:58:29 +00003661#endif
drh98aa2ab2018-09-26 16:53:51 +00003662 ".vfsinfo ?AUX? Information about the top-level VFS",
3663 ".vfslist List all available VFSes",
3664 ".vfsname ?AUX? Print the name of the VFS stack",
3665 ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
3666 " Negative values right-justify",
3667};
3668
3669/*
3670** Output help text.
3671**
3672** zPattern describes the set of commands for which help text is provided.
3673** If zPattern is NULL, then show all commands, but only give a one-line
3674** description of each.
3675**
3676** Return the number of matches.
3677*/
3678static int showHelp(FILE *out, const char *zPattern){
drhe93f8262018-10-11 16:53:37 +00003679 int i = 0;
3680 int j = 0;
drh98aa2ab2018-09-26 16:53:51 +00003681 int n = 0;
3682 char *zPat;
drh488cddf2018-10-06 14:38:17 +00003683 if( zPattern==0
3684 || zPattern[0]=='0'
3685 || strcmp(zPattern,"-a")==0
3686 || strcmp(zPattern,"-all")==0
3687 ){
drh98aa2ab2018-09-26 16:53:51 +00003688 /* Show all commands, but only one line per command */
drh488cddf2018-10-06 14:38:17 +00003689 if( zPattern==0 ) zPattern = "";
drh98aa2ab2018-09-26 16:53:51 +00003690 for(i=0; i<ArraySize(azHelp); i++){
drh488cddf2018-10-06 14:38:17 +00003691 if( azHelp[i][0]=='.' || zPattern[0] ){
drh98aa2ab2018-09-26 16:53:51 +00003692 utf8_printf(out, "%s\n", azHelp[i]);
3693 n++;
3694 }
3695 }
3696 }else{
3697 /* Look for commands that for which zPattern is an exact prefix */
3698 zPat = sqlite3_mprintf(".%s*", zPattern);
3699 for(i=0; i<ArraySize(azHelp); i++){
3700 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3701 utf8_printf(out, "%s\n", azHelp[i]);
drheb7f2a02018-09-26 18:02:32 +00003702 j = i+1;
drh98aa2ab2018-09-26 16:53:51 +00003703 n++;
3704 }
3705 }
3706 sqlite3_free(zPat);
drheb7f2a02018-09-26 18:02:32 +00003707 if( n ){
3708 if( n==1 ){
3709 /* when zPattern is a prefix of exactly one command, then include the
3710 ** details of that command, which should begin at offset j */
3711 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3712 utf8_printf(out, "%s\n", azHelp[j]);
3713 j++;
3714 }
3715 }
3716 return n;
3717 }
3718 /* Look for commands that contain zPattern anywhere. Show the complete
3719 ** text of all commands that match. */
drh98aa2ab2018-09-26 16:53:51 +00003720 zPat = sqlite3_mprintf("%%%s%%", zPattern);
3721 for(i=0; i<ArraySize(azHelp); i++){
3722 if( azHelp[i][0]=='.' ) j = i;
3723 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3724 utf8_printf(out, "%s\n", azHelp[j]);
3725 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3726 j++;
3727 utf8_printf(out, "%s\n", azHelp[j]);
3728 }
3729 i = j;
3730 n++;
3731 }
3732 }
3733 sqlite3_free(zPat);
3734 }
3735 return n;
3736}
drh2ce15c32017-07-11 13:34:40 +00003737
drh2ce15c32017-07-11 13:34:40 +00003738/* Forward reference */
drh60379d42018-12-13 18:30:01 +00003739static int process_input(ShellState *p);
drh2ce15c32017-07-11 13:34:40 +00003740
3741/*
3742** Read the content of file zName into memory obtained from sqlite3_malloc64()
3743** and return a pointer to the buffer. The caller is responsible for freeing
3744** the memory.
3745**
3746** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3747** read.
3748**
3749** For convenience, a nul-terminator byte is always appended to the data read
3750** from the file before the buffer is returned. This byte is not included in
3751** the final value of (*pnByte), if applicable.
3752**
3753** NULL is returned if any error is encountered. The final value of *pnByte
3754** is undefined in this case.
3755*/
3756static char *readFile(const char *zName, int *pnByte){
3757 FILE *in = fopen(zName, "rb");
3758 long nIn;
3759 size_t nRead;
3760 char *pBuf;
3761 if( in==0 ) return 0;
3762 fseek(in, 0, SEEK_END);
3763 nIn = ftell(in);
3764 rewind(in);
3765 pBuf = sqlite3_malloc64( nIn+1 );
drh1dbb1472018-10-11 10:37:24 +00003766 if( pBuf==0 ){ fclose(in); return 0; }
drh2ce15c32017-07-11 13:34:40 +00003767 nRead = fread(pBuf, nIn, 1, in);
3768 fclose(in);
3769 if( nRead!=1 ){
3770 sqlite3_free(pBuf);
3771 return 0;
3772 }
3773 pBuf[nIn] = 0;
3774 if( pnByte ) *pnByte = nIn;
3775 return pBuf;
3776}
3777
3778#if defined(SQLITE_ENABLE_SESSION)
3779/*
3780** Close a single OpenSession object and release all of its associated
3781** resources.
3782*/
3783static void session_close(OpenSession *pSession){
3784 int i;
3785 sqlite3session_delete(pSession->p);
3786 sqlite3_free(pSession->zName);
3787 for(i=0; i<pSession->nFilter; i++){
3788 sqlite3_free(pSession->azFilter[i]);
3789 }
3790 sqlite3_free(pSession->azFilter);
3791 memset(pSession, 0, sizeof(OpenSession));
3792}
3793#endif
3794
3795/*
3796** Close all OpenSession objects and release all associated resources.
3797*/
3798#if defined(SQLITE_ENABLE_SESSION)
3799static void session_close_all(ShellState *p){
3800 int i;
3801 for(i=0; i<p->nSession; i++){
3802 session_close(&p->aSession[i]);
3803 }
3804 p->nSession = 0;
3805}
3806#else
3807# define session_close_all(X)
3808#endif
3809
3810/*
3811** Implementation of the xFilter function for an open session. Omit
3812** any tables named by ".session filter" but let all other table through.
3813*/
3814#if defined(SQLITE_ENABLE_SESSION)
3815static int session_filter(void *pCtx, const char *zTab){
3816 OpenSession *pSession = (OpenSession*)pCtx;
3817 int i;
3818 for(i=0; i<pSession->nFilter; i++){
3819 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3820 }
3821 return 1;
3822}
3823#endif
3824
3825/*
drh1fa6d9f2018-01-06 21:46:01 +00003826** Try to deduce the type of file for zName based on its content. Return
3827** one of the SHELL_OPEN_* constants.
drh1bf208c2018-03-09 21:54:01 +00003828**
3829** If the file does not exist or is empty but its name looks like a ZIP
3830** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3831** Otherwise, assume an ordinary database regardless of the filename if
3832** the type cannot be determined from content.
drh1fa6d9f2018-01-06 21:46:01 +00003833*/
drhfc97c1c2018-05-14 00:41:12 +00003834int deduceDatabaseType(const char *zName, int dfltZip){
drh1fa6d9f2018-01-06 21:46:01 +00003835 FILE *f = fopen(zName, "rb");
3836 size_t n;
3837 int rc = SHELL_OPEN_UNSPEC;
3838 char zBuf[100];
drh1bf208c2018-03-09 21:54:01 +00003839 if( f==0 ){
drhbe4ccb22018-05-17 20:04:24 +00003840 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3841 return SHELL_OPEN_ZIPFILE;
3842 }else{
3843 return SHELL_OPEN_NORMAL;
3844 }
drh1bf208c2018-03-09 21:54:01 +00003845 }
drh2b3c4af2018-10-30 14:36:21 +00003846 n = fread(zBuf, 16, 1, f);
3847 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
3848 fclose(f);
3849 return SHELL_OPEN_NORMAL;
3850 }
drh1fa6d9f2018-01-06 21:46:01 +00003851 fseek(f, -25, SEEK_END);
3852 n = fread(zBuf, 25, 1, f);
3853 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3854 rc = SHELL_OPEN_APPENDVFS;
3855 }else{
3856 fseek(f, -22, SEEK_END);
3857 n = fread(zBuf, 22, 1, f);
3858 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3859 && zBuf[3]==0x06 ){
3860 rc = SHELL_OPEN_ZIPFILE;
drh1bf208c2018-03-09 21:54:01 +00003861 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
mistachkina3926f42018-05-14 12:23:04 +00003862 rc = SHELL_OPEN_ZIPFILE;
drh1fa6d9f2018-01-06 21:46:01 +00003863 }
3864 }
3865 fclose(f);
3866 return rc;
3867}
3868
drh33746482018-12-13 15:06:26 +00003869#ifdef SQLITE_ENABLE_DESERIALIZE
3870/*
3871** Reconstruct an in-memory database using the output from the "dbtotxt"
3872** program. Read content from the file in p->zDbFilename. If p->zDbFilename
3873** is 0, then read from standard input.
3874*/
3875static unsigned char *readHexDb(ShellState *p, int *pnData){
3876 unsigned char *a = 0;
drh2c8ee022018-12-13 18:59:30 +00003877 int nLine;
drh33746482018-12-13 15:06:26 +00003878 int n = 0;
3879 int pgsz = 0;
3880 int iOffset = 0;
3881 int j, k;
3882 int rc;
3883 FILE *in;
drh3ea557e2019-04-23 15:30:58 +00003884 unsigned int x[16];
drh2c8ee022018-12-13 18:59:30 +00003885 char zLine[1000];
drh33746482018-12-13 15:06:26 +00003886 if( p->zDbFilename ){
3887 in = fopen(p->zDbFilename, "r");
3888 if( in==0 ){
3889 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
3890 return 0;
3891 }
drh2c8ee022018-12-13 18:59:30 +00003892 nLine = 0;
drh33746482018-12-13 15:06:26 +00003893 }else{
drh60379d42018-12-13 18:30:01 +00003894 in = p->in;
drh2c8ee022018-12-13 18:59:30 +00003895 nLine = p->lineno;
drh5bf46442019-05-03 02:41:36 +00003896 if( in==0 ) in = stdin;
drh33746482018-12-13 15:06:26 +00003897 }
3898 *pnData = 0;
drh2c8ee022018-12-13 18:59:30 +00003899 nLine++;
drh33746482018-12-13 15:06:26 +00003900 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
3901 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
3902 if( rc!=2 ) goto readHexDb_error;
drh68feae52019-05-09 11:18:41 +00003903 if( n<0 ) goto readHexDb_error;
drh09ea1252019-07-17 15:05:16 +00003904 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error;
3905 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */
drh68feae52019-05-09 11:18:41 +00003906 a = sqlite3_malloc( n ? n : 1 );
drh33746482018-12-13 15:06:26 +00003907 if( a==0 ){
3908 utf8_printf(stderr, "Out of memory!\n");
3909 goto readHexDb_error;
3910 }
3911 memset(a, 0, n);
3912 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
3913 utf8_printf(stderr, "invalid pagesize\n");
3914 goto readHexDb_error;
3915 }
drh2c8ee022018-12-13 18:59:30 +00003916 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
drh33746482018-12-13 15:06:26 +00003917 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
3918 if( rc==2 ){
3919 iOffset = k;
3920 continue;
3921 }
3922 if( strncmp(zLine, "| end ", 6)==0 ){
3923 break;
3924 }
drh3ea557e2019-04-23 15:30:58 +00003925 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 +00003926 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
3927 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
3928 if( rc==17 ){
3929 k = iOffset+j;
drhf354e772018-12-13 22:58:52 +00003930 if( k+16<=n ){
drh3ea557e2019-04-23 15:30:58 +00003931 int ii;
3932 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
drh33746482018-12-13 15:06:26 +00003933 }
drh33746482018-12-13 15:06:26 +00003934 }
3935 }
3936 *pnData = n;
drh2c8ee022018-12-13 18:59:30 +00003937 if( in!=p->in ){
3938 fclose(in);
3939 }else{
3940 p->lineno = nLine;
3941 }
drh33746482018-12-13 15:06:26 +00003942 return a;
3943
3944readHexDb_error:
drh68feae52019-05-09 11:18:41 +00003945 if( in!=p->in ){
drh33746482018-12-13 15:06:26 +00003946 fclose(in);
3947 }else{
drh60379d42018-12-13 18:30:01 +00003948 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
drh2c8ee022018-12-13 18:59:30 +00003949 nLine++;
drh33746482018-12-13 15:06:26 +00003950 if(strncmp(zLine, "| end ", 6)==0 ) break;
3951 }
drh2c8ee022018-12-13 18:59:30 +00003952 p->lineno = nLine;
drh33746482018-12-13 15:06:26 +00003953 }
3954 sqlite3_free(a);
3955 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
3956 return 0;
3957}
3958#endif /* SQLITE_ENABLE_DESERIALIZE */
3959
danb1825882019-04-23 20:48:32 +00003960/*
dan9c014f82019-04-25 19:23:15 +00003961** Scalar function "shell_int32". The first argument to this function
3962** must be a blob. The second a non-negative integer. This function
3963** reads and returns a 32-bit big-endian integer from byte
3964** offset (4*<arg2>) of the blob.
3965*/
3966static void shellInt32(
3967 sqlite3_context *context,
3968 int argc,
3969 sqlite3_value **argv
3970){
3971 const unsigned char *pBlob;
3972 int nBlob;
3973 int iInt;
drh9546c762019-05-10 17:50:33 +00003974
3975 UNUSED_PARAMETER(argc);
dan9c014f82019-04-25 19:23:15 +00003976 nBlob = sqlite3_value_bytes(argv[0]);
3977 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
3978 iInt = sqlite3_value_int(argv[1]);
3979
3980 if( iInt>=0 && (iInt+1)*4<=nBlob ){
3981 const unsigned char *a = &pBlob[iInt*4];
3982 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
3983 + ((sqlite3_int64)a[1]<<16)
3984 + ((sqlite3_int64)a[2]<< 8)
3985 + ((sqlite3_int64)a[3]<< 0);
3986 sqlite3_result_int64(context, iVal);
3987 }
3988}
3989
3990/*
drha2de66c2019-08-06 20:26:17 +00003991** Scalar function "shell_idquote(X)" returns string X quoted as an identifier,
3992** using "..." with internal double-quote characters doubled.
3993*/
3994static void shellIdQuote(
3995 sqlite3_context *context,
3996 int argc,
3997 sqlite3_value **argv
3998){
3999 const char *zName = (const char*)sqlite3_value_text(argv[0]);
drh51755a72019-08-08 19:40:29 +00004000 UNUSED_PARAMETER(argc);
drha2de66c2019-08-06 20:26:17 +00004001 if( zName ){
4002 char *z = sqlite3_mprintf("\"%w\"", zName);
4003 sqlite3_result_text(context, z, -1, sqlite3_free);
4004 }
4005}
4006
4007/*
danb1825882019-04-23 20:48:32 +00004008** Scalar function "shell_escape_crnl" used by the .recover command.
4009** The argument passed to this function is the output of built-in
4010** function quote(). If the first character of the input is "'",
4011** indicating that the value passed to quote() was a text value,
4012** then this function searches the input for "\n" and "\r" characters
4013** and adds a wrapper similar to the following:
4014**
4015** replace(replace(<input>, '\n', char(10), '\r', char(13));
4016**
4017** Or, if the first character of the input is not "'", then a copy
4018** of the input is returned.
4019*/
4020static void shellEscapeCrnl(
4021 sqlite3_context *context,
4022 int argc,
4023 sqlite3_value **argv
4024){
4025 const char *zText = (const char*)sqlite3_value_text(argv[0]);
drh9546c762019-05-10 17:50:33 +00004026 UNUSED_PARAMETER(argc);
danb1825882019-04-23 20:48:32 +00004027 if( zText[0]=='\'' ){
4028 int nText = sqlite3_value_bytes(argv[0]);
4029 int i;
4030 char zBuf1[20];
4031 char zBuf2[20];
4032 const char *zNL = 0;
4033 const char *zCR = 0;
4034 int nCR = 0;
4035 int nNL = 0;
4036
4037 for(i=0; zText[i]; i++){
4038 if( zNL==0 && zText[i]=='\n' ){
4039 zNL = unused_string(zText, "\\n", "\\012", zBuf1);
4040 nNL = (int)strlen(zNL);
4041 }
4042 if( zCR==0 && zText[i]=='\r' ){
4043 zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4044 nCR = (int)strlen(zCR);
4045 }
4046 }
4047
4048 if( zNL || zCR ){
4049 int iOut = 0;
4050 i64 nMax = (nNL > nCR) ? nNL : nCR;
dan51f5ffa2019-04-29 11:41:46 +00004051 i64 nAlloc = nMax * nText + (nMax+64)*2;
danb1825882019-04-23 20:48:32 +00004052 char *zOut = (char*)sqlite3_malloc64(nAlloc);
4053 if( zOut==0 ){
4054 sqlite3_result_error_nomem(context);
4055 return;
4056 }
4057
4058 if( zNL && zCR ){
4059 memcpy(&zOut[iOut], "replace(replace(", 16);
4060 iOut += 16;
4061 }else{
4062 memcpy(&zOut[iOut], "replace(", 8);
4063 iOut += 8;
4064 }
4065 for(i=0; zText[i]; i++){
4066 if( zText[i]=='\n' ){
4067 memcpy(&zOut[iOut], zNL, nNL);
4068 iOut += nNL;
4069 }else if( zText[i]=='\r' ){
4070 memcpy(&zOut[iOut], zCR, nCR);
4071 iOut += nCR;
4072 }else{
4073 zOut[iOut] = zText[i];
4074 iOut++;
4075 }
4076 }
4077
4078 if( zNL ){
4079 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4080 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4081 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4082 }
4083 if( zCR ){
4084 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4085 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4086 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4087 }
4088
4089 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4090 sqlite3_free(zOut);
4091 return;
4092 }
4093 }
4094
4095 sqlite3_result_value(context, argv[0]);
4096}
4097
drhbe4ccb22018-05-17 20:04:24 +00004098/* Flags for open_db().
4099**
4100** The default behavior of open_db() is to exit(1) if the database fails to
4101** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4102** but still returns without calling exit.
4103**
4104** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4105** ZIP archive if the file does not exist or is empty and its name matches
4106** the *.zip pattern.
4107*/
4108#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
4109#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
4110
drh1fa6d9f2018-01-06 21:46:01 +00004111/*
drh2ce15c32017-07-11 13:34:40 +00004112** Make sure the database is open. If it is not, then open it. If
4113** the database fails to open, print an error message and exit.
4114*/
drhbe4ccb22018-05-17 20:04:24 +00004115static void open_db(ShellState *p, int openFlags){
drh2ce15c32017-07-11 13:34:40 +00004116 if( p->db==0 ){
drhf2072d12018-05-11 15:10:11 +00004117 if( p->openMode==SHELL_OPEN_UNSPEC ){
4118 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
4119 p->openMode = SHELL_OPEN_NORMAL;
drhbe4ccb22018-05-17 20:04:24 +00004120 }else{
4121 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
4122 (openFlags & OPEN_DB_ZIPFILE)!=0);
drhf2072d12018-05-11 15:10:11 +00004123 }
drh1fa6d9f2018-01-06 21:46:01 +00004124 }
4125 switch( p->openMode ){
4126 case SHELL_OPEN_APPENDVFS: {
4127 sqlite3_open_v2(p->zDbFilename, &p->db,
4128 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
4129 break;
4130 }
drh33746482018-12-13 15:06:26 +00004131 case SHELL_OPEN_HEXDB:
drh60f34ae2018-10-30 13:19:49 +00004132 case SHELL_OPEN_DESERIALIZE: {
4133 sqlite3_open(0, &p->db);
4134 break;
4135 }
drh1fa6d9f2018-01-06 21:46:01 +00004136 case SHELL_OPEN_ZIPFILE: {
4137 sqlite3_open(":memory:", &p->db);
4138 break;
4139 }
drhee269a62018-02-14 23:27:43 +00004140 case SHELL_OPEN_READONLY: {
4141 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
4142 break;
4143 }
drh1fa6d9f2018-01-06 21:46:01 +00004144 case SHELL_OPEN_UNSPEC:
4145 case SHELL_OPEN_NORMAL: {
4146 sqlite3_open(p->zDbFilename, &p->db);
4147 break;
4148 }
4149 }
drh2ce15c32017-07-11 13:34:40 +00004150 globalDb = p->db;
4151 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4152 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4153 p->zDbFilename, sqlite3_errmsg(p->db));
drhf25cc4f2019-01-04 14:29:21 +00004154 if( openFlags & OPEN_DB_KEEPALIVE ){
4155 sqlite3_open(":memory:", &p->db);
4156 return;
4157 }
drh2ce15c32017-07-11 13:34:40 +00004158 exit(1);
4159 }
4160#ifndef SQLITE_OMIT_LOAD_EXTENSION
4161 sqlite3_enable_load_extension(p->db, 1);
4162#endif
4163 sqlite3_fileio_init(p->db, 0, 0);
4164 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00004165 sqlite3_completion_init(p->db, 0, 0);
dan1b162162019-04-27 20:15:15 +00004166#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
dan68cb86e2019-04-20 20:57:28 +00004167 sqlite3_dbdata_init(p->db, 0, 0);
dan1b162162019-04-27 20:15:15 +00004168#endif
dan72afc3c2017-12-05 18:32:40 +00004169#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00004170 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00004171 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00004172#endif
drhceba7922018-01-01 21:28:25 +00004173 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00004174 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00004175 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4176 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00004177 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4178 shellPutsFunc, 0, 0);
danb1825882019-04-23 20:48:32 +00004179 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4180 shellEscapeCrnl, 0, 0);
dan9c014f82019-04-25 19:23:15 +00004181 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4182 shellInt32, 0, 0);
drha2de66c2019-08-06 20:26:17 +00004183 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
4184 shellIdQuote, 0, 0);
drh04a28c32018-01-31 01:38:44 +00004185#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00004186 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4187 editFunc, 0, 0);
4188 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4189 editFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00004190#endif
drh1fa6d9f2018-01-06 21:46:01 +00004191 if( p->openMode==SHELL_OPEN_ZIPFILE ){
4192 char *zSql = sqlite3_mprintf(
4193 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
4194 sqlite3_exec(p->db, zSql, 0, 0, 0);
4195 sqlite3_free(zSql);
drha751f392018-10-30 15:31:22 +00004196 }
4197#ifdef SQLITE_ENABLE_DESERIALIZE
drh33746482018-12-13 15:06:26 +00004198 else
4199 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
mistachkin99490932018-12-17 22:19:57 +00004200 int rc;
drh60f34ae2018-10-30 13:19:49 +00004201 int nData = 0;
drh33746482018-12-13 15:06:26 +00004202 unsigned char *aData;
4203 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4204 aData = (unsigned char*)readFile(p->zDbFilename, &nData);
4205 }else{
4206 aData = readHexDb(p, &nData);
4207 if( aData==0 ){
drh33746482018-12-13 15:06:26 +00004208 return;
4209 }
4210 }
mistachkin99490932018-12-17 22:19:57 +00004211 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
drh60f34ae2018-10-30 13:19:49 +00004212 SQLITE_DESERIALIZE_RESIZEABLE |
4213 SQLITE_DESERIALIZE_FREEONCLOSE);
4214 if( rc ){
4215 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4216 }
drh6ca64482019-01-22 16:06:20 +00004217 if( p->szMax>0 ){
4218 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4219 }
drh1fa6d9f2018-01-06 21:46:01 +00004220 }
drha751f392018-10-30 15:31:22 +00004221#endif
drh2ce15c32017-07-11 13:34:40 +00004222 }
4223}
4224
drh9e804032018-05-18 17:11:50 +00004225/*
4226** Attempt to close the databaes connection. Report errors.
4227*/
4228void close_db(sqlite3 *db){
4229 int rc = sqlite3_close(db);
4230 if( rc ){
4231 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4232 rc, sqlite3_errmsg(db));
4233 }
4234}
4235
drh56eb09b2017-07-11 13:59:07 +00004236#if HAVE_READLINE || HAVE_EDITLINE
4237/*
4238** Readline completion callbacks
4239*/
4240static char *readline_completion_generator(const char *text, int state){
4241 static sqlite3_stmt *pStmt = 0;
4242 char *zRet;
4243 if( state==0 ){
4244 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00004245 sqlite3_finalize(pStmt);
4246 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4247 " FROM completion(%Q) ORDER BY 1", text);
4248 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4249 sqlite3_free(zSql);
4250 }
4251 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00004252 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00004253 }else{
4254 sqlite3_finalize(pStmt);
4255 pStmt = 0;
4256 zRet = 0;
4257 }
4258 return zRet;
4259}
4260static char **readline_completion(const char *zText, int iStart, int iEnd){
4261 rl_attempted_completion_over = 1;
4262 return rl_completion_matches(zText, readline_completion_generator);
4263}
4264
4265#elif HAVE_LINENOISE
4266/*
4267** Linenoise completion callback
4268*/
4269static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00004270 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00004271 int i, iStart;
4272 sqlite3_stmt *pStmt = 0;
4273 char *zSql;
4274 char zBuf[1000];
4275
4276 if( nLine>sizeof(zBuf)-30 ) return;
drh1615c372018-05-12 23:56:22 +00004277 if( zLine[0]=='.' || zLine[0]=='#') return;
drh56eb09b2017-07-11 13:59:07 +00004278 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4279 if( i==nLine-1 ) return;
4280 iStart = i+1;
4281 memcpy(zBuf, zLine, iStart);
4282 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4283 " FROM completion(%Q,%Q) ORDER BY 1",
4284 &zLine[iStart], zLine);
4285 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4286 sqlite3_free(zSql);
4287 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4288 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4289 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4290 int nCompletion = sqlite3_column_bytes(pStmt, 0);
4291 if( iStart+nCompletion < sizeof(zBuf)-1 ){
4292 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4293 linenoiseAddCompletion(lc, zBuf);
4294 }
4295 }
4296 sqlite3_finalize(pStmt);
4297}
4298#endif
4299
drh2ce15c32017-07-11 13:34:40 +00004300/*
4301** Do C-language style dequoting.
4302**
4303** \a -> alarm
4304** \b -> backspace
4305** \t -> tab
4306** \n -> newline
4307** \v -> vertical tab
4308** \f -> form feed
4309** \r -> carriage return
4310** \s -> space
4311** \" -> "
4312** \' -> '
4313** \\ -> backslash
4314** \NNN -> ascii character NNN in octal
4315*/
4316static void resolve_backslashes(char *z){
4317 int i, j;
4318 char c;
4319 while( *z && *z!='\\' ) z++;
4320 for(i=j=0; (c = z[i])!=0; i++, j++){
4321 if( c=='\\' && z[i+1]!=0 ){
4322 c = z[++i];
4323 if( c=='a' ){
4324 c = '\a';
4325 }else if( c=='b' ){
4326 c = '\b';
4327 }else if( c=='t' ){
4328 c = '\t';
4329 }else if( c=='n' ){
4330 c = '\n';
4331 }else if( c=='v' ){
4332 c = '\v';
4333 }else if( c=='f' ){
4334 c = '\f';
4335 }else if( c=='r' ){
4336 c = '\r';
4337 }else if( c=='"' ){
4338 c = '"';
4339 }else if( c=='\'' ){
4340 c = '\'';
4341 }else if( c=='\\' ){
4342 c = '\\';
4343 }else if( c>='0' && c<='7' ){
4344 c -= '0';
4345 if( z[i+1]>='0' && z[i+1]<='7' ){
4346 i++;
4347 c = (c<<3) + z[i] - '0';
4348 if( z[i+1]>='0' && z[i+1]<='7' ){
4349 i++;
4350 c = (c<<3) + z[i] - '0';
4351 }
4352 }
4353 }
4354 }
4355 z[j] = c;
4356 }
4357 if( j<i ) z[j] = 0;
4358}
4359
4360/*
drh2ce15c32017-07-11 13:34:40 +00004361** Interpret zArg as either an integer or a boolean value. Return 1 or 0
4362** for TRUE and FALSE. Return the integer value if appropriate.
4363*/
4364static int booleanValue(const char *zArg){
4365 int i;
4366 if( zArg[0]=='0' && zArg[1]=='x' ){
4367 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4368 }else{
4369 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4370 }
4371 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4372 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4373 return 1;
4374 }
4375 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4376 return 0;
4377 }
4378 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4379 zArg);
4380 return 0;
4381}
4382
4383/*
4384** Set or clear a shell flag according to a boolean value.
4385*/
4386static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4387 if( booleanValue(zArg) ){
4388 ShellSetFlag(p, mFlag);
4389 }else{
4390 ShellClearFlag(p, mFlag);
4391 }
4392}
4393
4394/*
4395** Close an output file, assuming it is not stderr or stdout
4396*/
4397static void output_file_close(FILE *f){
4398 if( f && f!=stdout && f!=stderr ) fclose(f);
4399}
4400
4401/*
4402** Try to open an output file. The names "stdout" and "stderr" are
4403** recognized and do the right thing. NULL is returned if the output
4404** filename is "off".
4405*/
drha92a01a2018-01-10 22:15:37 +00004406static FILE *output_file_open(const char *zFile, int bTextMode){
drh2ce15c32017-07-11 13:34:40 +00004407 FILE *f;
4408 if( strcmp(zFile,"stdout")==0 ){
4409 f = stdout;
4410 }else if( strcmp(zFile, "stderr")==0 ){
4411 f = stderr;
4412 }else if( strcmp(zFile, "off")==0 ){
4413 f = 0;
4414 }else{
drha92a01a2018-01-10 22:15:37 +00004415 f = fopen(zFile, bTextMode ? "w" : "wb");
drh2ce15c32017-07-11 13:34:40 +00004416 if( f==0 ){
4417 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4418 }
4419 }
4420 return f;
4421}
4422
drh707821f2018-12-05 13:39:06 +00004423#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00004424/*
4425** A routine for handling output from sqlite3_trace().
4426*/
4427static int sql_trace_callback(
drh707821f2018-12-05 13:39:06 +00004428 unsigned mType, /* The trace type */
4429 void *pArg, /* The ShellState pointer */
4430 void *pP, /* Usually a pointer to sqlite_stmt */
4431 void *pX /* Auxiliary output */
drh2ce15c32017-07-11 13:34:40 +00004432){
drh707821f2018-12-05 13:39:06 +00004433 ShellState *p = (ShellState*)pArg;
4434 sqlite3_stmt *pStmt;
4435 const char *zSql;
4436 int nSql;
4437 if( p->traceOut==0 ) return 0;
4438 if( mType==SQLITE_TRACE_CLOSE ){
4439 utf8_printf(p->traceOut, "-- closing database connection\n");
4440 return 0;
4441 }
4442 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4443 zSql = (const char*)pX;
4444 }else{
4445 pStmt = (sqlite3_stmt*)pP;
4446 switch( p->eTraceType ){
4447 case SHELL_TRACE_EXPANDED: {
4448 zSql = sqlite3_expanded_sql(pStmt);
4449 break;
4450 }
4451#ifdef SQLITE_ENABLE_NORMALIZE
4452 case SHELL_TRACE_NORMALIZED: {
4453 zSql = sqlite3_normalized_sql(pStmt);
4454 break;
4455 }
4456#endif
4457 default: {
4458 zSql = sqlite3_sql(pStmt);
4459 break;
4460 }
4461 }
4462 }
4463 if( zSql==0 ) return 0;
4464 nSql = strlen30(zSql);
4465 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4466 switch( mType ){
4467 case SQLITE_TRACE_ROW:
4468 case SQLITE_TRACE_STMT: {
4469 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4470 break;
4471 }
4472 case SQLITE_TRACE_PROFILE: {
4473 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4474 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4475 break;
4476 }
drh2ce15c32017-07-11 13:34:40 +00004477 }
4478 return 0;
4479}
4480#endif
drh2ce15c32017-07-11 13:34:40 +00004481
4482/*
4483** A no-op routine that runs with the ".breakpoint" doc-command. This is
4484** a useful spot to set a debugger breakpoint.
4485*/
4486static void test_breakpoint(void){
4487 static int nCall = 0;
4488 nCall++;
4489}
4490
4491/*
4492** An object used to read a CSV and other files for import.
4493*/
4494typedef struct ImportCtx ImportCtx;
4495struct ImportCtx {
4496 const char *zFile; /* Name of the input file */
4497 FILE *in; /* Read the CSV text from this input stream */
4498 char *z; /* Accumulated text for a field */
4499 int n; /* Number of bytes in z */
4500 int nAlloc; /* Space allocated for z[] */
4501 int nLine; /* Current line number */
4502 int bNotFirst; /* True if one or more bytes already read */
4503 int cTerm; /* Character that terminated the most recent field */
4504 int cColSep; /* The column separator character. (Usually ",") */
4505 int cRowSep; /* The row separator character. (Usually "\n") */
4506};
4507
4508/* Append a single byte to z[] */
4509static void import_append_char(ImportCtx *p, int c){
4510 if( p->n+1>=p->nAlloc ){
4511 p->nAlloc += p->nAlloc + 100;
4512 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drh4b5345c2018-04-24 13:07:40 +00004513 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004514 }
4515 p->z[p->n++] = (char)c;
4516}
4517
4518/* Read a single field of CSV text. Compatible with rfc4180 and extended
4519** with the option of having a separator other than ",".
4520**
4521** + Input comes from p->in.
4522** + Store results in p->z of length p->n. Space to hold p->z comes
4523** from sqlite3_malloc64().
4524** + Use p->cSep as the column separator. The default is ",".
4525** + Use p->rSep as the row separator. The default is "\n".
4526** + Keep track of the line number in p->nLine.
4527** + Store the character that terminates the field in p->cTerm. Store
4528** EOF on end-of-file.
4529** + Report syntax errors on stderr
4530*/
4531static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4532 int c;
4533 int cSep = p->cColSep;
4534 int rSep = p->cRowSep;
4535 p->n = 0;
4536 c = fgetc(p->in);
4537 if( c==EOF || seenInterrupt ){
4538 p->cTerm = EOF;
4539 return 0;
4540 }
4541 if( c=='"' ){
4542 int pc, ppc;
4543 int startLine = p->nLine;
4544 int cQuote = c;
4545 pc = ppc = 0;
4546 while( 1 ){
4547 c = fgetc(p->in);
4548 if( c==rSep ) p->nLine++;
4549 if( c==cQuote ){
4550 if( pc==cQuote ){
4551 pc = 0;
4552 continue;
4553 }
4554 }
4555 if( (c==cSep && pc==cQuote)
4556 || (c==rSep && pc==cQuote)
4557 || (c==rSep && pc=='\r' && ppc==cQuote)
4558 || (c==EOF && pc==cQuote)
4559 ){
4560 do{ p->n--; }while( p->z[p->n]!=cQuote );
4561 p->cTerm = c;
4562 break;
4563 }
4564 if( pc==cQuote && c!='\r' ){
4565 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4566 p->zFile, p->nLine, cQuote);
4567 }
4568 if( c==EOF ){
4569 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4570 p->zFile, startLine, cQuote);
4571 p->cTerm = c;
4572 break;
4573 }
4574 import_append_char(p, c);
4575 ppc = pc;
4576 pc = c;
4577 }
4578 }else{
4579 /* If this is the first field being parsed and it begins with the
4580 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4581 if( (c&0xff)==0xef && p->bNotFirst==0 ){
4582 import_append_char(p, c);
4583 c = fgetc(p->in);
4584 if( (c&0xff)==0xbb ){
4585 import_append_char(p, c);
4586 c = fgetc(p->in);
4587 if( (c&0xff)==0xbf ){
4588 p->bNotFirst = 1;
4589 p->n = 0;
4590 return csv_read_one_field(p);
4591 }
4592 }
4593 }
4594 while( c!=EOF && c!=cSep && c!=rSep ){
4595 import_append_char(p, c);
4596 c = fgetc(p->in);
4597 }
4598 if( c==rSep ){
4599 p->nLine++;
4600 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4601 }
4602 p->cTerm = c;
4603 }
4604 if( p->z ) p->z[p->n] = 0;
4605 p->bNotFirst = 1;
4606 return p->z;
4607}
4608
4609/* Read a single field of ASCII delimited text.
4610**
4611** + Input comes from p->in.
4612** + Store results in p->z of length p->n. Space to hold p->z comes
4613** from sqlite3_malloc64().
4614** + Use p->cSep as the column separator. The default is "\x1F".
4615** + Use p->rSep as the row separator. The default is "\x1E".
4616** + Keep track of the row number in p->nLine.
4617** + Store the character that terminates the field in p->cTerm. Store
4618** EOF on end-of-file.
4619** + Report syntax errors on stderr
4620*/
4621static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4622 int c;
4623 int cSep = p->cColSep;
4624 int rSep = p->cRowSep;
4625 p->n = 0;
4626 c = fgetc(p->in);
4627 if( c==EOF || seenInterrupt ){
4628 p->cTerm = EOF;
4629 return 0;
4630 }
4631 while( c!=EOF && c!=cSep && c!=rSep ){
4632 import_append_char(p, c);
4633 c = fgetc(p->in);
4634 }
4635 if( c==rSep ){
4636 p->nLine++;
4637 }
4638 p->cTerm = c;
4639 if( p->z ) p->z[p->n] = 0;
4640 return p->z;
4641}
4642
4643/*
4644** Try to transfer data for table zTable. If an error is seen while
4645** moving forward, try to go backwards. The backwards movement won't
4646** work for WITHOUT ROWID tables.
4647*/
4648static void tryToCloneData(
4649 ShellState *p,
4650 sqlite3 *newDb,
4651 const char *zTable
4652){
4653 sqlite3_stmt *pQuery = 0;
4654 sqlite3_stmt *pInsert = 0;
4655 char *zQuery = 0;
4656 char *zInsert = 0;
4657 int rc;
4658 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00004659 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00004660 int k = 0;
4661 int cnt = 0;
4662 const int spinRate = 10000;
4663
4664 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4665 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4666 if( rc ){
4667 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4668 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4669 zQuery);
4670 goto end_data_xfer;
4671 }
4672 n = sqlite3_column_count(pQuery);
4673 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh4b5345c2018-04-24 13:07:40 +00004674 if( zInsert==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004675 sqlite3_snprintf(200+nTable,zInsert,
4676 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00004677 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00004678 for(j=1; j<n; j++){
4679 memcpy(zInsert+i, ",?", 2);
4680 i += 2;
4681 }
4682 memcpy(zInsert+i, ");", 3);
4683 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4684 if( rc ){
4685 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4686 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4687 zQuery);
4688 goto end_data_xfer;
4689 }
4690 for(k=0; k<2; k++){
4691 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4692 for(i=0; i<n; i++){
4693 switch( sqlite3_column_type(pQuery, i) ){
4694 case SQLITE_NULL: {
4695 sqlite3_bind_null(pInsert, i+1);
4696 break;
4697 }
4698 case SQLITE_INTEGER: {
4699 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4700 break;
4701 }
4702 case SQLITE_FLOAT: {
4703 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4704 break;
4705 }
4706 case SQLITE_TEXT: {
4707 sqlite3_bind_text(pInsert, i+1,
4708 (const char*)sqlite3_column_text(pQuery,i),
4709 -1, SQLITE_STATIC);
4710 break;
4711 }
4712 case SQLITE_BLOB: {
4713 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4714 sqlite3_column_bytes(pQuery,i),
4715 SQLITE_STATIC);
4716 break;
4717 }
4718 }
4719 } /* End for */
4720 rc = sqlite3_step(pInsert);
4721 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4722 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4723 sqlite3_errmsg(newDb));
4724 }
4725 sqlite3_reset(pInsert);
4726 cnt++;
4727 if( (cnt%spinRate)==0 ){
4728 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4729 fflush(stdout);
4730 }
4731 } /* End while */
4732 if( rc==SQLITE_DONE ) break;
4733 sqlite3_finalize(pQuery);
4734 sqlite3_free(zQuery);
4735 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4736 zTable);
4737 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4738 if( rc ){
4739 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4740 break;
4741 }
4742 } /* End for(k=0...) */
4743
4744end_data_xfer:
4745 sqlite3_finalize(pQuery);
4746 sqlite3_finalize(pInsert);
4747 sqlite3_free(zQuery);
4748 sqlite3_free(zInsert);
4749}
4750
4751
4752/*
4753** Try to transfer all rows of the schema that match zWhere. For
4754** each row, invoke xForEach() on the object defined by that row.
4755** If an error is encountered while moving forward through the
4756** sqlite_master table, try again moving backwards.
4757*/
4758static void tryToCloneSchema(
4759 ShellState *p,
4760 sqlite3 *newDb,
4761 const char *zWhere,
4762 void (*xForEach)(ShellState*,sqlite3*,const char*)
4763){
4764 sqlite3_stmt *pQuery = 0;
4765 char *zQuery = 0;
4766 int rc;
4767 const unsigned char *zName;
4768 const unsigned char *zSql;
4769 char *zErrMsg = 0;
4770
4771 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4772 " WHERE %s", zWhere);
4773 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4774 if( rc ){
4775 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4776 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4777 zQuery);
4778 goto end_schema_xfer;
4779 }
4780 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4781 zName = sqlite3_column_text(pQuery, 0);
4782 zSql = sqlite3_column_text(pQuery, 1);
4783 printf("%s... ", zName); fflush(stdout);
4784 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4785 if( zErrMsg ){
4786 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4787 sqlite3_free(zErrMsg);
4788 zErrMsg = 0;
4789 }
4790 if( xForEach ){
4791 xForEach(p, newDb, (const char*)zName);
4792 }
4793 printf("done\n");
4794 }
4795 if( rc!=SQLITE_DONE ){
4796 sqlite3_finalize(pQuery);
4797 sqlite3_free(zQuery);
4798 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4799 " WHERE %s ORDER BY rowid DESC", zWhere);
4800 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4801 if( rc ){
4802 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4803 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4804 zQuery);
4805 goto end_schema_xfer;
4806 }
4807 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4808 zName = sqlite3_column_text(pQuery, 0);
4809 zSql = sqlite3_column_text(pQuery, 1);
4810 printf("%s... ", zName); fflush(stdout);
4811 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4812 if( zErrMsg ){
4813 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4814 sqlite3_free(zErrMsg);
4815 zErrMsg = 0;
4816 }
4817 if( xForEach ){
4818 xForEach(p, newDb, (const char*)zName);
4819 }
4820 printf("done\n");
4821 }
4822 }
4823end_schema_xfer:
4824 sqlite3_finalize(pQuery);
4825 sqlite3_free(zQuery);
4826}
4827
4828/*
4829** Open a new database file named "zNewDb". Try to recover as much information
4830** as possible out of the main database (which might be corrupt) and write it
4831** into zNewDb.
4832*/
4833static void tryToClone(ShellState *p, const char *zNewDb){
4834 int rc;
4835 sqlite3 *newDb = 0;
4836 if( access(zNewDb,0)==0 ){
4837 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4838 return;
4839 }
4840 rc = sqlite3_open(zNewDb, &newDb);
4841 if( rc ){
4842 utf8_printf(stderr, "Cannot create output database: %s\n",
4843 sqlite3_errmsg(newDb));
4844 }else{
4845 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4846 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4847 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4848 tryToCloneSchema(p, newDb, "type!='table'", 0);
4849 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4850 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4851 }
drh9e804032018-05-18 17:11:50 +00004852 close_db(newDb);
drh2ce15c32017-07-11 13:34:40 +00004853}
4854
4855/*
drh13c20932018-01-10 21:41:55 +00004856** Change the output file back to stdout.
4857**
4858** If the p->doXdgOpen flag is set, that means the output was being
4859** redirected to a temporary file named by p->zTempFile. In that case,
4860** launch start/open/xdg-open on that temporary file.
drh2ce15c32017-07-11 13:34:40 +00004861*/
4862static void output_reset(ShellState *p){
4863 if( p->outfile[0]=='|' ){
4864#ifndef SQLITE_OMIT_POPEN
4865 pclose(p->out);
4866#endif
4867 }else{
4868 output_file_close(p->out);
drh04a28c32018-01-31 01:38:44 +00004869#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00004870 if( p->doXdgOpen ){
4871 const char *zXdgOpenCmd =
4872#if defined(_WIN32)
4873 "start";
4874#elif defined(__APPLE__)
4875 "open";
4876#else
4877 "xdg-open";
4878#endif
4879 char *zCmd;
4880 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
drha92a01a2018-01-10 22:15:37 +00004881 if( system(zCmd) ){
4882 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4883 }
drh13c20932018-01-10 21:41:55 +00004884 sqlite3_free(zCmd);
drh3c484e82018-01-10 22:27:21 +00004885 outputModePop(p);
drh13c20932018-01-10 21:41:55 +00004886 p->doXdgOpen = 0;
drhf9c7c4b2019-06-04 18:21:59 +00004887 sqlite3_sleep(100);
drh13c20932018-01-10 21:41:55 +00004888 }
drh04a28c32018-01-31 01:38:44 +00004889#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00004890 }
4891 p->outfile[0] = 0;
4892 p->out = stdout;
4893}
4894
4895/*
4896** Run an SQL command and return the single integer result.
4897*/
4898static int db_int(ShellState *p, const char *zSql){
4899 sqlite3_stmt *pStmt;
4900 int res = 0;
4901 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4902 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4903 res = sqlite3_column_int(pStmt,0);
4904 }
4905 sqlite3_finalize(pStmt);
4906 return res;
4907}
4908
4909/*
4910** Convert a 2-byte or 4-byte big-endian integer into a native integer
4911*/
4912static unsigned int get2byteInt(unsigned char *a){
4913 return (a[0]<<8) + a[1];
4914}
4915static unsigned int get4byteInt(unsigned char *a){
4916 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4917}
4918
4919/*
4920** Implementation of the ".info" command.
4921**
4922** Return 1 on error, 2 to exit, and 0 otherwise.
4923*/
4924static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4925 static const struct { const char *zName; int ofst; } aField[] = {
4926 { "file change counter:", 24 },
4927 { "database page count:", 28 },
4928 { "freelist page count:", 36 },
4929 { "schema cookie:", 40 },
4930 { "schema format:", 44 },
4931 { "default cache size:", 48 },
4932 { "autovacuum top root:", 52 },
4933 { "incremental vacuum:", 64 },
4934 { "text encoding:", 56 },
4935 { "user version:", 60 },
4936 { "application id:", 68 },
4937 { "software version:", 96 },
4938 };
4939 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4940 { "number of tables:",
4941 "SELECT count(*) FROM %s WHERE type='table'" },
4942 { "number of indexes:",
4943 "SELECT count(*) FROM %s WHERE type='index'" },
4944 { "number of triggers:",
4945 "SELECT count(*) FROM %s WHERE type='trigger'" },
4946 { "number of views:",
4947 "SELECT count(*) FROM %s WHERE type='view'" },
4948 { "schema size:",
4949 "SELECT total(length(sql)) FROM %s" },
4950 };
drh87c889c2019-03-20 18:22:51 +00004951 int i, rc;
drhea99a312018-07-18 19:09:07 +00004952 unsigned iDataVersion;
drh2ce15c32017-07-11 13:34:40 +00004953 char *zSchemaTab;
4954 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004955 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004956 unsigned char aHdr[100];
4957 open_db(p, 0);
4958 if( p->db==0 ) return 1;
drh87c889c2019-03-20 18:22:51 +00004959 rc = sqlite3_prepare_v2(p->db,
4960 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4961 -1, &pStmt, 0);
4962 if( rc ){
4963 if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){
4964 utf8_printf(stderr, "the \".dbinfo\" command requires the "
4965 "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n");
4966 }else{
4967 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
4968 }
4969 sqlite3_finalize(pStmt);
4970 return 1;
4971 }
drh512e6c32017-10-11 17:51:08 +00004972 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4973 if( sqlite3_step(pStmt)==SQLITE_ROW
4974 && sqlite3_column_bytes(pStmt,0)>100
4975 ){
4976 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4977 sqlite3_finalize(pStmt);
4978 }else{
drh2ce15c32017-07-11 13:34:40 +00004979 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004980 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004981 return 1;
4982 }
4983 i = get2byteInt(aHdr+16);
4984 if( i==1 ) i = 65536;
4985 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4986 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4987 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4988 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4989 for(i=0; i<ArraySize(aField); i++){
4990 int ofst = aField[i].ofst;
4991 unsigned int val = get4byteInt(aHdr + ofst);
4992 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4993 switch( ofst ){
4994 case 56: {
4995 if( val==1 ) raw_printf(p->out, " (utf8)");
4996 if( val==2 ) raw_printf(p->out, " (utf16le)");
4997 if( val==3 ) raw_printf(p->out, " (utf16be)");
4998 }
4999 }
5000 raw_printf(p->out, "\n");
5001 }
5002 if( zDb==0 ){
5003 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
5004 }else if( strcmp(zDb,"temp")==0 ){
5005 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
5006 }else{
5007 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
5008 }
5009 for(i=0; i<ArraySize(aQuery); i++){
5010 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5011 int val = db_int(p, zSql);
5012 sqlite3_free(zSql);
5013 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
5014 }
5015 sqlite3_free(zSchemaTab);
drhea99a312018-07-18 19:09:07 +00005016 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
5017 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
drh2ce15c32017-07-11 13:34:40 +00005018 return 0;
5019}
5020
5021/*
5022** Print the current sqlite3_errmsg() value to stderr and return 1.
5023*/
5024static int shellDatabaseError(sqlite3 *db){
5025 const char *zErr = sqlite3_errmsg(db);
5026 utf8_printf(stderr, "Error: %s\n", zErr);
5027 return 1;
5028}
5029
5030/*
drh2ce15c32017-07-11 13:34:40 +00005031** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
5032** if they match and FALSE (0) if they do not match.
5033**
5034** Globbing rules:
5035**
5036** '*' Matches any sequence of zero or more characters.
5037**
5038** '?' Matches exactly one character.
5039**
5040** [...] Matches one character from the enclosed list of
5041** characters.
5042**
5043** [^...] Matches one character not in the enclosed list.
5044**
5045** '#' Matches any sequence of one or more digits with an
5046** optional + or - sign in front
5047**
5048** ' ' Any span of whitespace matches any other span of
5049** whitespace.
5050**
5051** Extra whitespace at the end of z[] is ignored.
5052*/
5053static int testcase_glob(const char *zGlob, const char *z){
5054 int c, c2;
5055 int invert;
5056 int seen;
5057
5058 while( (c = (*(zGlob++)))!=0 ){
5059 if( IsSpace(c) ){
5060 if( !IsSpace(*z) ) return 0;
5061 while( IsSpace(*zGlob) ) zGlob++;
5062 while( IsSpace(*z) ) z++;
5063 }else if( c=='*' ){
5064 while( (c=(*(zGlob++))) == '*' || c=='?' ){
5065 if( c=='?' && (*(z++))==0 ) return 0;
5066 }
5067 if( c==0 ){
5068 return 1;
5069 }else if( c=='[' ){
5070 while( *z && testcase_glob(zGlob-1,z)==0 ){
5071 z++;
5072 }
5073 return (*z)!=0;
5074 }
5075 while( (c2 = (*(z++)))!=0 ){
5076 while( c2!=c ){
5077 c2 = *(z++);
5078 if( c2==0 ) return 0;
5079 }
5080 if( testcase_glob(zGlob,z) ) return 1;
5081 }
5082 return 0;
5083 }else if( c=='?' ){
5084 if( (*(z++))==0 ) return 0;
5085 }else if( c=='[' ){
5086 int prior_c = 0;
5087 seen = 0;
5088 invert = 0;
5089 c = *(z++);
5090 if( c==0 ) return 0;
5091 c2 = *(zGlob++);
5092 if( c2=='^' ){
5093 invert = 1;
5094 c2 = *(zGlob++);
5095 }
5096 if( c2==']' ){
5097 if( c==']' ) seen = 1;
5098 c2 = *(zGlob++);
5099 }
5100 while( c2 && c2!=']' ){
5101 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5102 c2 = *(zGlob++);
5103 if( c>=prior_c && c<=c2 ) seen = 1;
5104 prior_c = 0;
5105 }else{
5106 if( c==c2 ){
5107 seen = 1;
5108 }
5109 prior_c = c2;
5110 }
5111 c2 = *(zGlob++);
5112 }
5113 if( c2==0 || (seen ^ invert)==0 ) return 0;
5114 }else if( c=='#' ){
5115 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5116 if( !IsDigit(z[0]) ) return 0;
5117 z++;
5118 while( IsDigit(z[0]) ){ z++; }
5119 }else{
5120 if( c!=(*(z++)) ) return 0;
5121 }
5122 }
5123 while( IsSpace(*z) ){ z++; }
5124 return *z==0;
5125}
5126
5127
5128/*
5129** Compare the string as a command-line option with either one or two
5130** initial "-" characters.
5131*/
5132static int optionMatch(const char *zStr, const char *zOpt){
5133 if( zStr[0]!='-' ) return 0;
5134 zStr++;
5135 if( zStr[0]=='-' ) zStr++;
5136 return strcmp(zStr, zOpt)==0;
5137}
5138
5139/*
5140** Delete a file.
5141*/
5142int shellDeleteFile(const char *zFilename){
5143 int rc;
5144#ifdef _WIN32
5145 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5146 rc = _wunlink(z);
5147 sqlite3_free(z);
5148#else
5149 rc = unlink(zFilename);
5150#endif
5151 return rc;
5152}
5153
drh13c20932018-01-10 21:41:55 +00005154/*
5155** Try to delete the temporary file (if there is one) and free the
5156** memory used to hold the name of the temp file.
5157*/
5158static void clearTempFile(ShellState *p){
5159 if( p->zTempFile==0 ) return;
drh536c3452018-01-11 00:38:39 +00005160 if( p->doXdgOpen ) return;
drh13c20932018-01-10 21:41:55 +00005161 if( shellDeleteFile(p->zTempFile) ) return;
5162 sqlite3_free(p->zTempFile);
5163 p->zTempFile = 0;
5164}
5165
5166/*
5167** Create a new temp file name with the given suffix.
5168*/
5169static void newTempFile(ShellState *p, const char *zSuffix){
5170 clearTempFile(p);
5171 sqlite3_free(p->zTempFile);
5172 p->zTempFile = 0;
drh7f3bf8a2018-01-10 21:50:08 +00005173 if( p->db ){
5174 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5175 }
drh13c20932018-01-10 21:41:55 +00005176 if( p->zTempFile==0 ){
5177 sqlite3_uint64 r;
5178 sqlite3_randomness(sizeof(r), &r);
5179 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
5180 }else{
5181 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5182 }
5183 if( p->zTempFile==0 ){
5184 raw_printf(stderr, "out of memory\n");
5185 exit(1);
5186 }
5187}
5188
drh2ce15c32017-07-11 13:34:40 +00005189
5190/*
5191** The implementation of SQL scalar function fkey_collate_clause(), used
5192** by the ".lint fkey-indexes" command. This scalar function is always
5193** called with four arguments - the parent table name, the parent column name,
5194** the child table name and the child column name.
5195**
5196** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5197**
5198** If either of the named tables or columns do not exist, this function
5199** returns an empty string. An empty string is also returned if both tables
5200** and columns exist but have the same default collation sequence. Or,
5201** if both exist but the default collation sequences are different, this
5202** function returns the string " COLLATE <parent-collation>", where
5203** <parent-collation> is the default collation sequence of the parent column.
5204*/
5205static void shellFkeyCollateClause(
5206 sqlite3_context *pCtx,
5207 int nVal,
5208 sqlite3_value **apVal
5209){
5210 sqlite3 *db = sqlite3_context_db_handle(pCtx);
5211 const char *zParent;
5212 const char *zParentCol;
5213 const char *zParentSeq;
5214 const char *zChild;
5215 const char *zChildCol;
5216 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
5217 int rc;
5218
5219 assert( nVal==4 );
5220 zParent = (const char*)sqlite3_value_text(apVal[0]);
5221 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5222 zChild = (const char*)sqlite3_value_text(apVal[2]);
5223 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5224
5225 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5226 rc = sqlite3_table_column_metadata(
5227 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5228 );
5229 if( rc==SQLITE_OK ){
5230 rc = sqlite3_table_column_metadata(
5231 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5232 );
5233 }
5234
5235 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5236 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5237 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5238 sqlite3_free(z);
5239 }
5240}
5241
5242
5243/*
5244** The implementation of dot-command ".lint fkey-indexes".
5245*/
5246static int lintFkeyIndexes(
5247 ShellState *pState, /* Current shell tool state */
5248 char **azArg, /* Array of arguments passed to dot command */
5249 int nArg /* Number of entries in azArg[] */
5250){
5251 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
5252 FILE *out = pState->out; /* Stream to write non-error output to */
5253 int bVerbose = 0; /* If -verbose is present */
5254 int bGroupByParent = 0; /* If -groupbyparent is present */
5255 int i; /* To iterate through azArg[] */
5256 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
5257 int rc; /* Return code */
5258 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
5259
5260 /*
5261 ** This SELECT statement returns one row for each foreign key constraint
5262 ** in the schema of the main database. The column values are:
5263 **
5264 ** 0. The text of an SQL statement similar to:
5265 **
danf9679312017-12-01 18:40:18 +00005266 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00005267 **
danf9679312017-12-01 18:40:18 +00005268 ** This SELECT is similar to the one that the foreign keys implementation
5269 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00005270 ** be used to optimize this query, then it can also be used by the FK
5271 ** implementation to optimize DELETE or UPDATE statements on the parent
5272 ** table.
5273 **
5274 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5275 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5276 ** contains an index that can be used to optimize the query.
5277 **
5278 ** 2. Human readable text that describes the child table and columns. e.g.
5279 **
5280 ** "child_table(child_key1, child_key2)"
5281 **
5282 ** 3. Human readable text that describes the parent table and columns. e.g.
5283 **
5284 ** "parent_table(parent_key1, parent_key2)"
5285 **
5286 ** 4. A full CREATE INDEX statement for an index that could be used to
5287 ** optimize DELETE or UPDATE statements on the parent table. e.g.
5288 **
5289 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
5290 **
5291 ** 5. The name of the parent table.
5292 **
5293 ** These six values are used by the C logic below to generate the report.
5294 */
5295 const char *zSql =
5296 "SELECT "
danf9679312017-12-01 18:40:18 +00005297 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00005298 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5299 " || fkey_collate_clause("
5300 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5301 ", "
5302 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
5303 " || group_concat('*=?', ' AND ') || ')'"
5304 ", "
5305 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
5306 ", "
5307 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5308 ", "
5309 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5310 " || ' ON ' || quote(s.name) || '('"
5311 " || group_concat(quote(f.[from]) ||"
5312 " fkey_collate_clause("
5313 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5314 " || ');'"
5315 ", "
5316 " f.[table] "
5317 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
5318 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5319 "GROUP BY s.name, f.id "
5320 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5321 ;
5322 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
5323
5324 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00005325 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00005326 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5327 bVerbose = 1;
5328 }
5329 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5330 bGroupByParent = 1;
5331 zIndent = " ";
5332 }
5333 else{
5334 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5335 azArg[0], azArg[1]
5336 );
5337 return SQLITE_ERROR;
5338 }
5339 }
5340
5341 /* Register the fkey_collate_clause() SQL function */
5342 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5343 0, shellFkeyCollateClause, 0, 0
5344 );
5345
5346
5347 if( rc==SQLITE_OK ){
5348 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5349 }
5350 if( rc==SQLITE_OK ){
5351 sqlite3_bind_int(pSql, 1, bGroupByParent);
5352 }
5353
5354 if( rc==SQLITE_OK ){
5355 int rc2;
5356 char *zPrev = 0;
5357 while( SQLITE_ROW==sqlite3_step(pSql) ){
5358 int res = -1;
5359 sqlite3_stmt *pExplain = 0;
5360 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5361 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5362 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5363 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5364 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5365 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5366
5367 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5368 if( rc!=SQLITE_OK ) break;
5369 if( SQLITE_ROW==sqlite3_step(pExplain) ){
5370 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5371 res = (
5372 0==sqlite3_strglob(zGlob, zPlan)
5373 || 0==sqlite3_strglob(zGlobIPK, zPlan)
5374 );
5375 }
5376 rc = sqlite3_finalize(pExplain);
5377 if( rc!=SQLITE_OK ) break;
5378
5379 if( res<0 ){
5380 raw_printf(stderr, "Error: internal error");
5381 break;
5382 }else{
5383 if( bGroupByParent
5384 && (bVerbose || res==0)
5385 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5386 ){
5387 raw_printf(out, "-- Parent table %s\n", zParent);
5388 sqlite3_free(zPrev);
5389 zPrev = sqlite3_mprintf("%s", zParent);
5390 }
5391
5392 if( res==0 ){
5393 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5394 }else if( bVerbose ){
5395 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5396 zIndent, zFrom, zTarget
5397 );
5398 }
5399 }
5400 }
5401 sqlite3_free(zPrev);
5402
5403 if( rc!=SQLITE_OK ){
5404 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5405 }
5406
5407 rc2 = sqlite3_finalize(pSql);
5408 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5409 rc = rc2;
5410 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5411 }
5412 }else{
5413 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5414 }
5415
5416 return rc;
5417}
5418
5419/*
5420** Implementation of ".lint" dot command.
5421*/
5422static int lintDotCommand(
5423 ShellState *pState, /* Current shell tool state */
5424 char **azArg, /* Array of arguments passed to dot command */
5425 int nArg /* Number of entries in azArg[] */
5426){
5427 int n;
drhaf2770f2018-01-05 14:55:43 +00005428 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00005429 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5430 return lintFkeyIndexes(pState, azArg, nArg);
5431
5432 usage:
5433 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5434 raw_printf(stderr, "Where sub-commands are:\n");
5435 raw_printf(stderr, " fkey-indexes\n");
5436 return SQLITE_ERROR;
5437}
5438
dan1b162162019-04-27 20:15:15 +00005439#if !defined SQLITE_OMIT_VIRTUALTABLE
danfd0245d2017-12-07 15:44:29 +00005440static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00005441 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00005442 int *pRc,
5443 const char *zSql,
5444 sqlite3_stmt **ppStmt
5445){
5446 *ppStmt = 0;
5447 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00005448 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00005449 if( rc!=SQLITE_OK ){
5450 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00005451 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00005452 );
5453 *pRc = rc;
5454 }
5455 }
5456}
5457
drh9546c762019-05-10 17:50:33 +00005458/*
5459** Create a prepared statement using printf-style arguments for the SQL.
5460**
5461** This routine is could be marked "static". But it is not always used,
5462** depending on compile-time options. By omitting the "static", we avoid
5463** nuisance compiler warnings about "defined but not used".
5464*/
5465void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00005466 sqlite3 *db,
5467 int *pRc,
danac15e2d2017-12-14 19:15:07 +00005468 sqlite3_stmt **ppStmt,
5469 const char *zFmt,
5470 ...
dan3f67ddf2017-12-13 20:04:53 +00005471){
danac15e2d2017-12-14 19:15:07 +00005472 *ppStmt = 0;
5473 if( *pRc==SQLITE_OK ){
5474 va_list ap;
5475 char *z;
5476 va_start(ap, zFmt);
5477 z = sqlite3_vmprintf(zFmt, ap);
drh1dbb1472018-10-11 10:37:24 +00005478 va_end(ap);
dan3f67ddf2017-12-13 20:04:53 +00005479 if( z==0 ){
5480 *pRc = SQLITE_NOMEM;
5481 }else{
5482 shellPrepare(db, pRc, z, ppStmt);
5483 sqlite3_free(z);
5484 }
dan3f67ddf2017-12-13 20:04:53 +00005485 }
5486}
5487
drh9546c762019-05-10 17:50:33 +00005488/* Finalize the prepared statement created using shellPreparePrintf().
5489**
5490** This routine is could be marked "static". But it is not always used,
5491** depending on compile-time options. By omitting the "static", we avoid
5492** nuisance compiler warnings about "defined but not used".
5493*/
5494void shellFinalize(
danfd0245d2017-12-07 15:44:29 +00005495 int *pRc,
5496 sqlite3_stmt *pStmt
5497){
dan25c12182017-12-07 21:03:33 +00005498 if( pStmt ){
5499 sqlite3 *db = sqlite3_db_handle(pStmt);
5500 int rc = sqlite3_finalize(pStmt);
5501 if( *pRc==SQLITE_OK ){
5502 if( rc!=SQLITE_OK ){
5503 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5504 }
5505 *pRc = rc;
5506 }
5507 }
danfd0245d2017-12-07 15:44:29 +00005508}
5509
drh9546c762019-05-10 17:50:33 +00005510/* Reset the prepared statement created using shellPreparePrintf().
5511**
5512** This routine is could be marked "static". But it is not always used,
5513** depending on compile-time options. By omitting the "static", we avoid
5514** nuisance compiler warnings about "defined but not used".
5515*/
5516void shellReset(
danfd0245d2017-12-07 15:44:29 +00005517 int *pRc,
5518 sqlite3_stmt *pStmt
5519){
5520 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00005521 if( *pRc==SQLITE_OK ){
5522 if( rc!=SQLITE_OK ){
5523 sqlite3 *db = sqlite3_db_handle(pStmt);
5524 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5525 }
5526 *pRc = rc;
5527 }
danfd0245d2017-12-07 15:44:29 +00005528}
dan1b162162019-04-27 20:15:15 +00005529#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */
5530
5531#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drhe2754c12019-08-26 12:50:01 +00005532/******************************************************************************
dan1b162162019-04-27 20:15:15 +00005533** The ".archive" or ".ar" command.
5534*/
drhe37c0e12018-01-06 19:19:50 +00005535/*
dan88be0202017-12-09 17:58:02 +00005536** Structure representing a single ".ar" command.
5537*/
5538typedef struct ArCommand ArCommand;
5539struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00005540 u8 eCmd; /* An AR_CMD_* value */
5541 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00005542 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00005543 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00005544 u8 bAppend; /* True if --append */
drhd0f9cdc2018-05-17 14:09:06 +00005545 u8 fromCmdLine; /* Run from -A instead of .archive */
drhb376b3d2018-01-10 13:11:51 +00005546 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00005547 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00005548 const char *zFile; /* --file argument, or NULL */
5549 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00005550 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00005551 ShellState *p; /* Shell state */
5552 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00005553};
5554
5555/*
5556** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5557*/
dan0d0547f2017-12-14 15:40:42 +00005558static int arUsage(FILE *f){
drh98aa2ab2018-09-26 16:53:51 +00005559 showHelp(f,"archive");
dan0d0547f2017-12-14 15:40:42 +00005560 return SQLITE_ERROR;
5561}
5562
5563/*
5564** Print an error message for the .ar command to stderr and return
5565** SQLITE_ERROR.
5566*/
drhd0f9cdc2018-05-17 14:09:06 +00005567static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
dan0d0547f2017-12-14 15:40:42 +00005568 va_list ap;
5569 char *z;
5570 va_start(ap, zFmt);
5571 z = sqlite3_vmprintf(zFmt, ap);
5572 va_end(ap);
drhd0f9cdc2018-05-17 14:09:06 +00005573 utf8_printf(stderr, "Error: %s\n", z);
5574 if( pAr->fromCmdLine ){
5575 utf8_printf(stderr, "Use \"-A\" for more help\n");
5576 }else{
5577 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5578 }
dan0d0547f2017-12-14 15:40:42 +00005579 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00005580 return SQLITE_ERROR;
5581}
5582
5583/*
5584** Values for ArCommand.eCmd.
5585*/
dand4b56e52017-12-12 20:04:59 +00005586#define AR_CMD_CREATE 1
drhb17ea912019-03-25 14:24:19 +00005587#define AR_CMD_UPDATE 2
5588#define AR_CMD_INSERT 3
5589#define AR_CMD_EXTRACT 4
5590#define AR_CMD_LIST 5
5591#define AR_CMD_HELP 6
dand4b56e52017-12-12 20:04:59 +00005592
5593/*
5594** Other (non-command) switches.
5595*/
drhb17ea912019-03-25 14:24:19 +00005596#define AR_SWITCH_VERBOSE 7
5597#define AR_SWITCH_FILE 8
5598#define AR_SWITCH_DIRECTORY 9
5599#define AR_SWITCH_APPEND 10
5600#define AR_SWITCH_DRYRUN 11
dand4b56e52017-12-12 20:04:59 +00005601
5602static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5603 switch( eSwitch ){
5604 case AR_CMD_CREATE:
5605 case AR_CMD_EXTRACT:
5606 case AR_CMD_LIST:
5607 case AR_CMD_UPDATE:
drhb17ea912019-03-25 14:24:19 +00005608 case AR_CMD_INSERT:
dan0d0547f2017-12-14 15:40:42 +00005609 case AR_CMD_HELP:
5610 if( pAr->eCmd ){
drhd0f9cdc2018-05-17 14:09:06 +00005611 return arErrorMsg(pAr, "multiple command options");
dan0d0547f2017-12-14 15:40:42 +00005612 }
dand4b56e52017-12-12 20:04:59 +00005613 pAr->eCmd = eSwitch;
5614 break;
5615
drhb376b3d2018-01-10 13:11:51 +00005616 case AR_SWITCH_DRYRUN:
5617 pAr->bDryRun = 1;
5618 break;
dand4b56e52017-12-12 20:04:59 +00005619 case AR_SWITCH_VERBOSE:
5620 pAr->bVerbose = 1;
5621 break;
drha5676c42018-01-10 15:17:34 +00005622 case AR_SWITCH_APPEND:
5623 pAr->bAppend = 1;
drhca7733b2018-01-10 18:09:20 +00005624 /* Fall thru into --file */
dand4b56e52017-12-12 20:04:59 +00005625 case AR_SWITCH_FILE:
5626 pAr->zFile = zArg;
5627 break;
5628 case AR_SWITCH_DIRECTORY:
5629 pAr->zDir = zArg;
5630 break;
5631 }
5632
5633 return SQLITE_OK;
5634}
dan88be0202017-12-09 17:58:02 +00005635
5636/*
5637** Parse the command line for an ".ar" command. The results are written into
5638** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5639** successfully, otherwise an error message is written to stderr and
5640** SQLITE_ERROR returned.
5641*/
5642static int arParseCommand(
5643 char **azArg, /* Array of arguments passed to dot command */
5644 int nArg, /* Number of entries in azArg[] */
5645 ArCommand *pAr /* Populate this object */
5646){
dand4b56e52017-12-12 20:04:59 +00005647 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00005648 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00005649 char cShort;
5650 u8 eSwitch;
5651 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00005652 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00005653 { "create", 'c', AR_CMD_CREATE, 0 },
5654 { "extract", 'x', AR_CMD_EXTRACT, 0 },
drhb17ea912019-03-25 14:24:19 +00005655 { "insert", 'i', AR_CMD_INSERT, 0 },
drhb376b3d2018-01-10 13:11:51 +00005656 { "list", 't', AR_CMD_LIST, 0 },
5657 { "update", 'u', AR_CMD_UPDATE, 0 },
5658 { "help", 'h', AR_CMD_HELP, 0 },
5659 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
5660 { "file", 'f', AR_SWITCH_FILE, 1 },
drhca7733b2018-01-10 18:09:20 +00005661 { "append", 'a', AR_SWITCH_APPEND, 1 },
drhb376b3d2018-01-10 13:11:51 +00005662 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drhb376b3d2018-01-10 13:11:51 +00005663 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00005664 };
5665 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5666 struct ArSwitch *pEnd = &aSwitch[nSwitch];
5667
dan88be0202017-12-09 17:58:02 +00005668 if( nArg<=1 ){
drh98aa2ab2018-09-26 16:53:51 +00005669 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
dan0d0547f2017-12-14 15:40:42 +00005670 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00005671 }else{
5672 char *z = azArg[1];
dan88be0202017-12-09 17:58:02 +00005673 if( z[0]!='-' ){
5674 /* Traditional style [tar] invocation */
5675 int i;
5676 int iArg = 2;
5677 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00005678 const char *zArg = 0;
5679 struct ArSwitch *pOpt;
5680 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5681 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00005682 }
dan0d0547f2017-12-14 15:40:42 +00005683 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005684 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005685 }
dand4b56e52017-12-12 20:04:59 +00005686 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005687 if( iArg>=nArg ){
drhd0f9cdc2018-05-17 14:09:06 +00005688 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005689 }
dand4b56e52017-12-12 20:04:59 +00005690 zArg = azArg[iArg++];
5691 }
5692 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00005693 }
dan88be0202017-12-09 17:58:02 +00005694 pAr->nArg = nArg-iArg;
5695 if( pAr->nArg>0 ){
5696 pAr->azArg = &azArg[iArg];
5697 }
dand4b56e52017-12-12 20:04:59 +00005698 }else{
5699 /* Non-traditional invocation */
5700 int iArg;
5701 for(iArg=1; iArg<nArg; iArg++){
5702 int n;
5703 z = azArg[iArg];
5704 if( z[0]!='-' ){
5705 /* All remaining command line words are command arguments. */
5706 pAr->azArg = &azArg[iArg];
5707 pAr->nArg = nArg-iArg;
5708 break;
5709 }
drhaf2770f2018-01-05 14:55:43 +00005710 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00005711
5712 if( z[1]!='-' ){
5713 int i;
5714 /* One or more short options */
5715 for(i=1; i<n; i++){
5716 const char *zArg = 0;
5717 struct ArSwitch *pOpt;
5718 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5719 if( z[i]==pOpt->cShort ) break;
5720 }
dan0d0547f2017-12-14 15:40:42 +00005721 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005722 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005723 }
dand4b56e52017-12-12 20:04:59 +00005724 if( pOpt->bArg ){
5725 if( i<(n-1) ){
5726 zArg = &z[i+1];
5727 i = n;
5728 }else{
dan0d0547f2017-12-14 15:40:42 +00005729 if( iArg>=(nArg-1) ){
drhe2754c12019-08-26 12:50:01 +00005730 return arErrorMsg(pAr, "option requires an argument: %c",
5731 z[i]);
dan0d0547f2017-12-14 15:40:42 +00005732 }
dand4b56e52017-12-12 20:04:59 +00005733 zArg = azArg[++iArg];
5734 }
5735 }
5736 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5737 }
5738 }else if( z[2]=='\0' ){
5739 /* A -- option, indicating that all remaining command line words
5740 ** are command arguments. */
5741 pAr->azArg = &azArg[iArg+1];
5742 pAr->nArg = nArg-iArg-1;
5743 break;
5744 }else{
5745 /* A long option */
5746 const char *zArg = 0; /* Argument for option, if any */
5747 struct ArSwitch *pMatch = 0; /* Matching option */
5748 struct ArSwitch *pOpt; /* Iterator */
5749 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5750 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00005751 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00005752 if( pMatch ){
drhd0f9cdc2018-05-17 14:09:06 +00005753 return arErrorMsg(pAr, "ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00005754 }else{
5755 pMatch = pOpt;
5756 }
5757 }
5758 }
5759
5760 if( pMatch==0 ){
drhd0f9cdc2018-05-17 14:09:06 +00005761 return arErrorMsg(pAr, "unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00005762 }
5763 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005764 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005765 return arErrorMsg(pAr, "option requires an argument: %s", z);
dan0d0547f2017-12-14 15:40:42 +00005766 }
dand4b56e52017-12-12 20:04:59 +00005767 zArg = azArg[++iArg];
5768 }
5769 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5770 }
5771 }
dan88be0202017-12-09 17:58:02 +00005772 }
5773 }
5774
5775 return SQLITE_OK;
5776}
5777
5778/*
dan3f67ddf2017-12-13 20:04:53 +00005779** This function assumes that all arguments within the ArCommand.azArg[]
5780** array refer to archive members, as for the --extract or --list commands.
5781** It checks that each of them are present. If any specified file is not
5782** present in the archive, an error is printed to stderr and an error
5783** code returned. Otherwise, if all specified arguments are present in
5784** the archive, SQLITE_OK is returned.
5785**
5786** This function strips any trailing '/' characters from each argument.
5787** This is consistent with the way the [tar] command seems to work on
5788** Linux.
5789*/
drhb376b3d2018-01-10 13:11:51 +00005790static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00005791 int rc = SQLITE_OK;
5792 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00005793 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00005794 sqlite3_stmt *pTest = 0;
5795
drhb376b3d2018-01-10 13:11:51 +00005796 shellPreparePrintf(pAr->db, &rc, &pTest,
5797 "SELECT name FROM %s WHERE name=$name",
5798 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00005799 );
drhb376b3d2018-01-10 13:11:51 +00005800 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00005801 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5802 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00005803 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00005804 int bOk = 0;
5805 while( n>0 && z[n-1]=='/' ) n--;
5806 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00005807 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00005808 if( SQLITE_ROW==sqlite3_step(pTest) ){
5809 bOk = 1;
5810 }
5811 shellReset(&rc, pTest);
5812 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00005813 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00005814 rc = SQLITE_ERROR;
5815 }
5816 }
5817 shellFinalize(&rc, pTest);
5818 }
dan3f67ddf2017-12-13 20:04:53 +00005819 return rc;
5820}
5821
5822/*
5823** Format a WHERE clause that can be used against the "sqlar" table to
5824** identify all archive members that match the command arguments held
5825** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5826** The caller is responsible for eventually calling sqlite3_free() on
5827** any non-NULL (*pzWhere) value.
5828*/
5829static void arWhereClause(
5830 int *pRc,
5831 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00005832 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00005833){
5834 char *zWhere = 0;
5835 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00005836 if( pAr->nArg==0 ){
5837 zWhere = sqlite3_mprintf("1");
5838 }else{
5839 int i;
5840 const char *zSep = "";
5841 for(i=0; i<pAr->nArg; i++){
5842 const char *z = pAr->azArg[i];
5843 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00005844 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5845 zWhere, zSep, z, strlen30(z)+1, z
5846 );
danac15e2d2017-12-14 19:15:07 +00005847 if( zWhere==0 ){
5848 *pRc = SQLITE_NOMEM;
5849 break;
5850 }
5851 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00005852 }
dan3f67ddf2017-12-13 20:04:53 +00005853 }
5854 }
5855 *pzWhere = zWhere;
5856}
5857
5858/*
dan88be0202017-12-09 17:58:02 +00005859** Implementation of .ar "lisT" command.
5860*/
drhb376b3d2018-01-10 13:11:51 +00005861static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00005862 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00005863 const char *azCols[] = {
5864 "name",
drh410cad92018-01-10 17:19:16 +00005865 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00005866 };
dan5a78b812017-12-27 18:54:11 +00005867
dan3f67ddf2017-12-13 20:04:53 +00005868 char *zWhere = 0;
5869 sqlite3_stmt *pSql = 0;
5870 int rc;
5871
drhb376b3d2018-01-10 13:11:51 +00005872 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005873 arWhereClause(&rc, pAr, &zWhere);
5874
drhb376b3d2018-01-10 13:11:51 +00005875 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5876 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00005877 if( pAr->bDryRun ){
5878 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5879 }else{
5880 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5881 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00005882 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5883 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00005884 sqlite3_column_int(pSql, 1),
5885 sqlite3_column_text(pSql, 2),
5886 sqlite3_column_text(pSql, 3)
5887 );
5888 }else{
5889 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5890 }
danb5090e42017-12-27 21:13:21 +00005891 }
dan3f67ddf2017-12-13 20:04:53 +00005892 }
dan5a78b812017-12-27 18:54:11 +00005893 shellFinalize(&rc, pSql);
drhd0f9cdc2018-05-17 14:09:06 +00005894 sqlite3_free(zWhere);
dan3f67ddf2017-12-13 20:04:53 +00005895 return rc;
dan88be0202017-12-09 17:58:02 +00005896}
5897
5898
danfd0245d2017-12-07 15:44:29 +00005899/*
5900** Implementation of .ar "eXtract" command.
5901*/
drhb376b3d2018-01-10 13:11:51 +00005902static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00005903 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00005904 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00005905 " ($dir || name),"
5906 " writefile(($dir || name), %s, mode, mtime) "
drh0cfd46a2018-06-06 01:18:01 +00005907 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5908 " AND name NOT GLOB '*..[/\\]*'";
dan5a78b812017-12-27 18:54:11 +00005909
5910 const char *azExtraArg[] = {
5911 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00005912 "data"
dan5a78b812017-12-27 18:54:11 +00005913 };
dan5a78b812017-12-27 18:54:11 +00005914
danfd0245d2017-12-07 15:44:29 +00005915 sqlite3_stmt *pSql = 0;
5916 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00005917 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00005918 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00005919 int i, j;
dan2ad09492017-12-09 18:28:22 +00005920
dan3f67ddf2017-12-13 20:04:53 +00005921 /* If arguments are specified, check that they actually exist within
5922 ** the archive before proceeding. And formulate a WHERE clause to
5923 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00005924 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005925 arWhereClause(&rc, pAr, &zWhere);
5926
5927 if( rc==SQLITE_OK ){
5928 if( pAr->zDir ){
5929 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5930 }else{
5931 zDir = sqlite3_mprintf("");
5932 }
5933 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00005934 }
danfd0245d2017-12-07 15:44:29 +00005935
drhb376b3d2018-01-10 13:11:51 +00005936 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5937 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00005938 );
5939
dan2ad09492017-12-09 18:28:22 +00005940 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005941 j = sqlite3_bind_parameter_index(pSql, "$dir");
5942 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00005943
danac15e2d2017-12-14 19:15:07 +00005944 /* Run the SELECT statement twice. The first time, writefile() is called
5945 ** for all archive members that should be extracted. The second time,
5946 ** only for the directories. This is because the timestamps for
5947 ** extracted directories must be reset after they are populated (as
5948 ** populating them changes the timestamp). */
5949 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00005950 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5951 sqlite3_bind_int(pSql, j, i);
5952 if( pAr->bDryRun ){
5953 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5954 }else{
5955 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5956 if( i==0 && pAr->bVerbose ){
5957 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5958 }
danac15e2d2017-12-14 19:15:07 +00005959 }
5960 }
5961 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005962 }
danac15e2d2017-12-14 19:15:07 +00005963 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005964 }
dan25c12182017-12-07 21:03:33 +00005965
dan2ad09492017-12-09 18:28:22 +00005966 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00005967 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00005968 return rc;
5969}
5970
drhb376b3d2018-01-10 13:11:51 +00005971/*
5972** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5973*/
5974static int arExecSql(ArCommand *pAr, const char *zSql){
5975 int rc;
5976 if( pAr->bDryRun ){
5977 utf8_printf(pAr->p->out, "%s\n", zSql);
5978 rc = SQLITE_OK;
5979 }else{
drh410cad92018-01-10 17:19:16 +00005980 char *zErr = 0;
5981 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5982 if( zErr ){
5983 utf8_printf(stdout, "ERROR: %s\n", zErr);
5984 sqlite3_free(zErr);
5985 }
drhb376b3d2018-01-10 13:11:51 +00005986 }
5987 return rc;
5988}
5989
dan1ad3f612017-12-11 20:22:02 +00005990
danfd0245d2017-12-07 15:44:29 +00005991/*
drhb17ea912019-03-25 14:24:19 +00005992** Implementation of .ar "create", "insert", and "update" commands.
5993**
5994** create -> Create a new SQL archive
5995** insert -> Insert or reinsert all files listed
5996** update -> Insert files that have changed or that were not
5997** previously in the archive
danfd0245d2017-12-07 15:44:29 +00005998**
5999** Create the "sqlar" table in the database if it does not already exist.
6000** Then add each file in the azFile[] array to the archive. Directories
6001** are added recursively. If argument bVerbose is non-zero, a message is
6002** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00006003**
6004** The create command is the same as update, except that it drops
drhb17ea912019-03-25 14:24:19 +00006005** any existing "sqlar" table before beginning. The "insert" command
6006** always overwrites every file named on the command-line, where as
6007** "update" only overwrites if the size or mtime or mode has changed.
danfd0245d2017-12-07 15:44:29 +00006008*/
drhb376b3d2018-01-10 13:11:51 +00006009static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00006010 ArCommand *pAr, /* Command arguments and options */
drhb17ea912019-03-25 14:24:19 +00006011 int bUpdate, /* true for a --create. */
6012 int bOnlyIfChanged /* Only update if file has changed */
danfd0245d2017-12-07 15:44:29 +00006013){
dand4b56e52017-12-12 20:04:59 +00006014 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00006015 "CREATE TABLE IF NOT EXISTS sqlar(\n"
6016 " name TEXT PRIMARY KEY, -- name of the file\n"
6017 " mode INT, -- access permissions\n"
6018 " mtime INT, -- last modification time\n"
6019 " sz INT, -- original file size\n"
6020 " data BLOB -- compressed content\n"
6021 ")";
dand4b56e52017-12-12 20:04:59 +00006022 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh1bf208c2018-03-09 21:54:01 +00006023 const char *zInsertFmt[2] = {
6024 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
drh634c70f2018-01-10 16:50:18 +00006025 " SELECT\n"
6026 " %s,\n"
6027 " mode,\n"
6028 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00006029 " CASE substr(lsmode(mode),1,1)\n"
6030 " WHEN '-' THEN length(data)\n"
6031 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00006032 " ELSE -1 END,\n"
drh69d2d352018-03-09 22:18:53 +00006033 " sqlar_compress(data)\n"
drhb17ea912019-03-25 14:24:19 +00006034 " FROM fsdir(%Q,%Q) AS disk\n"
6035 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
6036 ,
drh1bf208c2018-03-09 21:54:01 +00006037 "REPLACE INTO %s(name,mode,mtime,data)\n"
6038 " SELECT\n"
6039 " %s,\n"
6040 " mode,\n"
6041 " mtime,\n"
6042 " data\n"
drhb17ea912019-03-25 14:24:19 +00006043 " FROM fsdir(%Q,%Q) AS disk\n"
6044 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
drh1bf208c2018-03-09 21:54:01 +00006045 };
danfd0245d2017-12-07 15:44:29 +00006046 int i; /* For iterating through azFile[] */
6047 int rc; /* Return code */
drh1bf208c2018-03-09 21:54:01 +00006048 const char *zTab = 0; /* SQL table into which to insert */
6049 char *zSql;
6050 char zTemp[50];
drhb17ea912019-03-25 14:24:19 +00006051 char *zExists = 0;
danfd0245d2017-12-07 15:44:29 +00006052
drh1bf208c2018-03-09 21:54:01 +00006053 arExecSql(pAr, "PRAGMA page_size=512");
drhb376b3d2018-01-10 13:11:51 +00006054 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00006055 if( rc!=SQLITE_OK ) return rc;
drh1bf208c2018-03-09 21:54:01 +00006056 zTemp[0] = 0;
6057 if( pAr->bZip ){
6058 /* Initialize the zipfile virtual table, if necessary */
6059 if( pAr->zFile ){
6060 sqlite3_uint64 r;
6061 sqlite3_randomness(sizeof(r),&r);
6062 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
6063 zTab = zTemp;
6064 zSql = sqlite3_mprintf(
6065 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
6066 zTab, pAr->zFile
6067 );
6068 rc = arExecSql(pAr, zSql);
6069 sqlite3_free(zSql);
6070 }else{
6071 zTab = "zip";
6072 }
6073 }else{
6074 /* Initialize the table for an SQLAR */
6075 zTab = "sqlar";
6076 if( bUpdate==0 ){
6077 rc = arExecSql(pAr, zDrop);
6078 if( rc!=SQLITE_OK ) goto end_ar_transaction;
6079 }
6080 rc = arExecSql(pAr, zCreate);
dan06741a32017-12-13 20:17:18 +00006081 }
drhb17ea912019-03-25 14:24:19 +00006082 if( bOnlyIfChanged ){
6083 zExists = sqlite3_mprintf(
6084 " AND NOT EXISTS("
6085 "SELECT 1 FROM %s AS mem"
6086 " WHERE mem.name=disk.name"
6087 " AND mem.mtime=disk.mtime"
6088 " AND mem.mode=disk.mode)", zTab);
6089 }else{
6090 zExists = sqlite3_mprintf("");
6091 }
6092 if( zExists==0 ) rc = SQLITE_NOMEM;
dan88be0202017-12-09 17:58:02 +00006093 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
mistachkince2052b2018-03-23 00:31:53 +00006094 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
drh634c70f2018-01-10 16:50:18 +00006095 pAr->bVerbose ? "shell_putsnl(name)" : "name",
drhb17ea912019-03-25 14:24:19 +00006096 pAr->azArg[i], pAr->zDir, zExists);
mistachkince2052b2018-03-23 00:31:53 +00006097 rc = arExecSql(pAr, zSql2);
6098 sqlite3_free(zSql2);
danfd0245d2017-12-07 15:44:29 +00006099 }
drh1bf208c2018-03-09 21:54:01 +00006100end_ar_transaction:
danfd0245d2017-12-07 15:44:29 +00006101 if( rc!=SQLITE_OK ){
drh2bd207f2019-01-11 17:19:59 +00006102 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00006103 }else{
drhb376b3d2018-01-10 13:11:51 +00006104 rc = arExecSql(pAr, "RELEASE ar;");
drh1bf208c2018-03-09 21:54:01 +00006105 if( pAr->bZip && pAr->zFile ){
6106 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6107 arExecSql(pAr, zSql);
6108 sqlite3_free(zSql);
6109 }
danfd0245d2017-12-07 15:44:29 +00006110 }
drhb17ea912019-03-25 14:24:19 +00006111 sqlite3_free(zExists);
danfd0245d2017-12-07 15:44:29 +00006112 return rc;
6113}
6114
6115/*
6116** Implementation of ".ar" dot command.
6117*/
6118static int arDotCommand(
drhe2754c12019-08-26 12:50:01 +00006119 ShellState *pState, /* Current shell tool state */
6120 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
6121 char **azArg, /* Array of arguments passed to dot command */
6122 int nArg /* Number of entries in azArg[] */
danfd0245d2017-12-07 15:44:29 +00006123){
dan88be0202017-12-09 17:58:02 +00006124 ArCommand cmd;
6125 int rc;
drh34660642018-01-10 17:39:54 +00006126 memset(&cmd, 0, sizeof(cmd));
drhd0f9cdc2018-05-17 14:09:06 +00006127 cmd.fromCmdLine = fromCmdLine;
dan88be0202017-12-09 17:58:02 +00006128 rc = arParseCommand(azArg, nArg, &cmd);
6129 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00006130 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00006131 cmd.p = pState;
6132 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00006133 if( cmd.zFile ){
drh1bf208c2018-03-09 21:54:01 +00006134 eDbType = deduceDatabaseType(cmd.zFile, 1);
drha5676c42018-01-10 15:17:34 +00006135 }else{
6136 eDbType = pState->openMode;
6137 }
6138 if( eDbType==SHELL_OPEN_ZIPFILE ){
drh1bf208c2018-03-09 21:54:01 +00006139 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6140 if( cmd.zFile==0 ){
6141 cmd.zSrcTable = sqlite3_mprintf("zip");
6142 }else{
6143 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6144 }
dan5a78b812017-12-27 18:54:11 +00006145 }
drha5676c42018-01-10 15:17:34 +00006146 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00006147 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00006148 int flags;
drha5676c42018-01-10 15:17:34 +00006149 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
drhb17ea912019-03-25 14:24:19 +00006150 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6151 || cmd.eCmd==AR_CMD_UPDATE ){
dand4b56e52017-12-12 20:04:59 +00006152 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6153 }else{
6154 flags = SQLITE_OPEN_READONLY;
6155 }
drha82c95b2018-01-10 14:00:00 +00006156 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00006157 if( cmd.bDryRun ){
6158 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6159 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6160 }
6161 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6162 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00006163 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00006164 utf8_printf(stderr, "cannot open file: %s (%s)\n",
6165 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00006166 );
drha5676c42018-01-10 15:17:34 +00006167 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00006168 }
drhb376b3d2018-01-10 13:11:51 +00006169 sqlite3_fileio_init(cmd.db, 0, 0);
drhb376b3d2018-01-10 13:11:51 +00006170 sqlite3_sqlar_init(cmd.db, 0, 0);
drh34660642018-01-10 17:39:54 +00006171 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6172 shellPutsFunc, 0, 0);
6173
dand4b56e52017-12-12 20:04:59 +00006174 }
drhd0f9cdc2018-05-17 14:09:06 +00006175 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
drh634c70f2018-01-10 16:50:18 +00006176 if( cmd.eCmd!=AR_CMD_CREATE
6177 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6178 ){
drha5676c42018-01-10 15:17:34 +00006179 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6180 rc = SQLITE_ERROR;
6181 goto end_ar_command;
6182 }
6183 cmd.zSrcTable = sqlite3_mprintf("sqlar");
6184 }
dand4b56e52017-12-12 20:04:59 +00006185
dan88be0202017-12-09 17:58:02 +00006186 switch( cmd.eCmd ){
6187 case AR_CMD_CREATE:
drhb17ea912019-03-25 14:24:19 +00006188 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
dan88be0202017-12-09 17:58:02 +00006189 break;
danfd0245d2017-12-07 15:44:29 +00006190
dan88be0202017-12-09 17:58:02 +00006191 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00006192 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00006193 break;
6194
6195 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00006196 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00006197 break;
6198
dan0d0547f2017-12-14 15:40:42 +00006199 case AR_CMD_HELP:
6200 arUsage(pState->out);
6201 break;
6202
drhb17ea912019-03-25 14:24:19 +00006203 case AR_CMD_INSERT:
6204 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6205 break;
6206
dan88be0202017-12-09 17:58:02 +00006207 default:
6208 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb17ea912019-03-25 14:24:19 +00006209 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
dan88be0202017-12-09 17:58:02 +00006210 break;
danfd0245d2017-12-07 15:44:29 +00006211 }
6212 }
drha5676c42018-01-10 15:17:34 +00006213end_ar_command:
6214 if( cmd.db!=pState->db ){
drh9e804032018-05-18 17:11:50 +00006215 close_db(cmd.db);
drha5676c42018-01-10 15:17:34 +00006216 }
6217 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00006218
dan88be0202017-12-09 17:58:02 +00006219 return rc;
danfd0245d2017-12-07 15:44:29 +00006220}
drhe37c0e12018-01-06 19:19:50 +00006221/* End of the ".archive" or ".ar" command logic
drhe2754c12019-08-26 12:50:01 +00006222*******************************************************************************/
drhe37c0e12018-01-06 19:19:50 +00006223#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00006224
dan1b162162019-04-27 20:15:15 +00006225#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
dan42ebb012019-04-27 18:47:03 +00006226/*
6227** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
6228** Otherwise, the SQL statement or statements in zSql are executed using
6229** database connection db and the error code written to *pRc before
6230** this function returns.
6231*/
dan68cb86e2019-04-20 20:57:28 +00006232static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6233 int rc = *pRc;
6234 if( rc==SQLITE_OK ){
6235 char *zErr = 0;
6236 rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6237 if( rc!=SQLITE_OK ){
6238 raw_printf(stderr, "SQL error: %s\n", zErr);
6239 }
6240 *pRc = rc;
6241 }
6242}
6243
dan42ebb012019-04-27 18:47:03 +00006244/*
6245** Like shellExec(), except that zFmt is a printf() style format string.
6246*/
danc0b42432019-04-26 15:14:53 +00006247static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6248 char *z = 0;
6249 if( *pRc==SQLITE_OK ){
6250 va_list ap;
6251 va_start(ap, zFmt);
6252 z = sqlite3_vmprintf(zFmt, ap);
6253 va_end(ap);
6254 if( z==0 ){
6255 *pRc = SQLITE_NOMEM;
6256 }else{
6257 shellExec(db, pRc, z);
6258 }
6259 sqlite3_free(z);
6260 }
6261}
6262
dan42ebb012019-04-27 18:47:03 +00006263/*
6264** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6265** Otherwise, an attempt is made to allocate, zero and return a pointer
6266** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
6267** to SQLITE_NOMEM and NULL returned.
6268*/
dan68cb86e2019-04-20 20:57:28 +00006269static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6270 void *pRet = 0;
6271 if( *pRc==SQLITE_OK ){
6272 pRet = sqlite3_malloc64(nByte);
6273 if( pRet==0 ){
6274 *pRc = SQLITE_NOMEM;
6275 }else{
6276 memset(pRet, 0, nByte);
6277 }
6278 }
6279 return pRet;
6280}
6281
dan42ebb012019-04-27 18:47:03 +00006282/*
6283** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6284** Otherwise, zFmt is treated as a printf() style string. The result of
6285** formatting it along with any trailing arguments is written into a
6286** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
6287** It is the responsibility of the caller to eventually free this buffer
6288** using a call to sqlite3_free().
6289**
6290** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
6291** pointer returned.
6292*/
dan68cb86e2019-04-20 20:57:28 +00006293static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6294 char *z = 0;
6295 if( *pRc==SQLITE_OK ){
6296 va_list ap;
6297 va_start(ap, zFmt);
6298 z = sqlite3_vmprintf(zFmt, ap);
6299 va_end(ap);
6300 if( z==0 ){
6301 *pRc = SQLITE_NOMEM;
6302 }
6303 }
6304 return z;
6305}
6306
dan42ebb012019-04-27 18:47:03 +00006307/*
6308** When running the ".recover" command, each output table, and the special
6309** orphaned row table if it is required, is represented by an instance
6310** of the following struct.
6311*/
dan68cb86e2019-04-20 20:57:28 +00006312typedef struct RecoverTable RecoverTable;
6313struct RecoverTable {
dan42ebb012019-04-27 18:47:03 +00006314 char *zQuoted; /* Quoted version of table name */
dan68cb86e2019-04-20 20:57:28 +00006315 int nCol; /* Number of columns in table */
6316 char **azlCol; /* Array of column lists */
dan42ebb012019-04-27 18:47:03 +00006317 int iPk; /* Index of IPK column */
dan68cb86e2019-04-20 20:57:28 +00006318};
6319
6320/*
dan42ebb012019-04-27 18:47:03 +00006321** Free a RecoverTable object allocated by recoverFindTable() or
6322** recoverOrphanTable().
dan68cb86e2019-04-20 20:57:28 +00006323*/
6324static void recoverFreeTable(RecoverTable *pTab){
6325 if( pTab ){
dan68cb86e2019-04-20 20:57:28 +00006326 sqlite3_free(pTab->zQuoted);
dan68cb86e2019-04-20 20:57:28 +00006327 if( pTab->azlCol ){
6328 int i;
dan98c5ad32019-04-26 21:11:37 +00006329 for(i=0; i<=pTab->nCol; i++){
dan68cb86e2019-04-20 20:57:28 +00006330 sqlite3_free(pTab->azlCol[i]);
6331 }
6332 sqlite3_free(pTab->azlCol);
6333 }
6334 sqlite3_free(pTab);
6335 }
6336}
6337
dan42ebb012019-04-27 18:47:03 +00006338/*
6339** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
6340** Otherwise, it allocates and returns a RecoverTable object based on the
6341** final four arguments passed to this function. It is the responsibility
6342** of the caller to eventually free the returned object using
6343** recoverFreeTable().
6344*/
6345static RecoverTable *recoverNewTable(
danb40af492019-04-22 20:52:12 +00006346 int *pRc, /* IN/OUT: Error code */
danb40af492019-04-22 20:52:12 +00006347 const char *zName, /* Name of table */
6348 const char *zSql, /* CREATE TABLE statement */
6349 int bIntkey,
6350 int nCol
6351){
6352 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */
6353 int rc = *pRc;
dan98c5ad32019-04-26 21:11:37 +00006354 RecoverTable *pTab = 0;
danb40af492019-04-22 20:52:12 +00006355
dan98c5ad32019-04-26 21:11:37 +00006356 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
danb40af492019-04-22 20:52:12 +00006357 if( rc==SQLITE_OK ){
6358 int nSqlCol = 0;
6359 int bSqlIntkey = 0;
6360 sqlite3_stmt *pStmt = 0;
dan98c5ad32019-04-26 21:11:37 +00006361
danb40af492019-04-22 20:52:12 +00006362 rc = sqlite3_open("", &dbtmp);
6363 if( rc==SQLITE_OK ){
drha2de66c2019-08-06 20:26:17 +00006364 sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0,
6365 shellIdQuote, 0, 0);
6366 }
6367 if( rc==SQLITE_OK ){
dan38f9c712019-04-23 18:03:02 +00006368 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
6369 }
6370 if( rc==SQLITE_OK ){
danb40af492019-04-22 20:52:12 +00006371 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
6372 if( rc==SQLITE_ERROR ){
6373 rc = SQLITE_OK;
6374 goto finished;
6375 }
6376 }
6377 shellPreparePrintf(dbtmp, &rc, &pStmt,
6378 "SELECT count(*) FROM pragma_table_info(%Q)", zName
6379 );
6380 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6381 nSqlCol = sqlite3_column_int(pStmt, 0);
6382 }
6383 shellFinalize(&rc, pStmt);
6384
6385 if( rc!=SQLITE_OK || nSqlCol<nCol ){
6386 goto finished;
6387 }
6388
6389 shellPreparePrintf(dbtmp, &rc, &pStmt,
6390 "SELECT ("
6391 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
6392 ") FROM sqlite_master WHERE name = %Q", zName
6393 );
6394 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6395 bSqlIntkey = sqlite3_column_int(pStmt, 0);
6396 }
6397 shellFinalize(&rc, pStmt);
6398
6399 if( bIntkey==bSqlIntkey ){
dan98c5ad32019-04-26 21:11:37 +00006400 int i;
danb40af492019-04-22 20:52:12 +00006401 const char *zPk = "_rowid_";
6402 sqlite3_stmt *pPkFinder = 0;
6403
danf57bea32019-04-27 15:35:45 +00006404 /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
6405 ** set zPk to the name of the PK column, and pTab->iPk to the index
6406 ** of the column, where columns are 0-numbered from left to right.
6407 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
6408 ** leave zPk as "_rowid_" and pTab->iPk at -2. */
dan98c5ad32019-04-26 21:11:37 +00006409 pTab->iPk = -2;
6410 if( bIntkey ){
6411 shellPreparePrintf(dbtmp, &rc, &pPkFinder,
danb40af492019-04-22 20:52:12 +00006412 "SELECT cid, name FROM pragma_table_info(%Q) "
6413 " WHERE pk=1 AND type='integer' COLLATE nocase"
dan98c5ad32019-04-26 21:11:37 +00006414 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
6415 , zName, zName
6416 );
6417 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
6418 pTab->iPk = sqlite3_column_int(pPkFinder, 0);
6419 zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
6420 }
danb40af492019-04-22 20:52:12 +00006421 }
6422
drha2de66c2019-08-06 20:26:17 +00006423 pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName);
dan98c5ad32019-04-26 21:11:37 +00006424 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
danb40af492019-04-22 20:52:12 +00006425 pTab->nCol = nSqlCol;
6426
dan98c5ad32019-04-26 21:11:37 +00006427 if( bIntkey ){
drha2de66c2019-08-06 20:26:17 +00006428 pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk);
danb40af492019-04-22 20:52:12 +00006429 }else{
dan98c5ad32019-04-26 21:11:37 +00006430 pTab->azlCol[0] = shellMPrintf(&rc, "");
danb40af492019-04-22 20:52:12 +00006431 }
dan98c5ad32019-04-26 21:11:37 +00006432 i = 1;
6433 shellPreparePrintf(dbtmp, &rc, &pStmt,
drha2de66c2019-08-06 20:26:17 +00006434 "SELECT %Q || group_concat(shell_idquote(name), ', ') "
danf57bea32019-04-27 15:35:45 +00006435 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
dan98c5ad32019-04-26 21:11:37 +00006436 "FROM pragma_table_info(%Q)",
danf57bea32019-04-27 15:35:45 +00006437 bIntkey ? ", " : "", pTab->iPk,
6438 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
6439 zName
dan98c5ad32019-04-26 21:11:37 +00006440 );
6441 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6442 const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
6443 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
6444 i++;
6445 }
6446 shellFinalize(&rc, pStmt);
6447
danb40af492019-04-22 20:52:12 +00006448 shellFinalize(&rc, pPkFinder);
6449 }
6450 }
6451
6452 finished:
6453 sqlite3_close(dbtmp);
6454 *pRc = rc;
dan98779652019-05-09 14:15:19 +00006455 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){
dan98c5ad32019-04-26 21:11:37 +00006456 recoverFreeTable(pTab);
6457 pTab = 0;
6458 }
6459 return pTab;
danb40af492019-04-22 20:52:12 +00006460}
6461
dan0aa01ee2019-04-27 19:36:49 +00006462/*
6463** This function is called to search the schema recovered from the
6464** sqlite_master table of the (possibly) corrupt database as part
6465** of a ".recover" command. Specifically, for a table with root page
6466** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
6467** table must be a WITHOUT ROWID table, or if non-zero, not one of
6468** those.
6469**
6470** If a table is found, a (RecoverTable*) object is returned. Or, if
6471** no such table is found, but bIntkey is false and iRoot is the
6472** root page of an index in the recovered schema, then (*pbNoop) is
6473** set to true and NULL returned. Or, if there is no such table or
6474** index, NULL is returned and (*pbNoop) set to 0, indicating that
6475** the caller should write data to the orphans table.
6476*/
dan42ebb012019-04-27 18:47:03 +00006477static RecoverTable *recoverFindTable(
dan0aa01ee2019-04-27 19:36:49 +00006478 ShellState *pState, /* Shell state object */
6479 int *pRc, /* IN/OUT: Error code */
6480 int iRoot, /* Root page of table */
6481 int bIntkey, /* True for an intkey table */
6482 int nCol, /* Number of columns in table */
6483 int *pbNoop /* OUT: True if iRoot is root of index */
dan68cb86e2019-04-20 20:57:28 +00006484){
danb40af492019-04-22 20:52:12 +00006485 sqlite3_stmt *pStmt = 0;
dan68cb86e2019-04-20 20:57:28 +00006486 RecoverTable *pRet = 0;
danb40af492019-04-22 20:52:12 +00006487 int bNoop = 0;
6488 const char *zSql = 0;
6489 const char *zName = 0;
dan68cb86e2019-04-20 20:57:28 +00006490
danb40af492019-04-22 20:52:12 +00006491 /* Search the recovered schema for an object with root page iRoot. */
6492 shellPreparePrintf(pState->db, pRc, &pStmt,
6493 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
6494 );
6495 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6496 const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
6497 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
6498 bNoop = 1;
6499 break;
6500 }
6501 if( sqlite3_stricmp(zType, "table")==0 ){
6502 zName = (const char*)sqlite3_column_text(pStmt, 1);
6503 zSql = (const char*)sqlite3_column_text(pStmt, 2);
dan42ebb012019-04-27 18:47:03 +00006504 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
danb40af492019-04-22 20:52:12 +00006505 break;
6506 }
6507 }
dan98c5ad32019-04-26 21:11:37 +00006508
danb40af492019-04-22 20:52:12 +00006509 shellFinalize(pRc, pStmt);
dan98c5ad32019-04-26 21:11:37 +00006510 *pbNoop = bNoop;
6511 return pRet;
6512}
danb40af492019-04-22 20:52:12 +00006513
dan0aa01ee2019-04-27 19:36:49 +00006514/*
6515** Return a RecoverTable object representing the orphans table.
6516*/
dan98c5ad32019-04-26 21:11:37 +00006517static RecoverTable *recoverOrphanTable(
dan0aa01ee2019-04-27 19:36:49 +00006518 ShellState *pState, /* Shell state object */
6519 int *pRc, /* IN/OUT: Error code */
6520 const char *zLostAndFound, /* Base name for orphans table */
6521 int nCol /* Number of user data columns */
dan98c5ad32019-04-26 21:11:37 +00006522){
6523 RecoverTable *pTab = 0;
6524 if( nCol>=0 && *pRc==SQLITE_OK ){
6525 int i;
dan42ebb012019-04-27 18:47:03 +00006526
6527 /* This block determines the name of the orphan table. The prefered
6528 ** name is zLostAndFound. But if that clashes with another name
6529 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
6530 ** and so on until a non-clashing name is found. */
6531 int iTab = 0;
6532 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
6533 sqlite3_stmt *pTest = 0;
6534 shellPrepare(pState->db, pRc,
6535 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
dan68cb86e2019-04-20 20:57:28 +00006536 );
dan42ebb012019-04-27 18:47:03 +00006537 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
6538 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
6539 shellReset(pRc, pTest);
6540 sqlite3_free(zTab);
6541 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
6542 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
dan68cb86e2019-04-20 20:57:28 +00006543 }
dan42ebb012019-04-27 18:47:03 +00006544 shellFinalize(pRc, pTest);
dan68cb86e2019-04-20 20:57:28 +00006545
dan98c5ad32019-04-26 21:11:37 +00006546 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
6547 if( pTab ){
drha2de66c2019-08-06 20:26:17 +00006548 pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab);
dan98c5ad32019-04-26 21:11:37 +00006549 pTab->nCol = nCol;
6550 pTab->iPk = -2;
6551 if( nCol>0 ){
6552 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
6553 if( pTab->azlCol ){
6554 pTab->azlCol[nCol] = shellMPrintf(pRc, "");
6555 for(i=nCol-1; i>=0; i--){
6556 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
6557 }
6558 }
danb40af492019-04-22 20:52:12 +00006559 }
dan68cb86e2019-04-20 20:57:28 +00006560
dan42ebb012019-04-27 18:47:03 +00006561 if( *pRc!=SQLITE_OK ){
6562 recoverFreeTable(pTab);
6563 pTab = 0;
6564 }else{
6565 raw_printf(pState->out,
6566 "CREATE TABLE %s(rootpgno INTEGER, "
6567 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
6568 );
6569 for(i=0; i<nCol; i++){
6570 raw_printf(pState->out, ", c%d", i);
6571 }
6572 raw_printf(pState->out, ");\n");
6573 }
dan98c5ad32019-04-26 21:11:37 +00006574 }
dan42ebb012019-04-27 18:47:03 +00006575 sqlite3_free(zTab);
dan68cb86e2019-04-20 20:57:28 +00006576 }
dan98c5ad32019-04-26 21:11:37 +00006577 return pTab;
dan68cb86e2019-04-20 20:57:28 +00006578}
6579
6580/*
6581** This function is called to recover data from the database. A script
6582** to construct a new database containing all recovered data is output
6583** on stream pState->out.
6584*/
danb9b71db2019-04-25 16:20:40 +00006585static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
dan68cb86e2019-04-20 20:57:28 +00006586 int rc = SQLITE_OK;
6587 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */
danefa363b2019-04-24 20:48:55 +00006588 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */
6589 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */
danc0b42432019-04-26 15:14:53 +00006590 const char *zRecoveryDb = ""; /* Name of "recovery" database */
dan42ebb012019-04-27 18:47:03 +00006591 const char *zLostAndFound = "lost_and_found";
dan9c014f82019-04-25 19:23:15 +00006592 int i;
dan98c5ad32019-04-26 21:11:37 +00006593 int nOrphan = -1;
6594 RecoverTable *pOrphan = 0;
dan9c014f82019-04-25 19:23:15 +00006595
6596 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */
dan8cce6b82019-09-14 16:44:51 +00006597 int bRowids = 1; /* 0 if --no-rowids */
dan9c014f82019-04-25 19:23:15 +00006598 for(i=1; i<nArg; i++){
6599 char *z = azArg[i];
6600 int n;
6601 if( z[0]=='-' && z[1]=='-' ) z++;
drh4245e042019-06-13 13:52:46 +00006602 n = strlen30(z);
dan9c014f82019-04-25 19:23:15 +00006603 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
6604 bFreelist = 0;
dan42ebb012019-04-27 18:47:03 +00006605 }else
danc0b42432019-04-26 15:14:53 +00006606 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
6607 i++;
6608 zRecoveryDb = azArg[i];
dan42ebb012019-04-27 18:47:03 +00006609 }else
6610 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
6611 i++;
6612 zLostAndFound = azArg[i];
dan8cce6b82019-09-14 16:44:51 +00006613 }else
6614 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
6615 bRowids = 0;
danc0b42432019-04-26 15:14:53 +00006616 }
dan9c014f82019-04-25 19:23:15 +00006617 else{
drhe2754c12019-08-26 12:50:01 +00006618 utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
6619 showHelp(pState->out, azArg[0]);
dan9c014f82019-04-25 19:23:15 +00006620 return 1;
6621 }
6622 }
dan68cb86e2019-04-20 20:57:28 +00006623
danc0b42432019-04-26 15:14:53 +00006624 shellExecPrintf(pState->db, &rc,
dan68cb86e2019-04-20 20:57:28 +00006625 /* Attach an in-memory database named 'recovery'. Create an indexed
6626 ** cache of the sqlite_dbptr virtual table. */
dan01c08bc2019-07-24 19:20:30 +00006627 "PRAGMA writable_schema = on;"
danc0b42432019-04-26 15:14:53 +00006628 "ATTACH %Q AS recovery;"
6629 "DROP TABLE IF EXISTS recovery.dbptr;"
6630 "DROP TABLE IF EXISTS recovery.freelist;"
6631 "DROP TABLE IF EXISTS recovery.map;"
6632 "DROP TABLE IF EXISTS recovery.schema;"
danc0b42432019-04-26 15:14:53 +00006633 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
dan9c014f82019-04-25 19:23:15 +00006634 );
6635
6636 if( bFreelist ){
6637 shellExec(pState->db, &rc,
6638 "WITH trunk(pgno) AS ("
6639 " SELECT shell_int32("
6640 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
6641 " WHERE x>0"
6642 " UNION"
6643 " SELECT shell_int32("
6644 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
6645 " FROM trunk WHERE x>0"
6646 "),"
6647 "freelist(data, n, freepgno) AS ("
danf6099e92019-05-09 16:57:39 +00006648 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno "
dan9c014f82019-04-25 19:23:15 +00006649 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
6650 " UNION ALL"
6651 " SELECT data, n-1, shell_int32(data, 2+n) "
6652 " FROM freelist WHERE n>=0"
6653 ")"
6654 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
6655 );
6656 }
6657
dan95063c22019-07-24 08:15:09 +00006658 /* If this is an auto-vacuum database, add all pointer-map pages to
6659 ** the freelist table. Do this regardless of whether or not
6660 ** --freelist-corrupt was specified. */
6661 shellExec(pState->db, &rc,
6662 "WITH ptrmap(pgno) AS ("
6663 " SELECT 2 WHERE shell_int32("
6664 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13"
6665 " )"
6666 " UNION ALL "
6667 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp "
6668 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)"
6669 ")"
6670 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap"
6671 );
6672
dan9c014f82019-04-25 19:23:15 +00006673 shellExec(pState->db, &rc,
danca424382019-04-26 15:40:27 +00006674 "CREATE TABLE recovery.dbptr("
6675 " pgno, child, PRIMARY KEY(child, pgno)"
6676 ") WITHOUT ROWID;"
6677 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
6678 " SELECT * FROM sqlite_dbptr"
6679 " WHERE pgno NOT IN freelist AND child NOT IN freelist;"
6680
6681 /* Delete any pointer to page 1. This ensures that page 1 is considered
6682 ** a root page, regardless of how corrupt the db is. */
6683 "DELETE FROM recovery.dbptr WHERE child = 1;"
6684
6685 /* Delete all pointers to any pages that have more than one pointer
6686 ** to them. Such pages will be treated as root pages when recovering
6687 ** data. */
6688 "DELETE FROM recovery.dbptr WHERE child IN ("
6689 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
6690 ");"
6691
dan68cb86e2019-04-20 20:57:28 +00006692 /* Create the "map" table that will (eventually) contain instructions
6693 ** for dealing with each page in the db that contains one or more
6694 ** records. */
danb40af492019-04-22 20:52:12 +00006695 "CREATE TABLE recovery.map("
6696 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
6697 ");"
dan68cb86e2019-04-20 20:57:28 +00006698
6699 /* Populate table [map]. If there are circular loops of pages in the
6700 ** database, the following adds all pages in such a loop to the map
6701 ** as individual root pages. This could be handled better. */
6702 "WITH pages(i, maxlen) AS ("
danb9b71db2019-04-25 16:20:40 +00006703 " SELECT page_count, ("
6704 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
dan13b87672019-05-09 11:45:21 +00006705 " ) FROM pragma_page_count WHERE page_count>0"
dan68cb86e2019-04-20 20:57:28 +00006706 " UNION ALL"
danb40af492019-04-22 20:52:12 +00006707 " SELECT i-1, ("
6708 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
6709 " ) FROM pages WHERE i>=2"
dan68cb86e2019-04-20 20:57:28 +00006710 ")"
danb40af492019-04-22 20:52:12 +00006711 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
6712 " SELECT i, maxlen, NULL, ("
dan68cb86e2019-04-20 20:57:28 +00006713 " WITH p(orig, pgno, parent) AS ("
6714 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
dan39e04f82019-05-09 18:33:32 +00006715 " UNION "
dan68cb86e2019-04-20 20:57:28 +00006716 " SELECT i, p.parent, "
6717 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
6718 " )"
6719 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
6720 ") "
dand790c9a2019-08-26 14:57:58 +00006721 "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;"
danb40af492019-04-22 20:52:12 +00006722 "UPDATE recovery.map AS o SET intkey = ("
6723 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
6724 ");"
dan68cb86e2019-04-20 20:57:28 +00006725
6726 /* Extract data from page 1 and any linked pages into table
6727 ** recovery.schema. With the same schema as an sqlite_master table. */
6728 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
6729 "INSERT INTO recovery.schema SELECT "
6730 " max(CASE WHEN field=0 THEN value ELSE NULL END),"
6731 " max(CASE WHEN field=1 THEN value ELSE NULL END),"
6732 " max(CASE WHEN field=2 THEN value ELSE NULL END),"
6733 " max(CASE WHEN field=3 THEN value ELSE NULL END),"
6734 " max(CASE WHEN field=4 THEN value ELSE NULL END)"
6735 "FROM sqlite_dbdata WHERE pgno IN ("
6736 " SELECT pgno FROM recovery.map WHERE root=1"
6737 ")"
6738 "GROUP BY pgno, cell;"
dan98c5ad32019-04-26 21:11:37 +00006739 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
dan68cb86e2019-04-20 20:57:28 +00006740 );
6741
danb40af492019-04-22 20:52:12 +00006742 /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
6743 ** CREATE TABLE statements that extracted from the existing schema. */
6744 if( rc==SQLITE_OK ){
6745 sqlite3_stmt *pStmt = 0;
danf3210572019-08-06 18:40:36 +00006746 /* ".recover" might output content in an order which causes immediate
6747 ** foreign key constraints to be violated. So disable foreign-key
6748 ** constraint enforcement to prevent problems when running the output
6749 ** script. */
6750 raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n");
danb40af492019-04-22 20:52:12 +00006751 raw_printf(pState->out, "BEGIN;\n");
dan38f9c712019-04-23 18:03:02 +00006752 raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
6753 shellPrepare(pState->db, &rc,
danb40af492019-04-22 20:52:12 +00006754 "SELECT sql FROM recovery.schema "
dan38f9c712019-04-23 18:03:02 +00006755 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
danb40af492019-04-22 20:52:12 +00006756 );
6757 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6758 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
dan38f9c712019-04-23 18:03:02 +00006759 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
6760 &zCreateTable[12]
6761 );
danb40af492019-04-22 20:52:12 +00006762 }
6763 shellFinalize(&rc, pStmt);
6764 }
6765
dan98c5ad32019-04-26 21:11:37 +00006766 /* Figure out if an orphan table will be required. And if so, how many
6767 ** user columns it should contain */
6768 shellPrepare(pState->db, &rc,
dan98779652019-05-09 14:15:19 +00006769 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1"
dan98c5ad32019-04-26 21:11:37 +00006770 , &pLoop
6771 );
6772 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6773 nOrphan = sqlite3_column_int(pLoop, 0);
6774 }
6775 shellFinalize(&rc, pLoop);
6776 pLoop = 0;
dan98c5ad32019-04-26 21:11:37 +00006777
danefa363b2019-04-24 20:48:55 +00006778 shellPrepare(pState->db, &rc,
6779 "SELECT pgno FROM recovery.map WHERE root=?", &pPages
6780 );
dan8cce6b82019-09-14 16:44:51 +00006781
danefa363b2019-04-24 20:48:55 +00006782 shellPrepare(pState->db, &rc,
dan8cce6b82019-09-14 16:44:51 +00006783 "SELECT max(field), group_concat(shell_escape_crnl(quote"
6784 "(case when (? AND field<0) then NULL else value end)"
6785 "), ', ')"
dan9443dbc2019-07-24 20:10:27 +00006786 ", min(field) "
danefa363b2019-04-24 20:48:55 +00006787 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
6788 "GROUP BY cell", &pCells
6789 );
6790
dan68cb86e2019-04-20 20:57:28 +00006791 /* Loop through each root page. */
danb40af492019-04-22 20:52:12 +00006792 shellPrepare(pState->db, &rc,
6793 "SELECT root, intkey, max(maxlen) FROM recovery.map"
dan38f9c712019-04-23 18:03:02 +00006794 " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
6795 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
6796 ")", &pLoop
danb40af492019-04-22 20:52:12 +00006797 );
dan68cb86e2019-04-20 20:57:28 +00006798 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6799 int iRoot = sqlite3_column_int(pLoop, 0);
danb40af492019-04-22 20:52:12 +00006800 int bIntkey = sqlite3_column_int(pLoop, 1);
6801 int nCol = sqlite3_column_int(pLoop, 2);
dan98c5ad32019-04-26 21:11:37 +00006802 int bNoop = 0;
dan68cb86e2019-04-20 20:57:28 +00006803 RecoverTable *pTab;
6804
dan9443dbc2019-07-24 20:10:27 +00006805 assert( bIntkey==0 || bIntkey==1 );
dan42ebb012019-04-27 18:47:03 +00006806 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
dan98c5ad32019-04-26 21:11:37 +00006807 if( bNoop || rc ) continue;
dan98779652019-05-09 14:15:19 +00006808 if( pTab==0 ){
6809 if( pOrphan==0 ){
6810 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
6811 }
6812 pTab = pOrphan;
6813 if( pTab==0 ) break;
6814 }
dan98c5ad32019-04-26 21:11:37 +00006815
drha2de66c2019-08-06 20:26:17 +00006816 if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){
dan98c5ad32019-04-26 21:11:37 +00006817 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
6818 }
6819 sqlite3_bind_int(pPages, 1, iRoot);
dan8cce6b82019-09-14 16:44:51 +00006820 if( bRowids==0 && pTab->iPk<0 ){
6821 sqlite3_bind_int(pCells, 1, 1);
6822 }else{
6823 sqlite3_bind_int(pCells, 1, 0);
6824 }
6825 sqlite3_bind_int(pCells, 3, pTab->iPk);
dan98c5ad32019-04-26 21:11:37 +00006826
6827 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
6828 int iPgno = sqlite3_column_int(pPages, 0);
dan8cce6b82019-09-14 16:44:51 +00006829 sqlite3_bind_int(pCells, 2, iPgno);
dan98c5ad32019-04-26 21:11:37 +00006830 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
6831 int nField = sqlite3_column_int(pCells, 0);
dan9443dbc2019-07-24 20:10:27 +00006832 int iMin = sqlite3_column_int(pCells, 2);
dan98c5ad32019-04-26 21:11:37 +00006833 const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
6834
dan9443dbc2019-07-24 20:10:27 +00006835 RecoverTable *pTab2 = pTab;
6836 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){
6837 if( pOrphan==0 ){
6838 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
6839 }
6840 pTab2 = pOrphan;
6841 if( pTab2==0 ) break;
6842 }
6843
dan98c5ad32019-04-26 21:11:37 +00006844 nField = nField+1;
dan9443dbc2019-07-24 20:10:27 +00006845 if( pTab2==pOrphan ){
dan98c5ad32019-04-26 21:11:37 +00006846 raw_printf(pState->out,
6847 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
dan9443dbc2019-07-24 20:10:27 +00006848 pTab2->zQuoted, iRoot, iPgno, nField,
6849 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField]
dan98c5ad32019-04-26 21:11:37 +00006850 );
6851 }else{
danefa363b2019-04-24 20:48:55 +00006852 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
dan9443dbc2019-07-24 20:10:27 +00006853 pTab2->zQuoted, pTab2->azlCol[nField], zVal
danefa363b2019-04-24 20:48:55 +00006854 );
6855 }
dan68cb86e2019-04-20 20:57:28 +00006856 }
dan98c5ad32019-04-26 21:11:37 +00006857 shellReset(&rc, pCells);
dan68cb86e2019-04-20 20:57:28 +00006858 }
dan98c5ad32019-04-26 21:11:37 +00006859 shellReset(&rc, pPages);
6860 if( pTab!=pOrphan ) recoverFreeTable(pTab);
dan68cb86e2019-04-20 20:57:28 +00006861 }
6862 shellFinalize(&rc, pLoop);
danefa363b2019-04-24 20:48:55 +00006863 shellFinalize(&rc, pPages);
6864 shellFinalize(&rc, pCells);
dan98c5ad32019-04-26 21:11:37 +00006865 recoverFreeTable(pOrphan);
dan68cb86e2019-04-20 20:57:28 +00006866
dan38f9c712019-04-23 18:03:02 +00006867 /* The rest of the schema */
danb40af492019-04-22 20:52:12 +00006868 if( rc==SQLITE_OK ){
dan38f9c712019-04-23 18:03:02 +00006869 sqlite3_stmt *pStmt = 0;
6870 shellPrepare(pState->db, &rc,
6871 "SELECT sql, name FROM recovery.schema "
danb1825882019-04-23 20:48:32 +00006872 "WHERE sql NOT LIKE 'create table%'", &pStmt
dan38f9c712019-04-23 18:03:02 +00006873 );
6874 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6875 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
6876 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
6877 const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
6878 char *zPrint = shellMPrintf(&rc,
6879 "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)",
6880 zName, zName, zSql
6881 );
6882 raw_printf(pState->out, "%s;\n", zPrint);
6883 sqlite3_free(zPrint);
6884 }else{
6885 raw_printf(pState->out, "%s;\n", zSql);
6886 }
6887 }
6888 shellFinalize(&rc, pStmt);
6889 }
6890
6891 if( rc==SQLITE_OK ){
6892 raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
danb40af492019-04-22 20:52:12 +00006893 raw_printf(pState->out, "COMMIT;\n");
6894 }
dan68cb86e2019-04-20 20:57:28 +00006895 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
6896 return rc;
6897}
dan1b162162019-04-27 20:15:15 +00006898#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
dan68cb86e2019-04-20 20:57:28 +00006899
drh2ce15c32017-07-11 13:34:40 +00006900
6901/*
6902** If an input line begins with "." then invoke this routine to
6903** process that line.
6904**
6905** Return 1 on error, 2 to exit, and 0 otherwise.
6906*/
6907static int do_meta_command(char *zLine, ShellState *p){
6908 int h = 1;
6909 int nArg = 0;
6910 int n, c;
6911 int rc = 0;
drh5df84282019-08-17 19:45:25 +00006912 char *azArg[52];
drh2ce15c32017-07-11 13:34:40 +00006913
dan6b046be2018-01-09 15:25:55 +00006914#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006915 if( p->expert.pExpert ){
6916 expertFinish(p, 1, 0);
6917 }
dan6b046be2018-01-09 15:25:55 +00006918#endif
dan43efc182017-12-19 17:42:13 +00006919
drh2ce15c32017-07-11 13:34:40 +00006920 /* Parse the input line into tokens.
6921 */
drh5df84282019-08-17 19:45:25 +00006922 while( zLine[h] && nArg<ArraySize(azArg)-1 ){
drh2ce15c32017-07-11 13:34:40 +00006923 while( IsSpace(zLine[h]) ){ h++; }
6924 if( zLine[h]==0 ) break;
6925 if( zLine[h]=='\'' || zLine[h]=='"' ){
6926 int delim = zLine[h++];
6927 azArg[nArg++] = &zLine[h];
6928 while( zLine[h] && zLine[h]!=delim ){
6929 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
6930 h++;
6931 }
6932 if( zLine[h]==delim ){
6933 zLine[h++] = 0;
6934 }
6935 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
6936 }else{
6937 azArg[nArg++] = &zLine[h];
6938 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
6939 if( zLine[h] ) zLine[h++] = 0;
6940 resolve_backslashes(azArg[nArg-1]);
6941 }
6942 }
drh5df84282019-08-17 19:45:25 +00006943 azArg[nArg] = 0;
drh2ce15c32017-07-11 13:34:40 +00006944
6945 /* Process the input line.
6946 */
6947 if( nArg==0 ) return 0; /* no tokens, no error */
6948 n = strlen30(azArg[0]);
6949 c = azArg[0][0];
drh13c20932018-01-10 21:41:55 +00006950 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00006951
6952#ifndef SQLITE_OMIT_AUTHORIZATION
6953 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
6954 if( nArg!=2 ){
6955 raw_printf(stderr, "Usage: .auth ON|OFF\n");
6956 rc = 1;
6957 goto meta_command_exit;
6958 }
6959 open_db(p, 0);
6960 if( booleanValue(azArg[1]) ){
6961 sqlite3_set_authorizer(p->db, shellAuth, p);
6962 }else{
6963 sqlite3_set_authorizer(p->db, 0, 0);
6964 }
6965 }else
6966#endif
6967
drhe37c0e12018-01-06 19:19:50 +00006968#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6969 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00006970 open_db(p, 0);
drhd0f9cdc2018-05-17 14:09:06 +00006971 rc = arDotCommand(p, 0, azArg, nArg);
danfd0245d2017-12-07 15:44:29 +00006972 }else
6973#endif
6974
drh2ce15c32017-07-11 13:34:40 +00006975 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
6976 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
6977 ){
6978 const char *zDestFile = 0;
6979 const char *zDb = 0;
6980 sqlite3 *pDest;
6981 sqlite3_backup *pBackup;
6982 int j;
drha50bffb2018-12-08 01:09:14 +00006983 int bAsync = 0;
drh69ed38a2018-05-14 00:23:08 +00006984 const char *zVfs = 0;
drh2ce15c32017-07-11 13:34:40 +00006985 for(j=1; j<nArg; j++){
6986 const char *z = azArg[j];
6987 if( z[0]=='-' ){
drh69ed38a2018-05-14 00:23:08 +00006988 if( z[1]=='-' ) z++;
6989 if( strcmp(z, "-append")==0 ){
6990 zVfs = "apndvfs";
6991 }else
drha50bffb2018-12-08 01:09:14 +00006992 if( strcmp(z, "-async")==0 ){
6993 bAsync = 1;
6994 }else
drh2ce15c32017-07-11 13:34:40 +00006995 {
6996 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
6997 return 1;
6998 }
6999 }else if( zDestFile==0 ){
7000 zDestFile = azArg[j];
7001 }else if( zDb==0 ){
7002 zDb = zDestFile;
7003 zDestFile = azArg[j];
7004 }else{
drha50bffb2018-12-08 01:09:14 +00007005 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
drh2ce15c32017-07-11 13:34:40 +00007006 return 1;
7007 }
7008 }
7009 if( zDestFile==0 ){
7010 raw_printf(stderr, "missing FILENAME argument on .backup\n");
7011 return 1;
7012 }
7013 if( zDb==0 ) zDb = "main";
drh69ed38a2018-05-14 00:23:08 +00007014 rc = sqlite3_open_v2(zDestFile, &pDest,
7015 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
drh2ce15c32017-07-11 13:34:40 +00007016 if( rc!=SQLITE_OK ){
7017 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9e804032018-05-18 17:11:50 +00007018 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00007019 return 1;
7020 }
drha50bffb2018-12-08 01:09:14 +00007021 if( bAsync ){
7022 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
7023 0, 0, 0);
7024 }
drh2ce15c32017-07-11 13:34:40 +00007025 open_db(p, 0);
7026 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
7027 if( pBackup==0 ){
7028 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9e804032018-05-18 17:11:50 +00007029 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00007030 return 1;
7031 }
7032 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
7033 sqlite3_backup_finish(pBackup);
7034 if( rc==SQLITE_DONE ){
7035 rc = 0;
7036 }else{
7037 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
7038 rc = 1;
7039 }
drh9e804032018-05-18 17:11:50 +00007040 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00007041 }else
7042
7043 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
7044 if( nArg==2 ){
7045 bail_on_error = booleanValue(azArg[1]);
7046 }else{
7047 raw_printf(stderr, "Usage: .bail on|off\n");
7048 rc = 1;
7049 }
7050 }else
7051
7052 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
7053 if( nArg==2 ){
7054 if( booleanValue(azArg[1]) ){
7055 setBinaryMode(p->out, 1);
7056 }else{
7057 setTextMode(p->out, 1);
7058 }
7059 }else{
7060 raw_printf(stderr, "Usage: .binary on|off\n");
7061 rc = 1;
7062 }
7063 }else
7064
7065 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
7066 if( nArg==2 ){
7067#if defined(_WIN32) || defined(WIN32)
7068 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
7069 rc = !SetCurrentDirectoryW(z);
7070 sqlite3_free(z);
7071#else
7072 rc = chdir(azArg[1]);
7073#endif
7074 if( rc ){
7075 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
7076 rc = 1;
7077 }
7078 }else{
7079 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
7080 rc = 1;
7081 }
7082 }else
7083
7084 /* The undocumented ".breakpoint" command causes a call to the no-op
7085 ** routine named test_breakpoint().
7086 */
7087 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
7088 test_breakpoint();
7089 }else
7090
7091 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
7092 if( nArg==2 ){
7093 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
7094 }else{
7095 raw_printf(stderr, "Usage: .changes on|off\n");
7096 rc = 1;
7097 }
7098 }else
7099
7100 /* Cancel output redirection, if it is currently set (by .testcase)
7101 ** Then read the content of the testcase-out.txt file and compare against
7102 ** azArg[1]. If there are differences, report an error and exit.
7103 */
7104 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
7105 char *zRes = 0;
7106 output_reset(p);
7107 if( nArg!=2 ){
7108 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
7109 rc = 2;
7110 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
7111 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
7112 rc = 2;
7113 }else if( testcase_glob(azArg[1],zRes)==0 ){
7114 utf8_printf(stderr,
7115 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
7116 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00007117 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00007118 }else{
7119 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
7120 p->nCheck++;
7121 }
7122 sqlite3_free(zRes);
7123 }else
7124
7125 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
7126 if( nArg==2 ){
7127 tryToClone(p, azArg[1]);
7128 }else{
7129 raw_printf(stderr, "Usage: .clone FILENAME\n");
7130 rc = 1;
7131 }
7132 }else
7133
7134 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
7135 ShellState data;
7136 char *zErrMsg = 0;
7137 open_db(p, 0);
7138 memcpy(&data, p, sizeof(data));
7139 data.showHeader = 0;
7140 data.cMode = data.mode = MODE_List;
7141 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
7142 data.cnt = 0;
7143 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
7144 callback, &data, &zErrMsg);
7145 if( zErrMsg ){
7146 utf8_printf(stderr,"Error: %s\n", zErrMsg);
7147 sqlite3_free(zErrMsg);
7148 rc = 1;
7149 }
7150 }else
7151
drh7df01192018-04-28 12:43:16 +00007152 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
drheb7f2a02018-09-26 18:02:32 +00007153 static const struct DbConfigChoices {
7154 const char *zName;
7155 int op;
7156 } aDbConfig[] = {
drh0a6873b2019-06-14 21:25:25 +00007157 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
7158 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
drh11d88e62019-08-15 21:27:20 +00007159 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW },
drh0a6873b2019-06-14 21:25:25 +00007160 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7161 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7162 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
7163 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
7164 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
7165 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
7166 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
dan07312a62019-06-21 14:05:27 +00007167 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA },
drh0a6873b2019-06-14 21:25:25 +00007168 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE },
drhd0ff6012019-06-17 13:56:11 +00007169 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML },
7170 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL },
drh7df01192018-04-28 12:43:16 +00007171 };
7172 int ii, v;
7173 open_db(p, 0);
7174 for(ii=0; ii<ArraySize(aDbConfig); ii++){
7175 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7176 if( nArg>=3 ){
7177 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7178 }
7179 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7180 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7181 if( nArg>1 ) break;
7182 }
7183 if( nArg>1 && ii==ArraySize(aDbConfig) ){
7184 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7185 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7186 }
7187 }else
7188
7189 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007190 rc = shell_dbinfo_command(p, nArg, azArg);
7191 }else
7192
dan1b162162019-04-27 20:15:15 +00007193#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
dan68cb86e2019-04-20 20:57:28 +00007194 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7195 open_db(p, 0);
danb9b71db2019-04-25 16:20:40 +00007196 rc = recoverDatabaseCmd(p, nArg, azArg);
dan68cb86e2019-04-20 20:57:28 +00007197 }else
dan1b162162019-04-27 20:15:15 +00007198#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
dan68cb86e2019-04-20 20:57:28 +00007199
drh2ce15c32017-07-11 13:34:40 +00007200 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7201 const char *zLike = 0;
7202 int i;
7203 int savedShowHeader = p->showHeader;
drhf213b332018-07-05 17:35:46 +00007204 int savedShellFlags = p->shellFlgs;
7205 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
drh2ce15c32017-07-11 13:34:40 +00007206 for(i=1; i<nArg; i++){
7207 if( azArg[i][0]=='-' ){
7208 const char *z = azArg[i]+1;
7209 if( z[0]=='-' ) z++;
7210 if( strcmp(z,"preserve-rowids")==0 ){
7211#ifdef SQLITE_OMIT_VIRTUALTABLE
7212 raw_printf(stderr, "The --preserve-rowids option is not compatible"
7213 " with SQLITE_OMIT_VIRTUALTABLE\n");
7214 rc = 1;
7215 goto meta_command_exit;
7216#else
7217 ShellSetFlag(p, SHFLG_PreserveRowid);
7218#endif
7219 }else
7220 if( strcmp(z,"newlines")==0 ){
7221 ShellSetFlag(p, SHFLG_Newlines);
7222 }else
7223 {
7224 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7225 rc = 1;
7226 goto meta_command_exit;
7227 }
7228 }else if( zLike ){
7229 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
7230 "?--newlines? ?LIKE-PATTERN?\n");
7231 rc = 1;
7232 goto meta_command_exit;
7233 }else{
7234 zLike = azArg[i];
7235 }
7236 }
dan68cb86e2019-04-20 20:57:28 +00007237
drh2ce15c32017-07-11 13:34:40 +00007238 open_db(p, 0);
dan68cb86e2019-04-20 20:57:28 +00007239
drh2ce15c32017-07-11 13:34:40 +00007240 /* When playing back a "dump", the content might appear in an order
7241 ** which causes immediate foreign key constraints to be violated.
7242 ** So disable foreign-key constraint enforcement to prevent problems. */
7243 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
7244 raw_printf(p->out, "BEGIN TRANSACTION;\n");
7245 p->writableSchema = 0;
7246 p->showHeader = 0;
7247 /* Set writable_schema=ON since doing so forces SQLite to initialize
7248 ** as much of the schema as it can even if the sqlite_master table is
7249 ** corrupt. */
7250 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
7251 p->nErr = 0;
7252 if( zLike==0 ){
7253 run_schema_dump_query(p,
dan42ebb012019-04-27 18:47:03 +00007254 "SELECT name, type, sql FROM sqlite_master "
7255 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
7256 );
drh2ce15c32017-07-11 13:34:40 +00007257 run_schema_dump_query(p,
dan42ebb012019-04-27 18:47:03 +00007258 "SELECT name, type, sql FROM sqlite_master "
7259 "WHERE name=='sqlite_sequence'"
7260 );
drh2ce15c32017-07-11 13:34:40 +00007261 run_table_dump_query(p,
dan42ebb012019-04-27 18:47:03 +00007262 "SELECT sql FROM sqlite_master "
7263 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
7264 );
drh2ce15c32017-07-11 13:34:40 +00007265 }else{
7266 char *zSql;
7267 zSql = sqlite3_mprintf(
dan42ebb012019-04-27 18:47:03 +00007268 "SELECT name, type, sql FROM sqlite_master "
7269 "WHERE tbl_name LIKE %Q AND type=='table'"
7270 " AND sql NOT NULL", zLike);
drh2ce15c32017-07-11 13:34:40 +00007271 run_schema_dump_query(p,zSql);
7272 sqlite3_free(zSql);
7273 zSql = sqlite3_mprintf(
dan42ebb012019-04-27 18:47:03 +00007274 "SELECT sql FROM sqlite_master "
7275 "WHERE sql NOT NULL"
7276 " AND type IN ('index','trigger','view')"
7277 " AND tbl_name LIKE %Q", zLike);
drh2ce15c32017-07-11 13:34:40 +00007278 run_table_dump_query(p, zSql, 0);
7279 sqlite3_free(zSql);
7280 }
7281 if( p->writableSchema ){
7282 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
7283 p->writableSchema = 0;
7284 }
7285 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
7286 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
dan68cb86e2019-04-20 20:57:28 +00007287 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
drh2ce15c32017-07-11 13:34:40 +00007288 p->showHeader = savedShowHeader;
drhf213b332018-07-05 17:35:46 +00007289 p->shellFlgs = savedShellFlags;
drh2ce15c32017-07-11 13:34:40 +00007290 }else
7291
7292 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
7293 if( nArg==2 ){
7294 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
7295 }else{
7296 raw_printf(stderr, "Usage: .echo on|off\n");
7297 rc = 1;
7298 }
7299 }else
7300
7301 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
7302 if( nArg==2 ){
drhe2ca99c2018-05-02 00:33:43 +00007303 p->autoEQPtest = 0;
drhb4e50392019-01-26 15:40:04 +00007304 if( p->autoEQPtrace ){
7305 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
7306 p->autoEQPtrace = 0;
7307 }
drh2ce15c32017-07-11 13:34:40 +00007308 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00007309 p->autoEQP = AUTOEQP_full;
7310 }else if( strcmp(azArg[1],"trigger")==0 ){
7311 p->autoEQP = AUTOEQP_trigger;
drhb4e50392019-01-26 15:40:04 +00007312#ifdef SQLITE_DEBUG
drhe2ca99c2018-05-02 00:33:43 +00007313 }else if( strcmp(azArg[1],"test")==0 ){
7314 p->autoEQP = AUTOEQP_on;
7315 p->autoEQPtest = 1;
drhb4e50392019-01-26 15:40:04 +00007316 }else if( strcmp(azArg[1],"trace")==0 ){
7317 p->autoEQP = AUTOEQP_full;
7318 p->autoEQPtrace = 1;
7319 open_db(p, 0);
drhc07eee72019-01-27 19:50:56 +00007320 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
drhb4e50392019-01-26 15:40:04 +00007321 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
7322#endif
drh2ce15c32017-07-11 13:34:40 +00007323 }else{
mistachkinb71aa092018-01-23 00:05:18 +00007324 p->autoEQP = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007325 }
7326 }else{
drhb4e50392019-01-26 15:40:04 +00007327 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00007328 rc = 1;
7329 }
7330 }else
7331
7332 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
7333 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
7334 rc = 2;
7335 }else
7336
7337 /* The ".explain" command is automatic now. It is largely pointless. It
7338 ** retained purely for backwards compatibility */
7339 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
7340 int val = 1;
7341 if( nArg>=2 ){
7342 if( strcmp(azArg[1],"auto")==0 ){
7343 val = 99;
7344 }else{
7345 val = booleanValue(azArg[1]);
7346 }
7347 }
7348 if( val==1 && p->mode!=MODE_Explain ){
7349 p->normalMode = p->mode;
7350 p->mode = MODE_Explain;
7351 p->autoExplain = 0;
7352 }else if( val==0 ){
7353 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7354 p->autoExplain = 0;
7355 }else if( val==99 ){
7356 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7357 p->autoExplain = 1;
7358 }
7359 }else
7360
dan6b046be2018-01-09 15:25:55 +00007361#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00007362 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
7363 open_db(p, 0);
7364 expertDotCommand(p, azArg, nArg);
7365 }else
dan6b046be2018-01-09 15:25:55 +00007366#endif
dan43efc182017-12-19 17:42:13 +00007367
drhd985f722019-06-05 14:29:53 +00007368 if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){
7369 static const struct {
7370 const char *zCtrlName; /* Name of a test-control option */
7371 int ctrlCode; /* Integer code for that option */
7372 const char *zUsage; /* Usage notes */
7373 } aCtrl[] = {
7374 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" },
7375 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" },
7376 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/
7377 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" },
7378 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" },
7379 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/
7380 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" },
7381 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" },
7382 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" },
7383 };
7384 int filectrl = -1;
7385 int iCtrl = -1;
drh4245e042019-06-13 13:52:46 +00007386 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */
7387 int isOk = 0; /* 0: usage 1: %lld 2: no-result */
drhd985f722019-06-05 14:29:53 +00007388 int n2, i;
7389 const char *zCmd = 0;
7390
7391 open_db(p, 0);
7392 zCmd = nArg>=2 ? azArg[1] : "help";
7393
7394 /* The argument can optionally begin with "-" or "--" */
7395 if( zCmd[0]=='-' && zCmd[1] ){
7396 zCmd++;
7397 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7398 }
7399
7400 /* --help lists all file-controls */
7401 if( strcmp(zCmd,"help")==0 ){
7402 utf8_printf(p->out, "Available file-controls:\n");
7403 for(i=0; i<ArraySize(aCtrl); i++){
7404 utf8_printf(p->out, " .filectrl %s %s\n",
7405 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
7406 }
7407 rc = 1;
7408 goto meta_command_exit;
7409 }
7410
7411 /* convert filectrl text option to value. allow any unique prefix
7412 ** of the option name, or a numerical value. */
7413 n2 = strlen30(zCmd);
7414 for(i=0; i<ArraySize(aCtrl); i++){
7415 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
7416 if( filectrl<0 ){
7417 filectrl = aCtrl[i].ctrlCode;
7418 iCtrl = i;
7419 }else{
7420 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n"
7421 "Use \".filectrl --help\" for help\n", zCmd);
7422 rc = 1;
7423 goto meta_command_exit;
7424 }
7425 }
7426 }
7427 if( filectrl<0 ){
7428 utf8_printf(stderr,"Error: unknown file-control: %s\n"
7429 "Use \".filectrl --help\" for help\n", zCmd);
7430 }else{
7431 switch(filectrl){
7432 case SQLITE_FCNTL_SIZE_LIMIT: {
7433 if( nArg!=2 && nArg!=3 ) break;
7434 iRes = nArg==3 ? integerValue(azArg[2]) : -1;
7435 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
7436 isOk = 1;
7437 break;
7438 }
7439 case SQLITE_FCNTL_LOCK_TIMEOUT:
7440 case SQLITE_FCNTL_CHUNK_SIZE: {
7441 int x;
7442 if( nArg!=3 ) break;
7443 x = (int)integerValue(azArg[2]);
7444 sqlite3_file_control(p->db, 0, filectrl, &x);
7445 isOk = 2;
7446 break;
7447 }
7448 case SQLITE_FCNTL_PERSIST_WAL:
7449 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
7450 int x;
7451 if( nArg!=2 && nArg!=3 ) break;
7452 x = nArg==3 ? booleanValue(azArg[2]) : -1;
7453 sqlite3_file_control(p->db, 0, filectrl, &x);
7454 iRes = x;
7455 isOk = 1;
7456 break;
7457 }
7458 case SQLITE_FCNTL_HAS_MOVED: {
7459 int x;
7460 if( nArg!=2 ) break;
7461 sqlite3_file_control(p->db, 0, filectrl, &x);
7462 iRes = x;
7463 isOk = 1;
7464 break;
7465 }
7466 case SQLITE_FCNTL_TEMPFILENAME: {
7467 char *z = 0;
7468 if( nArg!=2 ) break;
7469 sqlite3_file_control(p->db, 0, filectrl, &z);
7470 if( z ){
7471 utf8_printf(p->out, "%s\n", z);
7472 sqlite3_free(z);
7473 }
7474 isOk = 2;
7475 break;
7476 }
7477 }
7478 }
7479 if( isOk==0 && iCtrl>=0 ){
7480 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
7481 rc = 1;
7482 }else if( isOk==1 ){
drhe2500762019-06-13 14:07:41 +00007483 char zBuf[100];
7484 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes);
7485 raw_printf(p->out, "%s\n", zBuf);
drhd985f722019-06-05 14:29:53 +00007486 }
7487 }else
7488
drh2ce15c32017-07-11 13:34:40 +00007489 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
7490 ShellState data;
7491 char *zErrMsg = 0;
7492 int doStats = 0;
7493 memcpy(&data, p, sizeof(data));
7494 data.showHeader = 0;
7495 data.cMode = data.mode = MODE_Semi;
7496 if( nArg==2 && optionMatch(azArg[1], "indent") ){
7497 data.cMode = data.mode = MODE_Pretty;
7498 nArg = 1;
7499 }
7500 if( nArg!=1 ){
7501 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
7502 rc = 1;
7503 goto meta_command_exit;
7504 }
7505 open_db(p, 0);
7506 rc = sqlite3_exec(p->db,
7507 "SELECT sql FROM"
7508 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
7509 " FROM sqlite_master UNION ALL"
7510 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
7511 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
7512 "ORDER BY rowid",
7513 callback, &data, &zErrMsg
7514 );
7515 if( rc==SQLITE_OK ){
7516 sqlite3_stmt *pStmt;
7517 rc = sqlite3_prepare_v2(p->db,
7518 "SELECT rowid FROM sqlite_master"
7519 " WHERE name GLOB 'sqlite_stat[134]'",
7520 -1, &pStmt, 0);
7521 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
7522 sqlite3_finalize(pStmt);
7523 }
7524 if( doStats==0 ){
7525 raw_printf(p->out, "/* No STAT tables available */\n");
7526 }else{
7527 raw_printf(p->out, "ANALYZE sqlite_master;\n");
7528 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
7529 callback, &data, &zErrMsg);
7530 data.cMode = data.mode = MODE_Insert;
7531 data.zDestTable = "sqlite_stat1";
drh4c540452018-05-08 23:17:36 +00007532 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007533 data.zDestTable = "sqlite_stat4";
drh4c540452018-05-08 23:17:36 +00007534 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007535 raw_printf(p->out, "ANALYZE sqlite_master;\n");
7536 }
7537 }else
7538
7539 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
7540 if( nArg==2 ){
7541 p->showHeader = booleanValue(azArg[1]);
7542 }else{
7543 raw_printf(stderr, "Usage: .headers on|off\n");
7544 rc = 1;
7545 }
7546 }else
7547
7548 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
drh98aa2ab2018-09-26 16:53:51 +00007549 if( nArg>=2 ){
drhe93f8262018-10-11 16:53:37 +00007550 n = showHelp(p->out, azArg[1]);
drh98aa2ab2018-09-26 16:53:51 +00007551 if( n==0 ){
7552 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
7553 }
7554 }else{
7555 showHelp(p->out, 0);
7556 }
drh2ce15c32017-07-11 13:34:40 +00007557 }else
7558
7559 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
7560 char *zTable; /* Insert data into this table */
7561 char *zFile; /* Name of file to extra content from */
7562 sqlite3_stmt *pStmt = NULL; /* A statement */
7563 int nCol; /* Number of columns in the table */
7564 int nByte; /* Number of bytes in an SQL string */
7565 int i, j; /* Loop counters */
7566 int needCommit; /* True to COMMIT or ROLLBACK at end */
7567 int nSep; /* Number of bytes in p->colSeparator[] */
7568 char *zSql; /* An SQL statement */
7569 ImportCtx sCtx; /* Reader context */
7570 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
7571 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
7572
7573 if( nArg!=3 ){
7574 raw_printf(stderr, "Usage: .import FILE TABLE\n");
7575 goto meta_command_exit;
7576 }
7577 zFile = azArg[1];
7578 zTable = azArg[2];
7579 seenInterrupt = 0;
7580 memset(&sCtx, 0, sizeof(sCtx));
7581 open_db(p, 0);
7582 nSep = strlen30(p->colSeparator);
7583 if( nSep==0 ){
7584 raw_printf(stderr,
7585 "Error: non-null column separator required for import\n");
7586 return 1;
7587 }
7588 if( nSep>1 ){
7589 raw_printf(stderr, "Error: multi-character column separators not allowed"
7590 " for import\n");
7591 return 1;
7592 }
7593 nSep = strlen30(p->rowSeparator);
7594 if( nSep==0 ){
7595 raw_printf(stderr, "Error: non-null row separator required for import\n");
7596 return 1;
7597 }
7598 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
7599 /* When importing CSV (only), if the row separator is set to the
7600 ** default output row separator, change it to the default input
7601 ** row separator. This avoids having to maintain different input
7602 ** and output row separators. */
7603 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7604 nSep = strlen30(p->rowSeparator);
7605 }
7606 if( nSep>1 ){
7607 raw_printf(stderr, "Error: multi-character row separators not allowed"
7608 " for import\n");
7609 return 1;
7610 }
7611 sCtx.zFile = zFile;
7612 sCtx.nLine = 1;
7613 if( sCtx.zFile[0]=='|' ){
7614#ifdef SQLITE_OMIT_POPEN
7615 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7616 return 1;
7617#else
7618 sCtx.in = popen(sCtx.zFile+1, "r");
7619 sCtx.zFile = "<pipe>";
7620 xCloser = pclose;
7621#endif
7622 }else{
7623 sCtx.in = fopen(sCtx.zFile, "rb");
7624 xCloser = fclose;
7625 }
7626 if( p->mode==MODE_Ascii ){
7627 xRead = ascii_read_one_field;
7628 }else{
7629 xRead = csv_read_one_field;
7630 }
7631 if( sCtx.in==0 ){
7632 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
7633 return 1;
7634 }
7635 sCtx.cColSep = p->colSeparator[0];
7636 sCtx.cRowSep = p->rowSeparator[0];
7637 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
7638 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00007639 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00007640 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007641 }
7642 nByte = strlen30(zSql);
7643 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7644 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
7645 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
7646 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
7647 char cSep = '(';
7648 while( xRead(&sCtx) ){
7649 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
7650 cSep = ',';
7651 if( sCtx.cTerm!=sCtx.cColSep ) break;
7652 }
7653 if( cSep=='(' ){
7654 sqlite3_free(zCreate);
7655 sqlite3_free(sCtx.z);
7656 xCloser(sCtx.in);
7657 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
7658 return 1;
7659 }
7660 zCreate = sqlite3_mprintf("%z\n)", zCreate);
7661 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
7662 sqlite3_free(zCreate);
7663 if( rc ){
7664 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
7665 sqlite3_errmsg(p->db));
7666 sqlite3_free(sCtx.z);
7667 xCloser(sCtx.in);
7668 return 1;
7669 }
7670 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7671 }
7672 sqlite3_free(zSql);
7673 if( rc ){
7674 if (pStmt) sqlite3_finalize(pStmt);
7675 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
7676 xCloser(sCtx.in);
7677 return 1;
7678 }
7679 nCol = sqlite3_column_count(pStmt);
7680 sqlite3_finalize(pStmt);
7681 pStmt = 0;
7682 if( nCol==0 ) return 0; /* no columns, no error */
7683 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
7684 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00007685 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00007686 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007687 }
7688 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
7689 j = strlen30(zSql);
7690 for(i=1; i<nCol; i++){
7691 zSql[j++] = ',';
7692 zSql[j++] = '?';
7693 }
7694 zSql[j++] = ')';
7695 zSql[j] = 0;
7696 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7697 sqlite3_free(zSql);
7698 if( rc ){
7699 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7700 if (pStmt) sqlite3_finalize(pStmt);
7701 xCloser(sCtx.in);
7702 return 1;
7703 }
7704 needCommit = sqlite3_get_autocommit(p->db);
7705 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
7706 do{
7707 int startLine = sCtx.nLine;
7708 for(i=0; i<nCol; i++){
7709 char *z = xRead(&sCtx);
7710 /*
7711 ** Did we reach end-of-file before finding any columns?
7712 ** If so, stop instead of NULL filling the remaining columns.
7713 */
7714 if( z==0 && i==0 ) break;
7715 /*
7716 ** Did we reach end-of-file OR end-of-line before finding any
7717 ** columns in ASCII mode? If so, stop instead of NULL filling
7718 ** the remaining columns.
7719 */
7720 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
7721 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
7722 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
7723 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7724 "filling the rest with NULL\n",
7725 sCtx.zFile, startLine, nCol, i+1);
7726 i += 2;
7727 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
7728 }
7729 }
7730 if( sCtx.cTerm==sCtx.cColSep ){
7731 do{
7732 xRead(&sCtx);
7733 i++;
7734 }while( sCtx.cTerm==sCtx.cColSep );
7735 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7736 "extras ignored\n",
7737 sCtx.zFile, startLine, nCol, i);
7738 }
7739 if( i>=nCol ){
7740 sqlite3_step(pStmt);
7741 rc = sqlite3_reset(pStmt);
7742 if( rc!=SQLITE_OK ){
7743 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
7744 startLine, sqlite3_errmsg(p->db));
7745 }
7746 }
7747 }while( sCtx.cTerm!=EOF );
7748
7749 xCloser(sCtx.in);
7750 sqlite3_free(sCtx.z);
7751 sqlite3_finalize(pStmt);
7752 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
7753 }else
7754
7755#ifndef SQLITE_UNTESTABLE
7756 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
7757 char *zSql;
7758 char *zCollist = 0;
7759 sqlite3_stmt *pStmt;
7760 int tnum = 0;
drh491c5be2019-10-18 15:58:50 +00007761 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */
7762 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
drh2ce15c32017-07-11 13:34:40 +00007763 int i;
drh48d219a2018-04-23 18:38:48 +00007764 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
7765 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
7766 " .imposter off\n");
drh491c5be2019-10-18 15:58:50 +00007767 /* Also allowed, but not documented:
7768 **
7769 ** .imposter TABLE IMPOSTER
7770 **
7771 ** where TABLE is a WITHOUT ROWID table. In that case, the
7772 ** imposter is another WITHOUT ROWID table with the columns in
7773 ** storage order. */
drh2ce15c32017-07-11 13:34:40 +00007774 rc = 1;
7775 goto meta_command_exit;
7776 }
7777 open_db(p, 0);
drh48d219a2018-04-23 18:38:48 +00007778 if( nArg==2 ){
7779 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
7780 goto meta_command_exit;
7781 }
drh491c5be2019-10-18 15:58:50 +00007782 zSql = sqlite3_mprintf(
7783 "SELECT rootpage, 0 FROM sqlite_master"
7784 " WHERE name='%q' AND type='index'"
7785 "UNION ALL "
7786 "SELECT rootpage, 1 FROM sqlite_master"
7787 " WHERE name='%q' AND type='table'"
7788 " AND sql LIKE '%%without%%rowid%%'",
7789 azArg[1], azArg[1]
7790 );
drh2ce15c32017-07-11 13:34:40 +00007791 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7792 sqlite3_free(zSql);
7793 if( sqlite3_step(pStmt)==SQLITE_ROW ){
7794 tnum = sqlite3_column_int(pStmt, 0);
drh491c5be2019-10-18 15:58:50 +00007795 isWO = sqlite3_column_int(pStmt, 1);
drh2ce15c32017-07-11 13:34:40 +00007796 }
7797 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00007798 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
7799 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7800 sqlite3_free(zSql);
7801 i = 0;
7802 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7803 char zLabel[20];
7804 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
7805 i++;
7806 if( zCol==0 ){
7807 if( sqlite3_column_int(pStmt,1)==-1 ){
7808 zCol = "_ROWID_";
7809 }else{
7810 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
7811 zCol = zLabel;
7812 }
7813 }
drh491c5be2019-10-18 15:58:50 +00007814 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
7815 lenPK = (int)strlen(zCollist);
7816 }
drh2ce15c32017-07-11 13:34:40 +00007817 if( zCollist==0 ){
7818 zCollist = sqlite3_mprintf("\"%w\"", zCol);
7819 }else{
7820 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
7821 }
7822 }
7823 sqlite3_finalize(pStmt);
drh491c5be2019-10-18 15:58:50 +00007824 if( i==0 || tnum==0 ){
7825 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
7826 rc = 1;
7827 sqlite3_free(zCollist);
7828 goto meta_command_exit;
7829 }
7830 if( lenPK==0 ) lenPK = 100000;
drh2ce15c32017-07-11 13:34:40 +00007831 zSql = sqlite3_mprintf(
drh491c5be2019-10-18 15:58:50 +00007832 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
7833 azArg[2], zCollist, lenPK, zCollist);
drh2ce15c32017-07-11 13:34:40 +00007834 sqlite3_free(zCollist);
7835 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
7836 if( rc==SQLITE_OK ){
7837 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
7838 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
7839 if( rc ){
7840 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
7841 }else{
7842 utf8_printf(stdout, "%s;\n", zSql);
7843 raw_printf(stdout,
drh491c5be2019-10-18 15:58:50 +00007844 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
7845 azArg[1], isWO ? "table" : "index"
drh2ce15c32017-07-11 13:34:40 +00007846 );
7847 }
7848 }else{
7849 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
7850 rc = 1;
7851 }
7852 sqlite3_free(zSql);
7853 }else
7854#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
7855
7856#ifdef SQLITE_ENABLE_IOTRACE
7857 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
7858 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
7859 if( iotrace && iotrace!=stdout ) fclose(iotrace);
7860 iotrace = 0;
7861 if( nArg<2 ){
7862 sqlite3IoTrace = 0;
7863 }else if( strcmp(azArg[1], "-")==0 ){
7864 sqlite3IoTrace = iotracePrintf;
7865 iotrace = stdout;
7866 }else{
7867 iotrace = fopen(azArg[1], "w");
7868 if( iotrace==0 ){
7869 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
7870 sqlite3IoTrace = 0;
7871 rc = 1;
7872 }else{
7873 sqlite3IoTrace = iotracePrintf;
7874 }
7875 }
7876 }else
7877#endif
7878
7879 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
7880 static const struct {
7881 const char *zLimitName; /* Name of a limit */
7882 int limitCode; /* Integer code for that limit */
7883 } aLimit[] = {
7884 { "length", SQLITE_LIMIT_LENGTH },
7885 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
7886 { "column", SQLITE_LIMIT_COLUMN },
7887 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
7888 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
7889 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
7890 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
7891 { "attached", SQLITE_LIMIT_ATTACHED },
7892 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
7893 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
7894 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
7895 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
7896 };
7897 int i, n2;
7898 open_db(p, 0);
7899 if( nArg==1 ){
7900 for(i=0; i<ArraySize(aLimit); i++){
7901 printf("%20s %d\n", aLimit[i].zLimitName,
7902 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
7903 }
7904 }else if( nArg>3 ){
7905 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
7906 rc = 1;
7907 goto meta_command_exit;
7908 }else{
7909 int iLimit = -1;
7910 n2 = strlen30(azArg[1]);
7911 for(i=0; i<ArraySize(aLimit); i++){
7912 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
7913 if( iLimit<0 ){
7914 iLimit = i;
7915 }else{
7916 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
7917 rc = 1;
7918 goto meta_command_exit;
7919 }
7920 }
7921 }
7922 if( iLimit<0 ){
7923 utf8_printf(stderr, "unknown limit: \"%s\"\n"
7924 "enter \".limits\" with no arguments for a list.\n",
7925 azArg[1]);
7926 rc = 1;
7927 goto meta_command_exit;
7928 }
7929 if( nArg==3 ){
7930 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
7931 (int)integerValue(azArg[2]));
7932 }
7933 printf("%20s %d\n", aLimit[iLimit].zLimitName,
7934 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
7935 }
7936 }else
7937
7938 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
7939 open_db(p, 0);
7940 lintDotCommand(p, azArg, nArg);
7941 }else
7942
7943#ifndef SQLITE_OMIT_LOAD_EXTENSION
7944 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
7945 const char *zFile, *zProc;
7946 char *zErrMsg = 0;
7947 if( nArg<2 ){
7948 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
7949 rc = 1;
7950 goto meta_command_exit;
7951 }
7952 zFile = azArg[1];
7953 zProc = nArg>=3 ? azArg[2] : 0;
7954 open_db(p, 0);
7955 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
7956 if( rc!=SQLITE_OK ){
7957 utf8_printf(stderr, "Error: %s\n", zErrMsg);
7958 sqlite3_free(zErrMsg);
7959 rc = 1;
7960 }
7961 }else
7962#endif
7963
7964 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
7965 if( nArg!=2 ){
7966 raw_printf(stderr, "Usage: .log FILENAME\n");
7967 rc = 1;
7968 }else{
7969 const char *zFile = azArg[1];
7970 output_file_close(p->pLog);
drha92a01a2018-01-10 22:15:37 +00007971 p->pLog = output_file_open(zFile, 0);
drh2ce15c32017-07-11 13:34:40 +00007972 }
7973 }else
7974
7975 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
7976 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00007977 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00007978 int c2 = zMode[0];
7979 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
7980 p->mode = MODE_Line;
7981 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7982 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
7983 p->mode = MODE_Column;
7984 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7985 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
7986 p->mode = MODE_List;
7987 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
7988 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7989 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
7990 p->mode = MODE_Html;
7991 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
7992 p->mode = MODE_Tcl;
7993 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
7994 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7995 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
7996 p->mode = MODE_Csv;
7997 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
7998 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
7999 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
8000 p->mode = MODE_List;
8001 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
8002 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
8003 p->mode = MODE_Insert;
8004 set_table_name(p, nArg>=3 ? azArg[2] : "table");
8005 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
8006 p->mode = MODE_Quote;
8007 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
8008 p->mode = MODE_Ascii;
8009 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
8010 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
8011 }else if( nArg==1 ){
8012 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
8013 }else{
8014 raw_printf(stderr, "Error: mode should be one of: "
8015 "ascii column csv html insert line list quote tabs tcl\n");
8016 rc = 1;
8017 }
8018 p->cMode = p->mode;
8019 }else
8020
8021 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
8022 if( nArg==2 ){
8023 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
8024 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
8025 }else{
8026 raw_printf(stderr, "Usage: .nullvalue STRING\n");
8027 rc = 1;
8028 }
8029 }else
8030
8031 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
8032 char *zNewFilename; /* Name of the database file to open */
8033 int iName = 1; /* Index in azArg[] of the filename */
8034 int newFlag = 0; /* True to delete file before opening */
8035 /* Close the existing database */
8036 session_close_all(p);
drh9e804032018-05-18 17:11:50 +00008037 close_db(p->db);
drh2ce15c32017-07-11 13:34:40 +00008038 p->db = 0;
8039 p->zDbFilename = 0;
8040 sqlite3_free(p->zFreeOnClose);
8041 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00008042 p->openMode = SHELL_OPEN_UNSPEC;
drh6ca64482019-01-22 16:06:20 +00008043 p->szMax = 0;
drh2ce15c32017-07-11 13:34:40 +00008044 /* Check for command-line arguments */
8045 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
8046 const char *z = azArg[iName];
8047 if( optionMatch(z,"new") ){
8048 newFlag = 1;
drh3baed312018-03-08 18:14:41 +00008049#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00008050 }else if( optionMatch(z, "zip") ){
8051 p->openMode = SHELL_OPEN_ZIPFILE;
8052#endif
8053 }else if( optionMatch(z, "append") ){
8054 p->openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00008055 }else if( optionMatch(z, "readonly") ){
8056 p->openMode = SHELL_OPEN_READONLY;
drha751f392018-10-30 15:31:22 +00008057#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00008058 }else if( optionMatch(z, "deserialize") ){
8059 p->openMode = SHELL_OPEN_DESERIALIZE;
drh33746482018-12-13 15:06:26 +00008060 }else if( optionMatch(z, "hexdb") ){
8061 p->openMode = SHELL_OPEN_HEXDB;
drh6ca64482019-01-22 16:06:20 +00008062 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
8063 p->szMax = integerValue(azArg[++iName]);
drh33746482018-12-13 15:06:26 +00008064#endif /* SQLITE_ENABLE_DESERIALIZE */
drh2ce15c32017-07-11 13:34:40 +00008065 }else if( z[0]=='-' ){
8066 utf8_printf(stderr, "unknown option: %s\n", z);
8067 rc = 1;
8068 goto meta_command_exit;
8069 }
8070 }
8071 /* If a filename is specified, try to open it first */
8072 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
drh33746482018-12-13 15:06:26 +00008073 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
drh2ce15c32017-07-11 13:34:40 +00008074 if( newFlag ) shellDeleteFile(zNewFilename);
8075 p->zDbFilename = zNewFilename;
drhbe4ccb22018-05-17 20:04:24 +00008076 open_db(p, OPEN_DB_KEEPALIVE);
drh2ce15c32017-07-11 13:34:40 +00008077 if( p->db==0 ){
8078 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
8079 sqlite3_free(zNewFilename);
8080 }else{
8081 p->zFreeOnClose = zNewFilename;
8082 }
8083 }
8084 if( p->db==0 ){
8085 /* As a fall-back open a TEMP database */
8086 p->zDbFilename = 0;
8087 open_db(p, 0);
8088 }
8089 }else
8090
drh13c20932018-01-10 21:41:55 +00008091 if( (c=='o'
8092 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
8093 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
drh2ce15c32017-07-11 13:34:40 +00008094 ){
8095 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
drha92a01a2018-01-10 22:15:37 +00008096 int bTxtMode = 0;
drh13c20932018-01-10 21:41:55 +00008097 if( azArg[0][0]=='e' ){
8098 /* Transform the ".excel" command into ".once -x" */
8099 nArg = 2;
8100 azArg[0] = "once";
8101 zFile = azArg[1] = "-x";
8102 n = 4;
8103 }
drh2ce15c32017-07-11 13:34:40 +00008104 if( nArg>2 ){
drh13c20932018-01-10 21:41:55 +00008105 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00008106 rc = 1;
8107 goto meta_command_exit;
8108 }
8109 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
8110 if( nArg<2 ){
drh13c20932018-01-10 21:41:55 +00008111 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
drh2ce15c32017-07-11 13:34:40 +00008112 rc = 1;
8113 goto meta_command_exit;
8114 }
8115 p->outCount = 2;
8116 }else{
8117 p->outCount = 0;
8118 }
8119 output_reset(p);
drh13c20932018-01-10 21:41:55 +00008120 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
drh04a28c32018-01-31 01:38:44 +00008121#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00008122 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
drh3c484e82018-01-10 22:27:21 +00008123 p->doXdgOpen = 1;
8124 outputModePush(p);
drh13c20932018-01-10 21:41:55 +00008125 if( zFile[1]=='x' ){
8126 newTempFile(p, "csv");
8127 p->mode = MODE_Csv;
8128 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
8129 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
8130 }else{
8131 newTempFile(p, "txt");
drha92a01a2018-01-10 22:15:37 +00008132 bTxtMode = 1;
drh13c20932018-01-10 21:41:55 +00008133 }
8134 zFile = p->zTempFile;
8135 }
drh04a28c32018-01-31 01:38:44 +00008136#endif /* SQLITE_NOHAVE_SYSTEM */
drh2ce15c32017-07-11 13:34:40 +00008137 if( zFile[0]=='|' ){
8138#ifdef SQLITE_OMIT_POPEN
8139 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
8140 rc = 1;
8141 p->out = stdout;
8142#else
8143 p->out = popen(zFile + 1, "w");
8144 if( p->out==0 ){
8145 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
8146 p->out = stdout;
8147 rc = 1;
8148 }else{
8149 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8150 }
8151#endif
8152 }else{
drha92a01a2018-01-10 22:15:37 +00008153 p->out = output_file_open(zFile, bTxtMode);
drh2ce15c32017-07-11 13:34:40 +00008154 if( p->out==0 ){
8155 if( strcmp(zFile,"off")!=0 ){
8156 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
8157 }
8158 p->out = stdout;
8159 rc = 1;
8160 } else {
8161 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
8162 }
8163 }
8164 }else
8165
drh9cb02642019-02-28 20:10:52 +00008166 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
8167 open_db(p,0);
8168 if( nArg<=1 ) goto parameter_syntax_error;
8169
8170 /* .parameter clear
8171 ** Clear all bind parameters by dropping the TEMP table that holds them.
8172 */
8173 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
drh65c29fd2019-03-25 21:56:26 +00008174 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
drh9cb02642019-02-28 20:10:52 +00008175 0, 0, 0);
8176 }else
8177
8178 /* .parameter list
8179 ** List all bind parameters.
8180 */
8181 if( nArg==2 && strcmp(azArg[1],"list")==0 ){
8182 sqlite3_stmt *pStmt = 0;
8183 int rx;
8184 int len = 0;
8185 rx = sqlite3_prepare_v2(p->db,
8186 "SELECT max(length(key)) "
drh65c29fd2019-03-25 21:56:26 +00008187 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
drh9cb02642019-02-28 20:10:52 +00008188 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
8189 len = sqlite3_column_int(pStmt, 0);
8190 if( len>40 ) len = 40;
8191 }
8192 sqlite3_finalize(pStmt);
8193 pStmt = 0;
8194 if( len ){
8195 rx = sqlite3_prepare_v2(p->db,
8196 "SELECT key, quote(value) "
drh65c29fd2019-03-25 21:56:26 +00008197 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
drh9cb02642019-02-28 20:10:52 +00008198 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8199 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
8200 sqlite3_column_text(pStmt,1));
8201 }
8202 sqlite3_finalize(pStmt);
8203 }
8204 }else
8205
8206 /* .parameter init
8207 ** Make sure the TEMP table used to hold bind parameters exists.
8208 ** Create it if necessary.
8209 */
8210 if( nArg==2 && strcmp(azArg[1],"init")==0 ){
8211 bind_table_init(p);
8212 }else
8213
8214 /* .parameter set NAME VALUE
8215 ** Set or reset a bind parameter. NAME should be the full parameter
8216 ** name exactly as it appears in the query. (ex: $abc, @def). The
8217 ** VALUE can be in either SQL literal notation, or if not it will be
8218 ** understood to be a text string.
8219 */
8220 if( nArg==4 && strcmp(azArg[1],"set")==0 ){
8221 int rx;
8222 char *zSql;
8223 sqlite3_stmt *pStmt;
8224 const char *zKey = azArg[2];
8225 const char *zValue = azArg[3];
8226 bind_table_init(p);
8227 zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00008228 "REPLACE INTO temp.sqlite_parameters(key,value)"
drh9cb02642019-02-28 20:10:52 +00008229 "VALUES(%Q,%s);", zKey, zValue);
8230 if( zSql==0 ) shell_out_of_memory();
8231 pStmt = 0;
8232 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8233 sqlite3_free(zSql);
8234 if( rx!=SQLITE_OK ){
8235 sqlite3_finalize(pStmt);
8236 pStmt = 0;
8237 zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00008238 "REPLACE INTO temp.sqlite_parameters(key,value)"
drh9cb02642019-02-28 20:10:52 +00008239 "VALUES(%Q,%Q);", zKey, zValue);
8240 if( zSql==0 ) shell_out_of_memory();
8241 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8242 sqlite3_free(zSql);
8243 if( rx!=SQLITE_OK ){
8244 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
8245 sqlite3_finalize(pStmt);
8246 pStmt = 0;
8247 rc = 1;
8248 }
8249 }
8250 sqlite3_step(pStmt);
8251 sqlite3_finalize(pStmt);
8252 }else
8253
8254 /* .parameter unset NAME
8255 ** Remove the NAME binding from the parameter binding table, if it
8256 ** exists.
8257 */
8258 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
8259 char *zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00008260 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
drh9cb02642019-02-28 20:10:52 +00008261 if( zSql==0 ) shell_out_of_memory();
8262 sqlite3_exec(p->db, zSql, 0, 0, 0);
8263 sqlite3_free(zSql);
8264 }else
8265 /* If no command name matches, show a syntax error */
8266 parameter_syntax_error:
8267 showHelp(p->out, "parameter");
8268 }else
8269
drh2ce15c32017-07-11 13:34:40 +00008270 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
8271 int i;
8272 for(i=1; i<nArg; i++){
8273 if( i>1 ) raw_printf(p->out, " ");
8274 utf8_printf(p->out, "%s", azArg[i]);
8275 }
8276 raw_printf(p->out, "\n");
8277 }else
8278
drh569b1d92019-02-05 20:51:41 +00008279#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00008280 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
8281 int i;
drhfc4eeef2019-02-05 19:48:46 +00008282 int nn = 0;
drh3f83f592019-02-04 14:53:18 +00008283 p->flgProgress = 0;
8284 p->mxProgress = 0;
8285 p->nProgress = 0;
8286 for(i=1; i<nArg; i++){
8287 const char *z = azArg[i];
8288 if( z[0]=='-' ){
8289 z++;
8290 if( z[0]=='-' ) z++;
8291 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00008292 p->flgProgress |= SHELL_PROGRESS_QUIET;
drh3f83f592019-02-04 14:53:18 +00008293 continue;
8294 }
8295 if( strcmp(z,"reset")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00008296 p->flgProgress |= SHELL_PROGRESS_RESET;
drh3f83f592019-02-04 14:53:18 +00008297 continue;
8298 }
8299 if( strcmp(z,"once")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00008300 p->flgProgress |= SHELL_PROGRESS_ONCE;
drh3f83f592019-02-04 14:53:18 +00008301 continue;
8302 }
8303 if( strcmp(z,"limit")==0 ){
8304 if( i+1>=nArg ){
8305 utf8_printf(stderr, "Error: missing argument on --limit\n");
8306 rc = 1;
8307 goto meta_command_exit;
8308 }else{
8309 p->mxProgress = (int)integerValue(azArg[++i]);
8310 }
8311 continue;
8312 }
8313 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
8314 rc = 1;
8315 goto meta_command_exit;
8316 }else{
drhfc4eeef2019-02-05 19:48:46 +00008317 nn = (int)integerValue(z);
drh3f83f592019-02-04 14:53:18 +00008318 }
8319 }
8320 open_db(p, 0);
drhfc4eeef2019-02-05 19:48:46 +00008321 sqlite3_progress_handler(p->db, nn, progress_handler, p);
drh3f83f592019-02-04 14:53:18 +00008322 }else
drh569b1d92019-02-05 20:51:41 +00008323#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00008324
drh2ce15c32017-07-11 13:34:40 +00008325 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
8326 if( nArg >= 2) {
8327 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
8328 }
8329 if( nArg >= 3) {
8330 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
8331 }
8332 }else
8333
8334 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
8335 rc = 2;
8336 }else
8337
8338 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
drh60379d42018-12-13 18:30:01 +00008339 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00008340 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00008341 if( nArg!=2 ){
8342 raw_printf(stderr, "Usage: .read FILE\n");
8343 rc = 1;
8344 goto meta_command_exit;
8345 }
drh60379d42018-12-13 18:30:01 +00008346 p->in = fopen(azArg[1], "rb");
8347 if( p->in==0 ){
drh2ce15c32017-07-11 13:34:40 +00008348 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
8349 rc = 1;
8350 }else{
drh60379d42018-12-13 18:30:01 +00008351 rc = process_input(p);
8352 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00008353 }
drh60379d42018-12-13 18:30:01 +00008354 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00008355 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00008356 }else
8357
8358 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
8359 const char *zSrcFile;
8360 const char *zDb;
8361 sqlite3 *pSrc;
8362 sqlite3_backup *pBackup;
8363 int nTimeout = 0;
8364
8365 if( nArg==2 ){
8366 zSrcFile = azArg[1];
8367 zDb = "main";
8368 }else if( nArg==3 ){
8369 zSrcFile = azArg[2];
8370 zDb = azArg[1];
8371 }else{
8372 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
8373 rc = 1;
8374 goto meta_command_exit;
8375 }
8376 rc = sqlite3_open(zSrcFile, &pSrc);
8377 if( rc!=SQLITE_OK ){
8378 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9e804032018-05-18 17:11:50 +00008379 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00008380 return 1;
8381 }
8382 open_db(p, 0);
8383 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
8384 if( pBackup==0 ){
8385 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9e804032018-05-18 17:11:50 +00008386 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00008387 return 1;
8388 }
8389 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
8390 || rc==SQLITE_BUSY ){
8391 if( rc==SQLITE_BUSY ){
8392 if( nTimeout++ >= 3 ) break;
8393 sqlite3_sleep(100);
8394 }
8395 }
8396 sqlite3_backup_finish(pBackup);
8397 if( rc==SQLITE_DONE ){
8398 rc = 0;
8399 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
8400 raw_printf(stderr, "Error: source database is busy\n");
8401 rc = 1;
8402 }else{
8403 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8404 rc = 1;
8405 }
drh9e804032018-05-18 17:11:50 +00008406 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00008407 }else
8408
drh2ce15c32017-07-11 13:34:40 +00008409 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
8410 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00008411 p->scanstatsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00008412#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
8413 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
8414#endif
8415 }else{
8416 raw_printf(stderr, "Usage: .scanstats on|off\n");
8417 rc = 1;
8418 }
8419 }else
8420
8421 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
8422 ShellText sSelect;
8423 ShellState data;
8424 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00008425 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00008426 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00008427 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00008428 int bDebug = 0;
8429 int ii;
drh2ce15c32017-07-11 13:34:40 +00008430
8431 open_db(p, 0);
8432 memcpy(&data, p, sizeof(data));
8433 data.showHeader = 0;
8434 data.cMode = data.mode = MODE_Semi;
8435 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00008436 for(ii=1; ii<nArg; ii++){
8437 if( optionMatch(azArg[ii],"indent") ){
8438 data.cMode = data.mode = MODE_Pretty;
8439 }else if( optionMatch(azArg[ii],"debug") ){
8440 bDebug = 1;
8441 }else if( zName==0 ){
8442 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00008443 }else{
drhceba7922018-01-01 21:28:25 +00008444 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
8445 rc = 1;
8446 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00008447 }
drh2ce15c32017-07-11 13:34:40 +00008448 }
drhceba7922018-01-01 21:28:25 +00008449 if( zName!=0 ){
mistachkin9d107262018-03-23 14:24:34 +00008450 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
8451 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
drh2ce15c32017-07-11 13:34:40 +00008452 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00008453 new_argv[0] = sqlite3_mprintf(
8454 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00008455 " type text,\n"
8456 " name text,\n"
8457 " tbl_name text,\n"
8458 " rootpage integer,\n"
8459 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00008460 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00008461 new_argv[1] = 0;
8462 new_colv[0] = "sql";
8463 new_colv[1] = 0;
8464 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00008465 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00008466 }
drh2ce15c32017-07-11 13:34:40 +00008467 }
8468 if( zDiv ){
8469 sqlite3_stmt *pStmt = 0;
8470 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
8471 -1, &pStmt, 0);
8472 if( rc ){
8473 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8474 sqlite3_finalize(pStmt);
8475 rc = 1;
8476 goto meta_command_exit;
8477 }
8478 appendText(&sSelect, "SELECT sql FROM", 0);
8479 iSchema = 0;
8480 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8481 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
8482 char zScNum[30];
8483 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
8484 appendText(&sSelect, zDiv, 0);
8485 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00008486 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
8487 if( sqlite3_stricmp(zDb, "main")!=0 ){
drhea38f4f2019-07-13 17:21:47 +00008488 appendText(&sSelect, zDb, '\'');
drh2ce15c32017-07-11 13:34:40 +00008489 }else{
drhceba7922018-01-01 21:28:25 +00008490 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00008491 }
drhceba7922018-01-01 21:28:25 +00008492 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
8493 appendText(&sSelect, zScNum, 0);
8494 appendText(&sSelect, " AS snum, ", 0);
8495 appendText(&sSelect, zDb, '\'');
8496 appendText(&sSelect, " AS sname FROM ", 0);
drhea38f4f2019-07-13 17:21:47 +00008497 appendText(&sSelect, zDb, quoteChar(zDb));
drhceba7922018-01-01 21:28:25 +00008498 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00008499 }
8500 sqlite3_finalize(pStmt);
drhcc3f3d12019-08-17 15:27:58 +00008501#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00008502 if( zName ){
8503 appendText(&sSelect,
8504 " UNION ALL SELECT shell_module_schema(name),"
drhe2754c12019-08-26 12:50:01 +00008505 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list",
8506 0);
drh667a2a22018-01-02 00:04:37 +00008507 }
drhcde7b772018-01-02 12:50:40 +00008508#endif
drh2ce15c32017-07-11 13:34:40 +00008509 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00008510 if( zName ){
8511 char *zQarg = sqlite3_mprintf("%Q", zName);
mistachkin9d107262018-03-23 14:24:34 +00008512 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
8513 strchr(zName, '[') != 0;
drhceba7922018-01-01 21:28:25 +00008514 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00008515 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
8516 }else{
8517 appendText(&sSelect, "lower(tbl_name)", 0);
8518 }
mistachkin9d107262018-03-23 14:24:34 +00008519 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00008520 appendText(&sSelect, zQarg, 0);
mistachkin9d107262018-03-23 14:24:34 +00008521 if( !bGlob ){
8522 appendText(&sSelect, " ESCAPE '\\' ", 0);
8523 }
drh2ce15c32017-07-11 13:34:40 +00008524 appendText(&sSelect, " AND ", 0);
8525 sqlite3_free(zQarg);
8526 }
8527 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
8528 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00008529 if( bDebug ){
8530 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
8531 }else{
8532 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
8533 }
drh2ce15c32017-07-11 13:34:40 +00008534 freeText(&sSelect);
8535 }
8536 if( zErrMsg ){
8537 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8538 sqlite3_free(zErrMsg);
8539 rc = 1;
8540 }else if( rc != SQLITE_OK ){
8541 raw_printf(stderr,"Error: querying schema information\n");
8542 rc = 1;
8543 }else{
8544 rc = 0;
8545 }
8546 }else
8547
8548#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
8549 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
8550 sqlite3SelectTrace = (int)integerValue(azArg[1]);
8551 }else
8552#endif
8553
8554#if defined(SQLITE_ENABLE_SESSION)
8555 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
8556 OpenSession *pSession = &p->aSession[0];
8557 char **azCmd = &azArg[1];
8558 int iSes = 0;
8559 int nCmd = nArg - 1;
8560 int i;
8561 if( nArg<=1 ) goto session_syntax_error;
8562 open_db(p, 0);
8563 if( nArg>=3 ){
8564 for(iSes=0; iSes<p->nSession; iSes++){
8565 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
8566 }
8567 if( iSes<p->nSession ){
8568 pSession = &p->aSession[iSes];
8569 azCmd++;
8570 nCmd--;
8571 }else{
8572 pSession = &p->aSession[0];
8573 iSes = 0;
8574 }
8575 }
8576
8577 /* .session attach TABLE
8578 ** Invoke the sqlite3session_attach() interface to attach a particular
8579 ** table so that it is never filtered.
8580 */
8581 if( strcmp(azCmd[0],"attach")==0 ){
8582 if( nCmd!=2 ) goto session_syntax_error;
8583 if( pSession->p==0 ){
8584 session_not_open:
8585 raw_printf(stderr, "ERROR: No sessions are open\n");
8586 }else{
8587 rc = sqlite3session_attach(pSession->p, azCmd[1]);
8588 if( rc ){
8589 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
8590 rc = 0;
8591 }
8592 }
8593 }else
8594
8595 /* .session changeset FILE
8596 ** .session patchset FILE
8597 ** Write a changeset or patchset into a file. The file is overwritten.
8598 */
8599 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
8600 FILE *out = 0;
8601 if( nCmd!=2 ) goto session_syntax_error;
8602 if( pSession->p==0 ) goto session_not_open;
8603 out = fopen(azCmd[1], "wb");
8604 if( out==0 ){
drhe2754c12019-08-26 12:50:01 +00008605 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n",
8606 azCmd[1]);
drh2ce15c32017-07-11 13:34:40 +00008607 }else{
8608 int szChng;
8609 void *pChng;
8610 if( azCmd[0][0]=='c' ){
8611 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
8612 }else{
8613 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
8614 }
8615 if( rc ){
8616 printf("Error: error code %d\n", rc);
8617 rc = 0;
8618 }
8619 if( pChng
8620 && fwrite(pChng, szChng, 1, out)!=1 ){
8621 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
8622 szChng);
8623 }
8624 sqlite3_free(pChng);
8625 fclose(out);
8626 }
8627 }else
8628
8629 /* .session close
8630 ** Close the identified session
8631 */
8632 if( strcmp(azCmd[0], "close")==0 ){
8633 if( nCmd!=1 ) goto session_syntax_error;
8634 if( p->nSession ){
8635 session_close(pSession);
8636 p->aSession[iSes] = p->aSession[--p->nSession];
8637 }
8638 }else
8639
8640 /* .session enable ?BOOLEAN?
8641 ** Query or set the enable flag
8642 */
8643 if( strcmp(azCmd[0], "enable")==0 ){
8644 int ii;
8645 if( nCmd>2 ) goto session_syntax_error;
8646 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8647 if( p->nSession ){
8648 ii = sqlite3session_enable(pSession->p, ii);
8649 utf8_printf(p->out, "session %s enable flag = %d\n",
8650 pSession->zName, ii);
8651 }
8652 }else
8653
8654 /* .session filter GLOB ....
8655 ** Set a list of GLOB patterns of table names to be excluded.
8656 */
8657 if( strcmp(azCmd[0], "filter")==0 ){
8658 int ii, nByte;
8659 if( nCmd<2 ) goto session_syntax_error;
8660 if( p->nSession ){
8661 for(ii=0; ii<pSession->nFilter; ii++){
8662 sqlite3_free(pSession->azFilter[ii]);
8663 }
8664 sqlite3_free(pSession->azFilter);
8665 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
8666 pSession->azFilter = sqlite3_malloc( nByte );
8667 if( pSession->azFilter==0 ){
8668 raw_printf(stderr, "Error: out or memory\n");
8669 exit(1);
8670 }
8671 for(ii=1; ii<nCmd; ii++){
8672 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
8673 }
8674 pSession->nFilter = ii-1;
8675 }
8676 }else
8677
8678 /* .session indirect ?BOOLEAN?
8679 ** Query or set the indirect flag
8680 */
8681 if( strcmp(azCmd[0], "indirect")==0 ){
8682 int ii;
8683 if( nCmd>2 ) goto session_syntax_error;
8684 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8685 if( p->nSession ){
8686 ii = sqlite3session_indirect(pSession->p, ii);
8687 utf8_printf(p->out, "session %s indirect flag = %d\n",
8688 pSession->zName, ii);
8689 }
8690 }else
8691
8692 /* .session isempty
8693 ** Determine if the session is empty
8694 */
8695 if( strcmp(azCmd[0], "isempty")==0 ){
8696 int ii;
8697 if( nCmd!=1 ) goto session_syntax_error;
8698 if( p->nSession ){
8699 ii = sqlite3session_isempty(pSession->p);
8700 utf8_printf(p->out, "session %s isempty flag = %d\n",
8701 pSession->zName, ii);
8702 }
8703 }else
8704
8705 /* .session list
8706 ** List all currently open sessions
8707 */
8708 if( strcmp(azCmd[0],"list")==0 ){
8709 for(i=0; i<p->nSession; i++){
8710 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
8711 }
8712 }else
8713
8714 /* .session open DB NAME
8715 ** Open a new session called NAME on the attached database DB.
8716 ** DB is normally "main".
8717 */
8718 if( strcmp(azCmd[0],"open")==0 ){
8719 char *zName;
8720 if( nCmd!=3 ) goto session_syntax_error;
8721 zName = azCmd[2];
8722 if( zName[0]==0 ) goto session_syntax_error;
8723 for(i=0; i<p->nSession; i++){
8724 if( strcmp(p->aSession[i].zName,zName)==0 ){
8725 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
8726 goto meta_command_exit;
8727 }
8728 }
8729 if( p->nSession>=ArraySize(p->aSession) ){
8730 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
8731 goto meta_command_exit;
8732 }
8733 pSession = &p->aSession[p->nSession];
8734 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
8735 if( rc ){
8736 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
8737 rc = 0;
8738 goto meta_command_exit;
8739 }
8740 pSession->nFilter = 0;
8741 sqlite3session_table_filter(pSession->p, session_filter, pSession);
8742 p->nSession++;
8743 pSession->zName = sqlite3_mprintf("%s", zName);
8744 }else
8745 /* If no command name matches, show a syntax error */
8746 session_syntax_error:
drheb7f2a02018-09-26 18:02:32 +00008747 showHelp(p->out, "session");
drh2ce15c32017-07-11 13:34:40 +00008748 }else
8749#endif
8750
8751#ifdef SQLITE_DEBUG
8752 /* Undocumented commands for internal testing. Subject to change
8753 ** without notice. */
8754 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
8755 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
8756 int i, v;
8757 for(i=1; i<nArg; i++){
8758 v = booleanValue(azArg[i]);
8759 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
8760 }
8761 }
8762 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
8763 int i; sqlite3_int64 v;
8764 for(i=1; i<nArg; i++){
8765 char zBuf[200];
8766 v = integerValue(azArg[i]);
8767 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
8768 utf8_printf(p->out, "%s", zBuf);
8769 }
8770 }
8771 }else
8772#endif
8773
8774 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
8775 int bIsInit = 0; /* True to initialize the SELFTEST table */
8776 int bVerbose = 0; /* Verbose output */
8777 int bSelftestExists; /* True if SELFTEST already exists */
8778 int i, k; /* Loop counters */
8779 int nTest = 0; /* Number of tests runs */
8780 int nErr = 0; /* Number of errors seen */
8781 ShellText str; /* Answer for a query */
8782 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
8783
8784 open_db(p,0);
8785 for(i=1; i<nArg; i++){
8786 const char *z = azArg[i];
8787 if( z[0]=='-' && z[1]=='-' ) z++;
8788 if( strcmp(z,"-init")==0 ){
8789 bIsInit = 1;
8790 }else
8791 if( strcmp(z,"-v")==0 ){
8792 bVerbose++;
8793 }else
8794 {
8795 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8796 azArg[i], azArg[0]);
8797 raw_printf(stderr, "Should be one of: --init -v\n");
8798 rc = 1;
8799 goto meta_command_exit;
8800 }
8801 }
8802 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
8803 != SQLITE_OK ){
8804 bSelftestExists = 0;
8805 }else{
8806 bSelftestExists = 1;
8807 }
8808 if( bIsInit ){
8809 createSelftestTable(p);
8810 bSelftestExists = 1;
8811 }
8812 initText(&str);
8813 appendText(&str, "x", 0);
8814 for(k=bSelftestExists; k>=0; k--){
8815 if( k==1 ){
8816 rc = sqlite3_prepare_v2(p->db,
8817 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
8818 -1, &pStmt, 0);
8819 }else{
8820 rc = sqlite3_prepare_v2(p->db,
8821 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
8822 " (1,'run','PRAGMA integrity_check','ok')",
8823 -1, &pStmt, 0);
8824 }
8825 if( rc ){
8826 raw_printf(stderr, "Error querying the selftest table\n");
8827 rc = 1;
8828 sqlite3_finalize(pStmt);
8829 goto meta_command_exit;
8830 }
8831 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
8832 int tno = sqlite3_column_int(pStmt, 0);
8833 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
8834 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
8835 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
8836
8837 k = 0;
8838 if( bVerbose>0 ){
8839 char *zQuote = sqlite3_mprintf("%q", zSql);
8840 printf("%d: %s %s\n", tno, zOp, zSql);
8841 sqlite3_free(zQuote);
8842 }
8843 if( strcmp(zOp,"memo")==0 ){
8844 utf8_printf(p->out, "%s\n", zSql);
8845 }else
8846 if( strcmp(zOp,"run")==0 ){
8847 char *zErrMsg = 0;
8848 str.n = 0;
8849 str.z[0] = 0;
8850 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
8851 nTest++;
8852 if( bVerbose ){
8853 utf8_printf(p->out, "Result: %s\n", str.z);
8854 }
8855 if( rc || zErrMsg ){
8856 nErr++;
8857 rc = 1;
8858 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
8859 sqlite3_free(zErrMsg);
8860 }else if( strcmp(zAns,str.z)!=0 ){
8861 nErr++;
8862 rc = 1;
8863 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
8864 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
8865 }
8866 }else
8867 {
8868 utf8_printf(stderr,
8869 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
8870 rc = 1;
8871 break;
8872 }
8873 } /* End loop over rows of content from SELFTEST */
8874 sqlite3_finalize(pStmt);
8875 } /* End loop over k */
8876 freeText(&str);
8877 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
8878 }else
8879
8880 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
8881 if( nArg<2 || nArg>3 ){
8882 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
8883 rc = 1;
8884 }
8885 if( nArg>=2 ){
8886 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
8887 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
8888 }
8889 if( nArg>=3 ){
8890 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
8891 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
8892 }
8893 }else
8894
8895 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
8896 const char *zLike = 0; /* Which table to checksum. 0 means everything */
8897 int i; /* Loop counter */
8898 int bSchema = 0; /* Also hash the schema */
8899 int bSeparate = 0; /* Hash each table separately */
8900 int iSize = 224; /* Hash algorithm to use */
8901 int bDebug = 0; /* Only show the query that would have run */
8902 sqlite3_stmt *pStmt; /* For querying tables names */
8903 char *zSql; /* SQL to be run */
8904 char *zSep; /* Separator */
8905 ShellText sSql; /* Complete SQL for the query to run the hash */
8906 ShellText sQuery; /* Set of queries used to read all content */
8907 open_db(p, 0);
8908 for(i=1; i<nArg; i++){
8909 const char *z = azArg[i];
8910 if( z[0]=='-' ){
8911 z++;
8912 if( z[0]=='-' ) z++;
8913 if( strcmp(z,"schema")==0 ){
8914 bSchema = 1;
8915 }else
8916 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
8917 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
8918 ){
8919 iSize = atoi(&z[5]);
8920 }else
8921 if( strcmp(z,"debug")==0 ){
8922 bDebug = 1;
8923 }else
8924 {
8925 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8926 azArg[i], azArg[0]);
drhe2754c12019-08-26 12:50:01 +00008927 showHelp(p->out, azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00008928 rc = 1;
8929 goto meta_command_exit;
8930 }
8931 }else if( zLike ){
8932 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
8933 rc = 1;
8934 goto meta_command_exit;
8935 }else{
8936 zLike = z;
8937 bSeparate = 1;
drhcedfecf2018-03-23 12:59:10 +00008938 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
drh2ce15c32017-07-11 13:34:40 +00008939 }
8940 }
8941 if( bSchema ){
8942 zSql = "SELECT lower(name) FROM sqlite_master"
8943 " WHERE type='table' AND coalesce(rootpage,0)>1"
8944 " UNION ALL SELECT 'sqlite_master'"
8945 " ORDER BY 1 collate nocase";
8946 }else{
8947 zSql = "SELECT lower(name) FROM sqlite_master"
8948 " WHERE type='table' AND coalesce(rootpage,0)>1"
8949 " AND name NOT LIKE 'sqlite_%'"
8950 " ORDER BY 1 collate nocase";
8951 }
8952 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8953 initText(&sQuery);
8954 initText(&sSql);
8955 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
8956 zSep = "VALUES(";
8957 while( SQLITE_ROW==sqlite3_step(pStmt) ){
8958 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
8959 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
8960 if( strncmp(zTab, "sqlite_",7)!=0 ){
8961 appendText(&sQuery,"SELECT * FROM ", 0);
8962 appendText(&sQuery,zTab,'"');
8963 appendText(&sQuery," NOT INDEXED;", 0);
8964 }else if( strcmp(zTab, "sqlite_master")==0 ){
8965 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
8966 " ORDER BY name;", 0);
8967 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
8968 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
8969 " ORDER BY name;", 0);
8970 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
8971 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
8972 " ORDER BY tbl,idx;", 0);
drh175b8f02019-08-08 15:24:17 +00008973 }else if( strcmp(zTab, "sqlite_stat4")==0 ){
drh2ce15c32017-07-11 13:34:40 +00008974 appendText(&sQuery, "SELECT * FROM ", 0);
8975 appendText(&sQuery, zTab, 0);
8976 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
8977 }
8978 appendText(&sSql, zSep, 0);
8979 appendText(&sSql, sQuery.z, '\'');
8980 sQuery.n = 0;
8981 appendText(&sSql, ",", 0);
8982 appendText(&sSql, zTab, '\'');
8983 zSep = "),(";
8984 }
8985 sqlite3_finalize(pStmt);
8986 if( bSeparate ){
8987 zSql = sqlite3_mprintf(
8988 "%s))"
8989 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
8990 " FROM [sha3sum$query]",
8991 sSql.z, iSize);
8992 }else{
8993 zSql = sqlite3_mprintf(
8994 "%s))"
8995 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
8996 " FROM [sha3sum$query]",
8997 sSql.z, iSize);
8998 }
8999 freeText(&sQuery);
9000 freeText(&sSql);
9001 if( bDebug ){
9002 utf8_printf(p->out, "%s\n", zSql);
9003 }else{
drha10b9992018-03-09 15:24:33 +00009004 shell_exec(p, zSql, 0);
drh2ce15c32017-07-11 13:34:40 +00009005 }
9006 sqlite3_free(zSql);
9007 }else
9008
drh04a28c32018-01-31 01:38:44 +00009009#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00009010 if( c=='s'
9011 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
9012 ){
9013 char *zCmd;
9014 int i, x;
9015 if( nArg<2 ){
9016 raw_printf(stderr, "Usage: .system COMMAND\n");
9017 rc = 1;
9018 goto meta_command_exit;
9019 }
9020 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
9021 for(i=2; i<nArg; i++){
9022 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
9023 zCmd, azArg[i]);
9024 }
9025 x = system(zCmd);
9026 sqlite3_free(zCmd);
9027 if( x ) raw_printf(stderr, "System command returns %d\n", x);
9028 }else
drh04a28c32018-01-31 01:38:44 +00009029#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00009030
9031 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00009032 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00009033 int i;
9034 if( nArg!=1 ){
9035 raw_printf(stderr, "Usage: .show\n");
9036 rc = 1;
9037 goto meta_command_exit;
9038 }
9039 utf8_printf(p->out, "%12.12s: %s\n","echo",
9040 azBool[ShellHasFlag(p, SHFLG_Echo)]);
9041 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
9042 utf8_printf(p->out, "%12.12s: %s\n","explain",
9043 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
9044 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
9045 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
9046 utf8_printf(p->out, "%12.12s: ", "nullvalue");
9047 output_c_string(p->out, p->nullValue);
9048 raw_printf(p->out, "\n");
9049 utf8_printf(p->out,"%12.12s: %s\n","output",
9050 strlen30(p->outfile) ? p->outfile : "stdout");
9051 utf8_printf(p->out,"%12.12s: ", "colseparator");
9052 output_c_string(p->out, p->colSeparator);
9053 raw_printf(p->out, "\n");
9054 utf8_printf(p->out,"%12.12s: ", "rowseparator");
9055 output_c_string(p->out, p->rowSeparator);
9056 raw_printf(p->out, "\n");
9057 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
9058 utf8_printf(p->out, "%12.12s: ", "width");
9059 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
9060 raw_printf(p->out, "%d ", p->colWidth[i]);
9061 }
9062 raw_printf(p->out, "\n");
9063 utf8_printf(p->out, "%12.12s: %s\n", "filename",
9064 p->zDbFilename ? p->zDbFilename : "");
9065 }else
9066
9067 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
9068 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00009069 p->statsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00009070 }else if( nArg==1 ){
9071 display_stats(p->db, p, 0);
9072 }else{
9073 raw_printf(stderr, "Usage: .stats ?on|off?\n");
9074 rc = 1;
9075 }
9076 }else
9077
9078 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
9079 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
9080 || strncmp(azArg[0], "indexes", n)==0) )
9081 ){
9082 sqlite3_stmt *pStmt;
9083 char **azResult;
9084 int nRow, nAlloc;
9085 int ii;
9086 ShellText s;
9087 initText(&s);
9088 open_db(p, 0);
9089 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
drh9e804032018-05-18 17:11:50 +00009090 if( rc ){
9091 sqlite3_finalize(pStmt);
9092 return shellDatabaseError(p->db);
9093 }
drh2ce15c32017-07-11 13:34:40 +00009094
9095 if( nArg>2 && c=='i' ){
9096 /* It is an historical accident that the .indexes command shows an error
9097 ** when called with the wrong number of arguments whereas the .tables
9098 ** command does not. */
9099 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
9100 rc = 1;
drh9e804032018-05-18 17:11:50 +00009101 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00009102 goto meta_command_exit;
9103 }
9104 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
9105 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
9106 if( zDbName==0 ) continue;
9107 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
9108 if( sqlite3_stricmp(zDbName, "main")==0 ){
9109 appendText(&s, "SELECT name FROM ", 0);
9110 }else{
9111 appendText(&s, "SELECT ", 0);
9112 appendText(&s, zDbName, '\'');
9113 appendText(&s, "||'.'||name FROM ", 0);
9114 }
9115 appendText(&s, zDbName, '"');
9116 appendText(&s, ".sqlite_master ", 0);
9117 if( c=='t' ){
9118 appendText(&s," WHERE type IN ('table','view')"
9119 " AND name NOT LIKE 'sqlite_%'"
9120 " AND name LIKE ?1", 0);
9121 }else{
9122 appendText(&s," WHERE type='index'"
9123 " AND tbl_name LIKE ?1", 0);
9124 }
9125 }
9126 rc = sqlite3_finalize(pStmt);
9127 appendText(&s, " ORDER BY 1", 0);
9128 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
9129 freeText(&s);
9130 if( rc ) return shellDatabaseError(p->db);
9131
9132 /* Run the SQL statement prepared by the above block. Store the results
9133 ** as an array of nul-terminated strings in azResult[]. */
9134 nRow = nAlloc = 0;
9135 azResult = 0;
9136 if( nArg>1 ){
9137 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
9138 }else{
9139 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
9140 }
9141 while( sqlite3_step(pStmt)==SQLITE_ROW ){
9142 if( nRow>=nAlloc ){
9143 char **azNew;
9144 int n2 = nAlloc*2 + 10;
9145 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh4b5345c2018-04-24 13:07:40 +00009146 if( azNew==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009147 nAlloc = n2;
9148 azResult = azNew;
9149 }
9150 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
drh4b5345c2018-04-24 13:07:40 +00009151 if( 0==azResult[nRow] ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009152 nRow++;
9153 }
9154 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
9155 rc = shellDatabaseError(p->db);
9156 }
9157
9158 /* Pretty-print the contents of array azResult[] to the output */
9159 if( rc==0 && nRow>0 ){
9160 int len, maxlen = 0;
9161 int i, j;
9162 int nPrintCol, nPrintRow;
9163 for(i=0; i<nRow; i++){
9164 len = strlen30(azResult[i]);
9165 if( len>maxlen ) maxlen = len;
9166 }
9167 nPrintCol = 80/(maxlen+2);
9168 if( nPrintCol<1 ) nPrintCol = 1;
9169 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
9170 for(i=0; i<nPrintRow; i++){
9171 for(j=i; j<nRow; j+=nPrintRow){
9172 char *zSp = j<nPrintRow ? "" : " ";
9173 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
9174 azResult[j] ? azResult[j]:"");
9175 }
9176 raw_printf(p->out, "\n");
9177 }
9178 }
9179
9180 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
9181 sqlite3_free(azResult);
9182 }else
9183
9184 /* Begin redirecting output to the file "testcase-out.txt" */
9185 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
9186 output_reset(p);
drha92a01a2018-01-10 22:15:37 +00009187 p->out = output_file_open("testcase-out.txt", 0);
drh2ce15c32017-07-11 13:34:40 +00009188 if( p->out==0 ){
9189 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
9190 }
9191 if( nArg>=2 ){
9192 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
9193 }else{
9194 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
9195 }
9196 }else
9197
9198#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00009199 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00009200 static const struct {
9201 const char *zCtrlName; /* Name of a test-control option */
9202 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00009203 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00009204 } aCtrl[] = {
drhe2754c12019-08-26 12:50:01 +00009205 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
9206 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
9207 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
9208 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
9209 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
9210 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN" },
9211 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" },*/
9212 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
9213 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" },
9214 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
9215 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
9216 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00009217#ifdef YYCOVERAGE
drhe2754c12019-08-26 12:50:01 +00009218 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
drh0d9de992017-12-26 18:04:23 +00009219#endif
drhe2754c12019-08-26 12:50:01 +00009220 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
9221 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
9222 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
9223 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, "SEED ?db?" },
9224 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE"},
drh2ce15c32017-07-11 13:34:40 +00009225 };
9226 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00009227 int iCtrl = -1;
9228 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
9229 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00009230 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00009231 const char *zCmd = 0;
9232
drh2ce15c32017-07-11 13:34:40 +00009233 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00009234 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00009235
9236 /* The argument can optionally begin with "-" or "--" */
9237 if( zCmd[0]=='-' && zCmd[1] ){
9238 zCmd++;
9239 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
9240 }
9241
9242 /* --help lists all test-controls */
9243 if( strcmp(zCmd,"help")==0 ){
9244 utf8_printf(p->out, "Available test-controls:\n");
9245 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00009246 utf8_printf(p->out, " .testctrl %s %s\n",
9247 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00009248 }
9249 rc = 1;
9250 goto meta_command_exit;
9251 }
drh2ce15c32017-07-11 13:34:40 +00009252
9253 /* convert testctrl text option to value. allow any unique prefix
9254 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00009255 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00009256 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00009257 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00009258 if( testctrl<0 ){
9259 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00009260 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00009261 }else{
drh35f51a42017-11-15 17:07:22 +00009262 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
9263 "Use \".testctrl --help\" for help\n", zCmd);
9264 rc = 1;
9265 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00009266 }
9267 }
9268 }
drhef302e82017-11-15 19:14:08 +00009269 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00009270 utf8_printf(stderr,"Error: unknown test-control: %s\n"
9271 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00009272 }else{
9273 switch(testctrl){
9274
9275 /* sqlite3_test_control(int, db, int) */
9276 case SQLITE_TESTCTRL_OPTIMIZATIONS:
9277 case SQLITE_TESTCTRL_RESERVE:
9278 if( nArg==3 ){
9279 int opt = (int)strtol(azArg[2], 0, 0);
9280 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00009281 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00009282 }
9283 break;
9284
9285 /* sqlite3_test_control(int) */
9286 case SQLITE_TESTCTRL_PRNG_SAVE:
9287 case SQLITE_TESTCTRL_PRNG_RESTORE:
9288 case SQLITE_TESTCTRL_PRNG_RESET:
9289 case SQLITE_TESTCTRL_BYTEORDER:
9290 if( nArg==2 ){
9291 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00009292 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00009293 }
9294 break;
9295
9296 /* sqlite3_test_control(int, uint) */
9297 case SQLITE_TESTCTRL_PENDING_BYTE:
9298 if( nArg==3 ){
9299 unsigned int opt = (unsigned int)integerValue(azArg[2]);
9300 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00009301 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00009302 }
9303 break;
9304
drh2e6d83b2019-08-03 01:39:20 +00009305 /* sqlite3_test_control(int, int, sqlite3*) */
9306 case SQLITE_TESTCTRL_PRNG_SEED:
9307 if( nArg==3 || nArg==4 ){
drh51755a72019-08-08 19:40:29 +00009308 int ii = (int)integerValue(azArg[2]);
drh2e6d83b2019-08-03 01:39:20 +00009309 sqlite3 *db;
drh41428a92019-08-12 16:25:11 +00009310 if( ii==0 && strcmp(azArg[2],"random")==0 ){
9311 sqlite3_randomness(sizeof(ii),&ii);
9312 printf("-- random seed: %d\n", ii);
9313 }
drh2e6d83b2019-08-03 01:39:20 +00009314 if( nArg==3 ){
9315 db = 0;
9316 }else{
9317 db = p->db;
9318 /* Make sure the schema has been loaded */
9319 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0);
9320 }
drh51755a72019-08-08 19:40:29 +00009321 rc2 = sqlite3_test_control(testctrl, ii, db);
drh2e6d83b2019-08-03 01:39:20 +00009322 isOk = 3;
9323 }
9324 break;
9325
drh2ce15c32017-07-11 13:34:40 +00009326 /* sqlite3_test_control(int, int) */
9327 case SQLITE_TESTCTRL_ASSERT:
9328 case SQLITE_TESTCTRL_ALWAYS:
drheea8eb62018-11-26 18:09:15 +00009329 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
drhef302e82017-11-15 19:14:08 +00009330 if( nArg==3 ){
9331 int opt = booleanValue(azArg[2]);
9332 rc2 = sqlite3_test_control(testctrl, opt);
9333 isOk = 1;
9334 }
9335 break;
9336
9337 /* sqlite3_test_control(int, int) */
9338 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00009339 case SQLITE_TESTCTRL_NEVER_CORRUPT:
9340 if( nArg==3 ){
9341 int opt = booleanValue(azArg[2]);
9342 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00009343 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00009344 }
9345 break;
9346
drh2ce15c32017-07-11 13:34:40 +00009347 case SQLITE_TESTCTRL_IMPOSTER:
9348 if( nArg==5 ){
9349 rc2 = sqlite3_test_control(testctrl, p->db,
9350 azArg[2],
9351 integerValue(azArg[3]),
9352 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00009353 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00009354 }
9355 break;
drh0d9de992017-12-26 18:04:23 +00009356
9357#ifdef YYCOVERAGE
9358 case SQLITE_TESTCTRL_PARSER_COVERAGE:
9359 if( nArg==2 ){
9360 sqlite3_test_control(testctrl, p->out);
9361 isOk = 3;
9362 }
9363#endif
drh2ce15c32017-07-11 13:34:40 +00009364 }
9365 }
drhef302e82017-11-15 19:14:08 +00009366 if( isOk==0 && iCtrl>=0 ){
drhe2754c12019-08-26 12:50:01 +00009367 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage);
drhef302e82017-11-15 19:14:08 +00009368 rc = 1;
9369 }else if( isOk==1 ){
9370 raw_printf(p->out, "%d\n", rc2);
9371 }else if( isOk==2 ){
9372 raw_printf(p->out, "0x%08x\n", rc2);
9373 }
drh2ce15c32017-07-11 13:34:40 +00009374 }else
9375#endif /* !defined(SQLITE_UNTESTABLE) */
9376
9377 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
9378 open_db(p, 0);
9379 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
9380 }else
9381
9382 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
9383 if( nArg==2 ){
9384 enableTimer = booleanValue(azArg[1]);
9385 if( enableTimer && !HAS_TIMER ){
9386 raw_printf(stderr, "Error: timer not available on this system.\n");
9387 enableTimer = 0;
9388 }
9389 }else{
9390 raw_printf(stderr, "Usage: .timer on|off\n");
9391 rc = 1;
9392 }
9393 }else
9394
drh707821f2018-12-05 13:39:06 +00009395#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00009396 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh707821f2018-12-05 13:39:06 +00009397 int mType = 0;
9398 int jj;
drh2ce15c32017-07-11 13:34:40 +00009399 open_db(p, 0);
drh707821f2018-12-05 13:39:06 +00009400 for(jj=1; jj<nArg; jj++){
9401 const char *z = azArg[jj];
9402 if( z[0]=='-' ){
9403 if( optionMatch(z, "expanded") ){
9404 p->eTraceType = SHELL_TRACE_EXPANDED;
9405 }
9406#ifdef SQLITE_ENABLE_NORMALIZE
9407 else if( optionMatch(z, "normalized") ){
9408 p->eTraceType = SHELL_TRACE_NORMALIZED;
9409 }
9410#endif
9411 else if( optionMatch(z, "plain") ){
9412 p->eTraceType = SHELL_TRACE_PLAIN;
9413 }
9414 else if( optionMatch(z, "profile") ){
9415 mType |= SQLITE_TRACE_PROFILE;
9416 }
9417 else if( optionMatch(z, "row") ){
9418 mType |= SQLITE_TRACE_ROW;
9419 }
9420 else if( optionMatch(z, "stmt") ){
9421 mType |= SQLITE_TRACE_STMT;
9422 }
9423 else if( optionMatch(z, "close") ){
9424 mType |= SQLITE_TRACE_CLOSE;
9425 }
9426 else {
9427 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
9428 rc = 1;
9429 goto meta_command_exit;
9430 }
9431 }else{
9432 output_file_close(p->traceOut);
9433 p->traceOut = output_file_open(azArg[1], 0);
9434 }
drh2ce15c32017-07-11 13:34:40 +00009435 }
drh2ce15c32017-07-11 13:34:40 +00009436 if( p->traceOut==0 ){
9437 sqlite3_trace_v2(p->db, 0, 0, 0);
9438 }else{
drh707821f2018-12-05 13:39:06 +00009439 if( mType==0 ) mType = SQLITE_TRACE_STMT;
9440 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
drh2ce15c32017-07-11 13:34:40 +00009441 }
drh2ce15c32017-07-11 13:34:40 +00009442 }else
drh707821f2018-12-05 13:39:06 +00009443#endif /* !defined(SQLITE_OMIT_TRACE) */
drh2ce15c32017-07-11 13:34:40 +00009444
drhe2b7a762019-10-02 00:25:08 +00009445#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhcc5979d2019-08-16 22:58:29 +00009446 if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){
9447 int ii;
drh8c754a32019-08-19 20:35:30 +00009448 int lenOpt;
drh5df84282019-08-17 19:45:25 +00009449 char *zOpt;
drhcc5979d2019-08-16 22:58:29 +00009450 if( nArg<2 ){
drh5df84282019-08-17 19:45:25 +00009451 raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n");
drhcc5979d2019-08-16 22:58:29 +00009452 rc = 1;
9453 goto meta_command_exit;
9454 }
9455 open_db(p, 0);
drh5df84282019-08-17 19:45:25 +00009456 zOpt = azArg[1];
9457 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++;
drh8c754a32019-08-19 20:35:30 +00009458 lenOpt = (int)strlen(zOpt);
9459 if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){
drh5df84282019-08-17 19:45:25 +00009460 assert( azArg[nArg]==0 );
drh8c754a32019-08-19 20:35:30 +00009461 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0);
drh5df84282019-08-17 19:45:25 +00009462 }else{
9463 for(ii=1; ii<nArg; ii++){
9464 sqlite3_create_module(p->db, azArg[ii], 0, 0);
9465 }
drhcc5979d2019-08-16 22:58:29 +00009466 }
9467 }else
9468#endif
9469
drh2ce15c32017-07-11 13:34:40 +00009470#if SQLITE_USER_AUTHENTICATION
9471 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
9472 if( nArg<2 ){
9473 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
9474 rc = 1;
9475 goto meta_command_exit;
9476 }
9477 open_db(p, 0);
9478 if( strcmp(azArg[1],"login")==0 ){
9479 if( nArg!=4 ){
9480 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
9481 rc = 1;
9482 goto meta_command_exit;
9483 }
drhe2754c12019-08-26 12:50:01 +00009484 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
9485 strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00009486 if( rc ){
9487 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
9488 rc = 1;
9489 }
9490 }else if( strcmp(azArg[1],"add")==0 ){
9491 if( nArg!=5 ){
9492 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
9493 rc = 1;
9494 goto meta_command_exit;
9495 }
drhaf2770f2018-01-05 14:55:43 +00009496 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00009497 booleanValue(azArg[4]));
9498 if( rc ){
9499 raw_printf(stderr, "User-Add failed: %d\n", rc);
9500 rc = 1;
9501 }
9502 }else if( strcmp(azArg[1],"edit")==0 ){
9503 if( nArg!=5 ){
9504 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
9505 rc = 1;
9506 goto meta_command_exit;
9507 }
drhaf2770f2018-01-05 14:55:43 +00009508 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00009509 booleanValue(azArg[4]));
9510 if( rc ){
9511 raw_printf(stderr, "User-Edit failed: %d\n", rc);
9512 rc = 1;
9513 }
9514 }else if( strcmp(azArg[1],"delete")==0 ){
9515 if( nArg!=3 ){
9516 raw_printf(stderr, "Usage: .user delete USER\n");
9517 rc = 1;
9518 goto meta_command_exit;
9519 }
9520 rc = sqlite3_user_delete(p->db, azArg[2]);
9521 if( rc ){
9522 raw_printf(stderr, "User-Delete failed: %d\n", rc);
9523 rc = 1;
9524 }
9525 }else{
9526 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
9527 rc = 1;
9528 goto meta_command_exit;
9529 }
9530 }else
9531#endif /* SQLITE_USER_AUTHENTICATION */
9532
9533 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
9534 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
9535 sqlite3_libversion(), sqlite3_sourceid());
drh0ed2fd82018-01-16 20:05:27 +00009536#if SQLITE_HAVE_ZLIB
9537 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
9538#endif
9539#define CTIMEOPT_VAL_(opt) #opt
9540#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
9541#if defined(__clang__) && defined(__clang_major__)
9542 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
9543 CTIMEOPT_VAL(__clang_minor__) "."
9544 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
9545#elif defined(_MSC_VER)
9546 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
9547#elif defined(__GNUC__) && defined(__VERSION__)
9548 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
9549#endif
drh2ce15c32017-07-11 13:34:40 +00009550 }else
9551
9552 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
9553 const char *zDbName = nArg==2 ? azArg[1] : "main";
9554 sqlite3_vfs *pVfs = 0;
9555 if( p->db ){
9556 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
9557 if( pVfs ){
9558 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
9559 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
9560 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
9561 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9562 }
9563 }
9564 }else
9565
9566 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
9567 sqlite3_vfs *pVfs;
9568 sqlite3_vfs *pCurrent = 0;
9569 if( p->db ){
9570 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
9571 }
9572 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
9573 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
9574 pVfs==pCurrent ? " <--- CURRENT" : "");
9575 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
9576 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
9577 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9578 if( pVfs->pNext ){
9579 raw_printf(p->out, "-----------------------------------\n");
9580 }
9581 }
9582 }else
9583
9584 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
9585 const char *zDbName = nArg==2 ? azArg[1] : "main";
9586 char *zVfsName = 0;
9587 if( p->db ){
9588 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
9589 if( zVfsName ){
9590 utf8_printf(p->out, "%s\n", zVfsName);
9591 sqlite3_free(zVfsName);
9592 }
9593 }
9594 }else
9595
9596#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
9597 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
9598 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
9599 }else
9600#endif
9601
9602 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
9603 int j;
9604 assert( nArg<=ArraySize(azArg) );
9605 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
9606 p->colWidth[j-1] = (int)integerValue(azArg[j]);
9607 }
9608 }else
9609
9610 {
9611 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
9612 " \"%s\". Enter \".help\" for help\n", azArg[0]);
9613 rc = 1;
9614 }
9615
9616meta_command_exit:
9617 if( p->outCount ){
9618 p->outCount--;
9619 if( p->outCount==0 ) output_reset(p);
9620 }
9621 return rc;
9622}
9623
9624/*
9625** Return TRUE if a semicolon occurs anywhere in the first N characters
9626** of string z[].
9627*/
9628static int line_contains_semicolon(const char *z, int N){
9629 int i;
9630 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
9631 return 0;
9632}
9633
9634/*
9635** Test to see if a line consists entirely of whitespace.
9636*/
9637static int _all_whitespace(const char *z){
9638 for(; *z; z++){
9639 if( IsSpace(z[0]) ) continue;
9640 if( *z=='/' && z[1]=='*' ){
9641 z += 2;
9642 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
9643 if( *z==0 ) return 0;
9644 z++;
9645 continue;
9646 }
9647 if( *z=='-' && z[1]=='-' ){
9648 z += 2;
9649 while( *z && *z!='\n' ){ z++; }
9650 if( *z==0 ) return 1;
9651 continue;
9652 }
9653 return 0;
9654 }
9655 return 1;
9656}
9657
9658/*
9659** Return TRUE if the line typed in is an SQL command terminator other
9660** than a semi-colon. The SQL Server style "go" command is understood
9661** as is the Oracle "/".
9662*/
9663static int line_is_command_terminator(const char *zLine){
9664 while( IsSpace(zLine[0]) ){ zLine++; };
9665 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
9666 return 1; /* Oracle */
9667 }
9668 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
9669 && _all_whitespace(&zLine[2]) ){
9670 return 1; /* SQL Server */
9671 }
9672 return 0;
9673}
9674
9675/*
drh56f17742018-01-24 01:58:49 +00009676** We need a default sqlite3_complete() implementation to use in case
9677** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
9678** any arbitrary text is a complete SQL statement. This is not very
9679** user-friendly, but it does seem to work.
9680*/
9681#ifdef SQLITE_OMIT_COMPLETE
danc86b23b2018-11-16 14:36:42 +00009682#define sqlite3_complete(x) 1
drh56f17742018-01-24 01:58:49 +00009683#endif
9684
9685/*
drh2ce15c32017-07-11 13:34:40 +00009686** Return true if zSql is a complete SQL statement. Return false if it
9687** ends in the middle of a string literal or C-style comment.
9688*/
9689static int line_is_complete(char *zSql, int nSql){
9690 int rc;
9691 if( zSql==0 ) return 1;
9692 zSql[nSql] = ';';
9693 zSql[nSql+1] = 0;
9694 rc = sqlite3_complete(zSql);
9695 zSql[nSql] = 0;
9696 return rc;
9697}
9698
9699/*
drhfc29a862018-05-11 19:11:18 +00009700** Run a single line of SQL. Return the number of errors.
drh2ce15c32017-07-11 13:34:40 +00009701*/
9702static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
9703 int rc;
9704 char *zErrMsg = 0;
9705
9706 open_db(p, 0);
9707 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drhfc4eeef2019-02-05 19:48:46 +00009708 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
drh2ce15c32017-07-11 13:34:40 +00009709 BEGIN_TIMER;
drha10b9992018-03-09 15:24:33 +00009710 rc = shell_exec(p, zSql, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00009711 END_TIMER;
9712 if( rc || zErrMsg ){
9713 char zPrefix[100];
9714 if( in!=0 || !stdin_is_interactive ){
9715 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
9716 "Error: near line %d:", startline);
9717 }else{
9718 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
9719 }
9720 if( zErrMsg!=0 ){
9721 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
9722 sqlite3_free(zErrMsg);
9723 zErrMsg = 0;
9724 }else{
9725 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
9726 }
9727 return 1;
9728 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
9729 raw_printf(p->out, "changes: %3d total_changes: %d\n",
9730 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
9731 }
9732 return 0;
9733}
9734
9735
9736/*
9737** Read input from *in and process it. If *in==0 then input
9738** is interactive - the user is typing it it. Otherwise, input
9739** is coming from a file or device. A prompt is issued and history
9740** is saved only if input is interactive. An interrupt signal will
9741** cause this routine to exit immediately, unless input is interactive.
9742**
9743** Return the number of errors.
9744*/
drh60379d42018-12-13 18:30:01 +00009745static int process_input(ShellState *p){
drh2ce15c32017-07-11 13:34:40 +00009746 char *zLine = 0; /* A single input line */
9747 char *zSql = 0; /* Accumulated SQL text */
9748 int nLine; /* Length of current line */
9749 int nSql = 0; /* Bytes of zSql[] used */
9750 int nAlloc = 0; /* Allocated zSql[] space */
9751 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
9752 int rc; /* Error code */
9753 int errCnt = 0; /* Number of errors seen */
drh2ce15c32017-07-11 13:34:40 +00009754 int startline = 0; /* Line number for start of current input */
9755
drh2c8ee022018-12-13 18:59:30 +00009756 p->lineno = 0;
drh60379d42018-12-13 18:30:01 +00009757 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
drh2ce15c32017-07-11 13:34:40 +00009758 fflush(p->out);
drh60379d42018-12-13 18:30:01 +00009759 zLine = one_input_line(p->in, zLine, nSql>0);
drh2ce15c32017-07-11 13:34:40 +00009760 if( zLine==0 ){
9761 /* End of input */
drh60379d42018-12-13 18:30:01 +00009762 if( p->in==0 && stdin_is_interactive ) printf("\n");
drh2ce15c32017-07-11 13:34:40 +00009763 break;
9764 }
9765 if( seenInterrupt ){
drh60379d42018-12-13 18:30:01 +00009766 if( p->in!=0 ) break;
drh2ce15c32017-07-11 13:34:40 +00009767 seenInterrupt = 0;
9768 }
drh2c8ee022018-12-13 18:59:30 +00009769 p->lineno++;
drh2ce15c32017-07-11 13:34:40 +00009770 if( nSql==0 && _all_whitespace(zLine) ){
9771 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
9772 continue;
9773 }
drh1615c372018-05-12 23:56:22 +00009774 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00009775 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh1615c372018-05-12 23:56:22 +00009776 if( zLine[0]=='.' ){
9777 rc = do_meta_command(zLine, p);
9778 if( rc==2 ){ /* exit requested */
9779 break;
9780 }else if( rc ){
9781 errCnt++;
9782 }
drh2ce15c32017-07-11 13:34:40 +00009783 }
9784 continue;
9785 }
9786 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
9787 memcpy(zLine,";",2);
9788 }
9789 nLine = strlen30(zLine);
9790 if( nSql+nLine+2>=nAlloc ){
9791 nAlloc = nSql+nLine+100;
9792 zSql = realloc(zSql, nAlloc);
drh4b5345c2018-04-24 13:07:40 +00009793 if( zSql==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009794 }
9795 nSqlPrior = nSql;
9796 if( nSql==0 ){
9797 int i;
9798 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
9799 assert( nAlloc>0 && zSql!=0 );
9800 memcpy(zSql, zLine+i, nLine+1-i);
drh2c8ee022018-12-13 18:59:30 +00009801 startline = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00009802 nSql = nLine-i;
9803 }else{
9804 zSql[nSql++] = '\n';
9805 memcpy(zSql+nSql, zLine, nLine+1);
9806 nSql += nLine;
9807 }
9808 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
9809 && sqlite3_complete(zSql) ){
drh60379d42018-12-13 18:30:01 +00009810 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00009811 nSql = 0;
9812 if( p->outCount ){
9813 output_reset(p);
9814 p->outCount = 0;
drh13c20932018-01-10 21:41:55 +00009815 }else{
9816 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00009817 }
9818 }else if( nSql && _all_whitespace(zSql) ){
9819 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
9820 nSql = 0;
9821 }
9822 }
9823 if( nSql && !_all_whitespace(zSql) ){
drh60379d42018-12-13 18:30:01 +00009824 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00009825 }
9826 free(zSql);
9827 free(zLine);
9828 return errCnt>0;
9829}
9830
9831/*
9832** Return a pathname which is the user's home directory. A
9833** 0 return indicates an error of some kind.
9834*/
9835static char *find_home_dir(int clearFlag){
9836 static char *home_dir = NULL;
9837 if( clearFlag ){
9838 free(home_dir);
9839 home_dir = 0;
9840 return 0;
9841 }
9842 if( home_dir ) return home_dir;
9843
9844#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
9845 && !defined(__RTP__) && !defined(_WRS_KERNEL)
9846 {
9847 struct passwd *pwent;
9848 uid_t uid = getuid();
9849 if( (pwent=getpwuid(uid)) != NULL) {
9850 home_dir = pwent->pw_dir;
9851 }
9852 }
9853#endif
9854
9855#if defined(_WIN32_WCE)
9856 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
9857 */
9858 home_dir = "/";
9859#else
9860
9861#if defined(_WIN32) || defined(WIN32)
9862 if (!home_dir) {
9863 home_dir = getenv("USERPROFILE");
9864 }
9865#endif
9866
9867 if (!home_dir) {
9868 home_dir = getenv("HOME");
9869 }
9870
9871#if defined(_WIN32) || defined(WIN32)
9872 if (!home_dir) {
9873 char *zDrive, *zPath;
9874 int n;
9875 zDrive = getenv("HOMEDRIVE");
9876 zPath = getenv("HOMEPATH");
9877 if( zDrive && zPath ){
9878 n = strlen30(zDrive) + strlen30(zPath) + 1;
9879 home_dir = malloc( n );
9880 if( home_dir==0 ) return 0;
9881 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
9882 return home_dir;
9883 }
9884 home_dir = "c:\\";
9885 }
9886#endif
9887
9888#endif /* !_WIN32_WCE */
9889
9890 if( home_dir ){
9891 int n = strlen30(home_dir) + 1;
9892 char *z = malloc( n );
9893 if( z ) memcpy(z, home_dir, n);
9894 home_dir = z;
9895 }
9896
9897 return home_dir;
9898}
9899
9900/*
9901** Read input from the file given by sqliterc_override. Or if that
9902** parameter is NULL, take input from ~/.sqliterc
9903**
9904** Returns the number of errors.
9905*/
9906static void process_sqliterc(
9907 ShellState *p, /* Configuration data */
9908 const char *sqliterc_override /* Name of config file. NULL to use default */
9909){
9910 char *home_dir = NULL;
9911 const char *sqliterc = sqliterc_override;
9912 char *zBuf = 0;
drh60379d42018-12-13 18:30:01 +00009913 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00009914 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00009915
9916 if (sqliterc == NULL) {
9917 home_dir = find_home_dir(0);
9918 if( home_dir==0 ){
9919 raw_printf(stderr, "-- warning: cannot find home directory;"
9920 " cannot read ~/.sqliterc\n");
9921 return;
9922 }
drh2ce15c32017-07-11 13:34:40 +00009923 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
9924 sqliterc = zBuf;
9925 }
drh60379d42018-12-13 18:30:01 +00009926 p->in = fopen(sqliterc,"rb");
9927 if( p->in ){
drh2ce15c32017-07-11 13:34:40 +00009928 if( stdin_is_interactive ){
9929 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
9930 }
drh60379d42018-12-13 18:30:01 +00009931 process_input(p);
9932 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00009933 }
drh60379d42018-12-13 18:30:01 +00009934 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00009935 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00009936 sqlite3_free(zBuf);
9937}
9938
9939/*
9940** Show available command line options
9941*/
9942static const char zOptions[] =
drhda57d962018-03-05 19:34:05 +00009943#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhad7fd5d2018-03-05 20:21:50 +00009944 " -A ARGS... run \".archive ARGS\" and exit\n"
drhda57d962018-03-05 19:34:05 +00009945#endif
drh3baed312018-03-08 18:14:41 +00009946 " -append append the database to the end of the file\n"
drh2ce15c32017-07-11 13:34:40 +00009947 " -ascii set output mode to 'ascii'\n"
9948 " -bail stop after hitting an error\n"
9949 " -batch force batch I/O\n"
9950 " -column set output mode to 'column'\n"
9951 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
9952 " -csv set output mode to 'csv'\n"
drh6ca64482019-01-22 16:06:20 +00009953#if defined(SQLITE_ENABLE_DESERIALIZE)
9954 " -deserialize open the database using sqlite3_deserialize()\n"
9955#endif
drh2ce15c32017-07-11 13:34:40 +00009956 " -echo print commands before execution\n"
9957 " -init FILENAME read/process named file\n"
9958 " -[no]header turn headers on or off\n"
9959#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
9960 " -heap SIZE Size of heap for memsys3 or memsys5\n"
9961#endif
9962 " -help show this message\n"
9963 " -html set output mode to HTML\n"
9964 " -interactive force interactive I/O\n"
9965 " -line set output mode to 'line'\n"
9966 " -list set output mode to 'list'\n"
9967 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh6ca64482019-01-22 16:06:20 +00009968#if defined(SQLITE_ENABLE_DESERIALIZE)
9969 " -maxsize N maximum size for a --deserialize database\n"
9970#endif
drhaf482572019-02-04 19:52:39 +00009971 " -memtrace trace all memory allocations and deallocations\n"
drh2ce15c32017-07-11 13:34:40 +00009972 " -mmap N default mmap size set to N\n"
9973#ifdef SQLITE_ENABLE_MULTIPLEX
9974 " -multiplex enable the multiplexor VFS\n"
9975#endif
9976 " -newline SEP set output row separator. Default: '\\n'\n"
9977 " -nullvalue TEXT set text string for NULL values. Default ''\n"
9978 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
9979 " -quote set output mode to 'quote'\n"
drhee269a62018-02-14 23:27:43 +00009980 " -readonly open the database read-only\n"
drh2ce15c32017-07-11 13:34:40 +00009981 " -separator SEP set output column separator. Default: '|'\n"
drha90d84f2018-04-18 15:21:13 +00009982#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9983 " -sorterref SIZE sorter references threshold size\n"
9984#endif
drh2ce15c32017-07-11 13:34:40 +00009985 " -stats print memory stats before each finalize\n"
9986 " -version show SQLite version\n"
9987 " -vfs NAME use NAME as the default VFS\n"
9988#ifdef SQLITE_ENABLE_VFSTRACE
9989 " -vfstrace enable tracing of all VFS calls\n"
9990#endif
drh3baed312018-03-08 18:14:41 +00009991#ifdef SQLITE_HAVE_ZLIB
9992 " -zip open the file as a ZIP Archive\n"
9993#endif
drh2ce15c32017-07-11 13:34:40 +00009994;
9995static void usage(int showDetail){
9996 utf8_printf(stderr,
9997 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
9998 "FILENAME is the name of an SQLite database. A new database is created\n"
9999 "if the file does not previously exist.\n", Argv0);
10000 if( showDetail ){
10001 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
10002 }else{
10003 raw_printf(stderr, "Use the -help option for additional information\n");
10004 }
10005 exit(1);
10006}
10007
10008/*
drhe7df8922018-04-18 10:44:58 +000010009** Internal check: Verify that the SQLite is uninitialized. Print a
10010** error message if it is initialized.
10011*/
10012static void verify_uninitialized(void){
10013 if( sqlite3_config(-1)==SQLITE_MISUSE ){
drh8e02a182018-05-30 07:24:41 +000010014 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
drhe7df8922018-04-18 10:44:58 +000010015 " initialization.\n");
10016 }
10017}
10018
10019/*
drh2ce15c32017-07-11 13:34:40 +000010020** Initialize the state information in data
10021*/
10022static void main_init(ShellState *data) {
10023 memset(data, 0, sizeof(*data));
10024 data->normalMode = data->cMode = data->mode = MODE_List;
10025 data->autoExplain = 1;
10026 memcpy(data->colSeparator,SEP_Column, 2);
10027 memcpy(data->rowSeparator,SEP_Row, 2);
10028 data->showHeader = 0;
10029 data->shellFlgs = SHFLG_Lookaside;
drhe7df8922018-04-18 10:44:58 +000010030 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +000010031 sqlite3_config(SQLITE_CONFIG_URI, 1);
10032 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
10033 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
10034 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
10035 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
10036}
10037
10038/*
10039** Output text to the console in a font that attracts extra attention.
10040*/
10041#ifdef _WIN32
10042static void printBold(const char *zText){
10043 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
10044 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
10045 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
10046 SetConsoleTextAttribute(out,
10047 FOREGROUND_RED|FOREGROUND_INTENSITY
10048 );
10049 printf("%s", zText);
10050 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
10051}
10052#else
10053static void printBold(const char *zText){
10054 printf("\033[1m%s\033[0m", zText);
10055}
10056#endif
10057
10058/*
10059** Get the argument to an --option. Throw an error and die if no argument
10060** is available.
10061*/
10062static char *cmdline_option_value(int argc, char **argv, int i){
10063 if( i==argc ){
10064 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
10065 argv[0], argv[argc-1]);
10066 exit(1);
10067 }
10068 return argv[i];
10069}
10070
10071#ifndef SQLITE_SHELL_IS_UTF8
10072# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
10073# define SQLITE_SHELL_IS_UTF8 (0)
10074# else
10075# define SQLITE_SHELL_IS_UTF8 (1)
10076# endif
10077#endif
10078
10079#if SQLITE_SHELL_IS_UTF8
10080int SQLITE_CDECL main(int argc, char **argv){
10081#else
10082int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
10083 char **argv;
10084#endif
10085 char *zErrMsg = 0;
10086 ShellState data;
10087 const char *zInitFile = 0;
10088 int i;
10089 int rc = 0;
10090 int warnInmemoryDb = 0;
10091 int readStdin = 1;
10092 int nCmd = 0;
10093 char **azCmd = 0;
dan16a47422018-04-18 09:16:11 +000010094 const char *zVfs = 0; /* Value of -vfs command-line option */
drh1f22f622018-05-17 13:29:14 +000010095#if !SQLITE_SHELL_IS_UTF8
10096 char **argvToFree = 0;
10097 int argcToFree = 0;
10098#endif
drh2ce15c32017-07-11 13:34:40 +000010099
10100 setBinaryMode(stdin, 0);
10101 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
10102 stdin_is_interactive = isatty(0);
10103 stdout_is_console = isatty(1);
10104
mistachkin1e8487d2018-07-22 06:25:35 +000010105#if !defined(_WIN32_WCE)
10106 if( getenv("SQLITE_DEBUG_BREAK") ){
10107 if( isatty(0) && isatty(2) ){
10108 fprintf(stderr,
10109 "attach debugger to process %d and press any key to continue.\n",
10110 GETPID());
10111 fgetc(stdin);
10112 }else{
10113#if defined(_WIN32) || defined(WIN32)
10114 DebugBreak();
10115#elif defined(SIGTRAP)
10116 raise(SIGTRAP);
10117#endif
10118 }
10119 }
10120#endif
10121
drh2ce15c32017-07-11 13:34:40 +000010122#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +000010123 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +000010124 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
10125 sqlite3_sourceid(), SQLITE_SOURCE_ID);
10126 exit(1);
10127 }
10128#endif
10129 main_init(&data);
drh501ea052018-02-15 01:03:37 +000010130
10131 /* On Windows, we must translate command-line arguments into UTF-8.
10132 ** The SQLite memory allocator subsystem has to be enabled in order to
10133 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
10134 ** subsequent sqlite3_config() calls will work. So copy all results into
10135 ** memory that does not come from the SQLite memory allocator.
10136 */
drh4b18c1d2018-02-04 20:33:13 +000010137#if !SQLITE_SHELL_IS_UTF8
drh501ea052018-02-15 01:03:37 +000010138 sqlite3_initialize();
drh1f22f622018-05-17 13:29:14 +000010139 argvToFree = malloc(sizeof(argv[0])*argc*2);
10140 argcToFree = argc;
10141 argv = argvToFree + argc;
drh4b5345c2018-04-24 13:07:40 +000010142 if( argv==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +000010143 for(i=0; i<argc; i++){
drh501ea052018-02-15 01:03:37 +000010144 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
10145 int n;
drh4b5345c2018-04-24 13:07:40 +000010146 if( z==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +000010147 n = (int)strlen(z);
10148 argv[i] = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +000010149 if( argv[i]==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +000010150 memcpy(argv[i], z, n+1);
drh1f22f622018-05-17 13:29:14 +000010151 argvToFree[i] = argv[i];
drh501ea052018-02-15 01:03:37 +000010152 sqlite3_free(z);
drh2ce15c32017-07-11 13:34:40 +000010153 }
drh501ea052018-02-15 01:03:37 +000010154 sqlite3_shutdown();
drh2ce15c32017-07-11 13:34:40 +000010155#endif
drh501ea052018-02-15 01:03:37 +000010156
drh2ce15c32017-07-11 13:34:40 +000010157 assert( argc>=1 && argv && argv[0] );
10158 Argv0 = argv[0];
10159
10160 /* Make sure we have a valid signal handler early, before anything
10161 ** else is done.
10162 */
10163#ifdef SIGINT
10164 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +000010165#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
10166 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +000010167#endif
10168
10169#ifdef SQLITE_SHELL_DBNAME_PROC
10170 {
10171 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
10172 ** of a C-function that will provide the name of the database file. Use
10173 ** this compile-time option to embed this shell program in larger
10174 ** applications. */
10175 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
10176 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
10177 warnInmemoryDb = 0;
10178 }
10179#endif
10180
10181 /* Do an initial pass through the command-line argument to locate
10182 ** the name of the database file, the name of the initialization file,
10183 ** the size of the alternative malloc heap,
10184 ** and the first command to execute.
10185 */
drhe7df8922018-04-18 10:44:58 +000010186 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +000010187 for(i=1; i<argc; i++){
10188 char *z;
10189 z = argv[i];
10190 if( z[0]!='-' ){
10191 if( data.zDbFilename==0 ){
10192 data.zDbFilename = z;
10193 }else{
10194 /* Excesss arguments are interpreted as SQL (or dot-commands) and
10195 ** mean that nothing is read from stdin */
10196 readStdin = 0;
10197 nCmd++;
10198 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
drh4b5345c2018-04-24 13:07:40 +000010199 if( azCmd==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +000010200 azCmd[nCmd-1] = z;
10201 }
10202 }
10203 if( z[1]=='-' ) z++;
10204 if( strcmp(z,"-separator")==0
10205 || strcmp(z,"-nullvalue")==0
10206 || strcmp(z,"-newline")==0
10207 || strcmp(z,"-cmd")==0
10208 ){
10209 (void)cmdline_option_value(argc, argv, ++i);
10210 }else if( strcmp(z,"-init")==0 ){
10211 zInitFile = cmdline_option_value(argc, argv, ++i);
10212 }else if( strcmp(z,"-batch")==0 ){
10213 /* Need to check for batch mode here to so we can avoid printing
10214 ** informational messages (like from process_sqliterc) before
10215 ** we do the actual processing of arguments later in a second pass.
10216 */
10217 stdin_is_interactive = 0;
10218 }else if( strcmp(z,"-heap")==0 ){
10219#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
10220 const char *zSize;
10221 sqlite3_int64 szHeap;
10222
10223 zSize = cmdline_option_value(argc, argv, ++i);
10224 szHeap = integerValue(zSize);
10225 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
10226 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
10227#else
10228 (void)cmdline_option_value(argc, argv, ++i);
10229#endif
drh2ce15c32017-07-11 13:34:40 +000010230 }else if( strcmp(z,"-pagecache")==0 ){
10231 int n, sz;
10232 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
10233 if( sz>70000 ) sz = 70000;
10234 if( sz<0 ) sz = 0;
10235 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
10236 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
10237 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
10238 data.shellFlgs |= SHFLG_Pagecache;
10239 }else if( strcmp(z,"-lookaside")==0 ){
10240 int n, sz;
10241 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
10242 if( sz<0 ) sz = 0;
10243 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
10244 if( n<0 ) n = 0;
10245 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
10246 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
10247#ifdef SQLITE_ENABLE_VFSTRACE
10248 }else if( strcmp(z,"-vfstrace")==0 ){
10249 extern int vfstrace_register(
10250 const char *zTraceName,
10251 const char *zOldVfsName,
10252 int (*xOut)(const char*,void*),
10253 void *pOutArg,
10254 int makeDefault
10255 );
10256 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
10257#endif
10258#ifdef SQLITE_ENABLE_MULTIPLEX
10259 }else if( strcmp(z,"-multiplex")==0 ){
10260 extern int sqlite3_multiple_initialize(const char*,int);
10261 sqlite3_multiplex_initialize(0, 1);
10262#endif
10263 }else if( strcmp(z,"-mmap")==0 ){
10264 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
10265 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drha90d84f2018-04-18 15:21:13 +000010266#ifdef SQLITE_ENABLE_SORTER_REFERENCES
10267 }else if( strcmp(z,"-sorterref")==0 ){
10268 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
10269 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
10270#endif
drh2ce15c32017-07-11 13:34:40 +000010271 }else if( strcmp(z,"-vfs")==0 ){
dan16a47422018-04-18 09:16:11 +000010272 zVfs = cmdline_option_value(argc, argv, ++i);
drh3baed312018-03-08 18:14:41 +000010273#ifdef SQLITE_HAVE_ZLIB
drh8682e122018-01-07 20:38:10 +000010274 }else if( strcmp(z,"-zip")==0 ){
10275 data.openMode = SHELL_OPEN_ZIPFILE;
10276#endif
10277 }else if( strcmp(z,"-append")==0 ){
10278 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +000010279#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +000010280 }else if( strcmp(z,"-deserialize")==0 ){
10281 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +000010282 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
10283 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +000010284#endif
drhee269a62018-02-14 23:27:43 +000010285 }else if( strcmp(z,"-readonly")==0 ){
10286 data.openMode = SHELL_OPEN_READONLY;
drhda57d962018-03-05 19:34:05 +000010287#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +000010288 }else if( strncmp(z, "-A",2)==0 ){
drhda57d962018-03-05 19:34:05 +000010289 /* All remaining command-line arguments are passed to the ".archive"
10290 ** command, so ignore them */
10291 break;
10292#endif
drh50b910a2019-01-21 14:55:03 +000010293 }else if( strcmp(z, "-memtrace")==0 ){
10294 sqlite3MemTraceActivate(stderr);
drh2ce15c32017-07-11 13:34:40 +000010295 }
10296 }
drhe7df8922018-04-18 10:44:58 +000010297 verify_uninitialized();
10298
dan16a47422018-04-18 09:16:11 +000010299
drhd11b8f62018-04-25 13:27:07 +000010300#ifdef SQLITE_SHELL_INIT_PROC
10301 {
10302 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
10303 ** of a C-function that will perform initialization actions on SQLite that
10304 ** occur just before or after sqlite3_initialize(). Use this compile-time
10305 ** option to embed this shell program in larger applications. */
10306 extern void SQLITE_SHELL_INIT_PROC(void);
10307 SQLITE_SHELL_INIT_PROC();
10308 }
10309#else
dan16a47422018-04-18 09:16:11 +000010310 /* All the sqlite3_config() calls have now been made. So it is safe
10311 ** to call sqlite3_initialize() and process any command line -vfs option. */
10312 sqlite3_initialize();
drhd11b8f62018-04-25 13:27:07 +000010313#endif
10314
dan16a47422018-04-18 09:16:11 +000010315 if( zVfs ){
10316 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
10317 if( pVfs ){
10318 sqlite3_vfs_register(pVfs, 1);
10319 }else{
10320 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
10321 exit(1);
10322 }
10323 }
10324
drh2ce15c32017-07-11 13:34:40 +000010325 if( data.zDbFilename==0 ){
10326#ifndef SQLITE_OMIT_MEMORYDB
10327 data.zDbFilename = ":memory:";
10328 warnInmemoryDb = argc==1;
10329#else
10330 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
10331 return 1;
10332#endif
10333 }
10334 data.out = stdout;
drh8682e122018-01-07 20:38:10 +000010335 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +000010336
10337 /* Go ahead and open the database file if it already exists. If the
10338 ** file does not exist, delay opening it. This prevents empty database
10339 ** files from being created if a user mistypes the database name argument
10340 ** to the sqlite command-line tool.
10341 */
10342 if( access(data.zDbFilename, 0)==0 ){
10343 open_db(&data, 0);
10344 }
10345
10346 /* Process the initialization file if there is one. If no -init option
10347 ** is given on the command line, look for a file named ~/.sqliterc and
10348 ** try to process it.
10349 */
10350 process_sqliterc(&data,zInitFile);
10351
10352 /* Make a second pass through the command-line argument and set
10353 ** options. This second pass is delayed until after the initialization
10354 ** file is processed so that the command-line arguments will override
10355 ** settings in the initialization file.
10356 */
10357 for(i=1; i<argc; i++){
10358 char *z = argv[i];
10359 if( z[0]!='-' ) continue;
10360 if( z[1]=='-' ){ z++; }
10361 if( strcmp(z,"-init")==0 ){
10362 i++;
10363 }else if( strcmp(z,"-html")==0 ){
10364 data.mode = MODE_Html;
10365 }else if( strcmp(z,"-list")==0 ){
10366 data.mode = MODE_List;
10367 }else if( strcmp(z,"-quote")==0 ){
10368 data.mode = MODE_Quote;
10369 }else if( strcmp(z,"-line")==0 ){
10370 data.mode = MODE_Line;
10371 }else if( strcmp(z,"-column")==0 ){
10372 data.mode = MODE_Column;
10373 }else if( strcmp(z,"-csv")==0 ){
10374 data.mode = MODE_Csv;
10375 memcpy(data.colSeparator,",",2);
drh3baed312018-03-08 18:14:41 +000010376#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +000010377 }else if( strcmp(z,"-zip")==0 ){
10378 data.openMode = SHELL_OPEN_ZIPFILE;
10379#endif
10380 }else if( strcmp(z,"-append")==0 ){
10381 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +000010382#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +000010383 }else if( strcmp(z,"-deserialize")==0 ){
10384 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +000010385 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
10386 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +000010387#endif
drh4aafe592018-03-23 16:08:30 +000010388 }else if( strcmp(z,"-readonly")==0 ){
10389 data.openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +000010390 }else if( strcmp(z,"-ascii")==0 ){
10391 data.mode = MODE_Ascii;
10392 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
10393 SEP_Unit);
10394 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
10395 SEP_Record);
10396 }else if( strcmp(z,"-separator")==0 ){
10397 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
10398 "%s",cmdline_option_value(argc,argv,++i));
10399 }else if( strcmp(z,"-newline")==0 ){
10400 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
10401 "%s",cmdline_option_value(argc,argv,++i));
10402 }else if( strcmp(z,"-nullvalue")==0 ){
10403 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
10404 "%s",cmdline_option_value(argc,argv,++i));
10405 }else if( strcmp(z,"-header")==0 ){
10406 data.showHeader = 1;
10407 }else if( strcmp(z,"-noheader")==0 ){
10408 data.showHeader = 0;
10409 }else if( strcmp(z,"-echo")==0 ){
10410 ShellSetFlag(&data, SHFLG_Echo);
10411 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +000010412 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +000010413 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +000010414 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +000010415 }else if( strcmp(z,"-stats")==0 ){
10416 data.statsOn = 1;
10417 }else if( strcmp(z,"-scanstats")==0 ){
10418 data.scanstatsOn = 1;
10419 }else if( strcmp(z,"-backslash")==0 ){
10420 /* Undocumented command-line option: -backslash
10421 ** Causes C-style backslash escapes to be evaluated in SQL statements
10422 ** prior to sending the SQL into SQLite. Useful for injecting
10423 ** crazy bytes in the middle of SQL statements for testing and debugging.
10424 */
10425 ShellSetFlag(&data, SHFLG_Backslash);
10426 }else if( strcmp(z,"-bail")==0 ){
10427 bail_on_error = 1;
10428 }else if( strcmp(z,"-version")==0 ){
10429 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
10430 return 0;
10431 }else if( strcmp(z,"-interactive")==0 ){
10432 stdin_is_interactive = 1;
10433 }else if( strcmp(z,"-batch")==0 ){
10434 stdin_is_interactive = 0;
10435 }else if( strcmp(z,"-heap")==0 ){
10436 i++;
drh2ce15c32017-07-11 13:34:40 +000010437 }else if( strcmp(z,"-pagecache")==0 ){
10438 i+=2;
10439 }else if( strcmp(z,"-lookaside")==0 ){
10440 i+=2;
10441 }else if( strcmp(z,"-mmap")==0 ){
10442 i++;
drh50b910a2019-01-21 14:55:03 +000010443 }else if( strcmp(z,"-memtrace")==0 ){
10444 i++;
drha90d84f2018-04-18 15:21:13 +000010445#ifdef SQLITE_ENABLE_SORTER_REFERENCES
10446 }else if( strcmp(z,"-sorterref")==0 ){
10447 i++;
10448#endif
drh2ce15c32017-07-11 13:34:40 +000010449 }else if( strcmp(z,"-vfs")==0 ){
10450 i++;
10451#ifdef SQLITE_ENABLE_VFSTRACE
10452 }else if( strcmp(z,"-vfstrace")==0 ){
10453 i++;
10454#endif
10455#ifdef SQLITE_ENABLE_MULTIPLEX
10456 }else if( strcmp(z,"-multiplex")==0 ){
10457 i++;
10458#endif
10459 }else if( strcmp(z,"-help")==0 ){
10460 usage(1);
10461 }else if( strcmp(z,"-cmd")==0 ){
10462 /* Run commands that follow -cmd first and separately from commands
10463 ** that simply appear on the command-line. This seems goofy. It would
10464 ** be better if all commands ran in the order that they appear. But
10465 ** we retain the goofy behavior for historical compatibility. */
10466 if( i==argc-1 ) break;
10467 z = cmdline_option_value(argc,argv,++i);
10468 if( z[0]=='.' ){
10469 rc = do_meta_command(z, &data);
10470 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
10471 }else{
10472 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +000010473 rc = shell_exec(&data, z, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +000010474 if( zErrMsg!=0 ){
10475 utf8_printf(stderr,"Error: %s\n", zErrMsg);
10476 if( bail_on_error ) return rc!=0 ? rc : 1;
10477 }else if( rc!=0 ){
10478 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
10479 if( bail_on_error ) return rc;
10480 }
10481 }
drhda57d962018-03-05 19:34:05 +000010482#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +000010483 }else if( strncmp(z, "-A", 2)==0 ){
drhda57d962018-03-05 19:34:05 +000010484 if( nCmd>0 ){
10485 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
10486 " with \"%s\"\n", z);
10487 return 1;
10488 }
drhbe4ccb22018-05-17 20:04:24 +000010489 open_db(&data, OPEN_DB_ZIPFILE);
drh93b77312018-03-05 20:20:22 +000010490 if( z[2] ){
10491 argv[i] = &z[2];
drhd0f9cdc2018-05-17 14:09:06 +000010492 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
drh93b77312018-03-05 20:20:22 +000010493 }else{
drhd0f9cdc2018-05-17 14:09:06 +000010494 arDotCommand(&data, 1, argv+i, argc-i);
drh93b77312018-03-05 20:20:22 +000010495 }
drhda57d962018-03-05 19:34:05 +000010496 readStdin = 0;
10497 break;
10498#endif
drh2ce15c32017-07-11 13:34:40 +000010499 }else{
10500 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
10501 raw_printf(stderr,"Use -help for a list of options.\n");
10502 return 1;
10503 }
10504 data.cMode = data.mode;
10505 }
10506
10507 if( !readStdin ){
10508 /* Run all arguments that do not begin with '-' as if they were separate
10509 ** command-line inputs, except for the argToSkip argument which contains
10510 ** the database filename.
10511 */
10512 for(i=0; i<nCmd; i++){
10513 if( azCmd[i][0]=='.' ){
10514 rc = do_meta_command(azCmd[i], &data);
10515 if( rc ) return rc==2 ? 0 : rc;
10516 }else{
10517 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +000010518 rc = shell_exec(&data, azCmd[i], &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +000010519 if( zErrMsg!=0 ){
10520 utf8_printf(stderr,"Error: %s\n", zErrMsg);
10521 return rc!=0 ? rc : 1;
10522 }else if( rc!=0 ){
10523 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
10524 return rc;
10525 }
10526 }
10527 }
10528 free(azCmd);
10529 }else{
10530 /* Run commands received from standard input
10531 */
10532 if( stdin_is_interactive ){
10533 char *zHome;
drha9e4be32018-10-10 18:56:40 +000010534 char *zHistory;
drh2ce15c32017-07-11 13:34:40 +000010535 int nHistory;
10536 printf(
10537 "SQLite version %s %.19s\n" /*extra-version-info*/
10538 "Enter \".help\" for usage hints.\n",
10539 sqlite3_libversion(), sqlite3_sourceid()
10540 );
10541 if( warnInmemoryDb ){
10542 printf("Connected to a ");
10543 printBold("transient in-memory database");
10544 printf(".\nUse \".open FILENAME\" to reopen on a "
10545 "persistent database.\n");
10546 }
drha9e4be32018-10-10 18:56:40 +000010547 zHistory = getenv("SQLITE_HISTORY");
10548 if( zHistory ){
10549 zHistory = strdup(zHistory);
10550 }else if( (zHome = find_home_dir(0))!=0 ){
drh2ce15c32017-07-11 13:34:40 +000010551 nHistory = strlen30(zHome) + 20;
10552 if( (zHistory = malloc(nHistory))!=0 ){
10553 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
10554 }
10555 }
10556 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +000010557#if HAVE_READLINE || HAVE_EDITLINE
10558 rl_attempted_completion_function = readline_completion;
10559#elif HAVE_LINENOISE
10560 linenoiseSetCompletionCallback(linenoise_completion);
10561#endif
drh60379d42018-12-13 18:30:01 +000010562 data.in = 0;
10563 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +000010564 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +000010565 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +000010566 shell_write_history(zHistory);
10567 free(zHistory);
10568 }
10569 }else{
drh60379d42018-12-13 18:30:01 +000010570 data.in = stdin;
10571 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +000010572 }
10573 }
10574 set_table_name(&data, 0);
10575 if( data.db ){
10576 session_close_all(&data);
drh9e804032018-05-18 17:11:50 +000010577 close_db(data.db);
drh2ce15c32017-07-11 13:34:40 +000010578 }
10579 sqlite3_free(data.zFreeOnClose);
10580 find_home_dir(1);
drh536c3452018-01-11 00:38:39 +000010581 output_reset(&data);
10582 data.doXdgOpen = 0;
drh13c20932018-01-10 21:41:55 +000010583 clearTempFile(&data);
drh2ce15c32017-07-11 13:34:40 +000010584#if !SQLITE_SHELL_IS_UTF8
drh1f22f622018-05-17 13:29:14 +000010585 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
10586 free(argvToFree);
drh2ce15c32017-07-11 13:34:40 +000010587#endif
drh9e804032018-05-18 17:11:50 +000010588 /* Clear the global data structure so that valgrind will detect memory
10589 ** leaks */
10590 memset(&data, 0, sizeof(data));
drh2ce15c32017-07-11 13:34:40 +000010591 return rc;
10592}