blob: 8c967a83d8e24b17cd11c3e5f884792f37233778 [file] [log] [blame]
drh2ce15c32017-07-11 13:34:40 +00001/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
14*/
15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
20/*
21** Warning pragmas copied from msvc.h in the core.
22*/
23#if defined(_MSC_VER)
24#pragma warning(disable : 4054)
25#pragma warning(disable : 4055)
26#pragma warning(disable : 4100)
27#pragma warning(disable : 4127)
28#pragma warning(disable : 4130)
29#pragma warning(disable : 4152)
30#pragma warning(disable : 4189)
31#pragma warning(disable : 4206)
32#pragma warning(disable : 4210)
33#pragma warning(disable : 4232)
34#pragma warning(disable : 4244)
35#pragma warning(disable : 4305)
36#pragma warning(disable : 4306)
37#pragma warning(disable : 4702)
38#pragma warning(disable : 4706)
39#endif /* defined(_MSC_VER) */
40
41/*
42** No support for loadable extensions in VxWorks.
43*/
44#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45# define SQLITE_OMIT_LOAD_EXTENSION 1
46#endif
47
48/*
49** Enable large-file support for fopen() and friends on unix.
50*/
51#ifndef SQLITE_DISABLE_LFS
52# define _LARGE_FILE 1
53# ifndef _FILE_OFFSET_BITS
54# define _FILE_OFFSET_BITS 64
55# endif
56# define _LARGEFILE_SOURCE 1
57#endif
58
59#include <stdlib.h>
60#include <string.h>
61#include <stdio.h>
62#include <assert.h>
63#include "sqlite3.h"
drh1e506b52018-01-05 21:01:37 +000064typedef sqlite3_int64 i64;
65typedef sqlite3_uint64 u64;
drh1fa6d9f2018-01-06 21:46:01 +000066typedef unsigned char u8;
drh2ce15c32017-07-11 13:34:40 +000067#if SQLITE_USER_AUTHENTICATION
68# include "sqlite3userauth.h"
69#endif
70#include <ctype.h>
71#include <stdarg.h>
72
73#if !defined(_WIN32) && !defined(WIN32)
74# include <signal.h>
75# if !defined(__RTP__) && !defined(_WRS_KERNEL)
76# include <pwd.h>
77# endif
mistachkinacae8c32018-01-05 20:08:46 +000078#endif
mistachkin562f0c82018-01-09 00:28:24 +000079#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
drh2ce15c32017-07-11 13:34:40 +000080# include <unistd.h>
mistachkinacae8c32018-01-05 20:08:46 +000081# include <dirent.h>
mistachkin1e8487d2018-07-22 06:25:35 +000082# define GETPID getpid
mistachkin562f0c82018-01-09 00:28:24 +000083# if defined(__MINGW32__)
mistachkinacae8c32018-01-05 20:08:46 +000084# define DIRENT dirent
mistachkin2f74b3c2018-01-05 20:26:06 +000085# ifndef S_ISLNK
86# define S_ISLNK(mode) (0)
87# endif
mistachkinacae8c32018-01-05 20:08:46 +000088# endif
mistachkin1e8487d2018-07-22 06:25:35 +000089#else
90# define GETPID (int)GetCurrentProcessId
drh2ce15c32017-07-11 13:34:40 +000091#endif
mistachkindfdfd8c2018-01-04 22:46:08 +000092#include <sys/types.h>
93#include <sys/stat.h>
drh2ce15c32017-07-11 13:34:40 +000094
95#if HAVE_READLINE
96# include <readline/readline.h>
97# include <readline/history.h>
98#endif
99
100#if HAVE_EDITLINE
101# include <editline/readline.h>
102#endif
103
104#if HAVE_EDITLINE || HAVE_READLINE
105
106# define shell_add_history(X) add_history(X)
107# define shell_read_history(X) read_history(X)
108# define shell_write_history(X) write_history(X)
109# define shell_stifle_history(X) stifle_history(X)
110# define shell_readline(X) readline(X)
111
112#elif HAVE_LINENOISE
113
114# include "linenoise.h"
115# define shell_add_history(X) linenoiseHistoryAdd(X)
116# define shell_read_history(X) linenoiseHistoryLoad(X)
117# define shell_write_history(X) linenoiseHistorySave(X)
118# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
119# define shell_readline(X) linenoise(X)
120
121#else
122
123# define shell_read_history(X)
124# define shell_write_history(X)
125# define shell_stifle_history(X)
126
127# define SHELL_USE_LOCAL_GETLINE 1
128#endif
129
130
131#if defined(_WIN32) || defined(WIN32)
132# include <io.h>
133# include <fcntl.h>
134# define isatty(h) _isatty(h)
135# ifndef access
136# define access(f,m) _access((f),(m))
137# endif
mistachkince2052b2018-03-23 00:31:53 +0000138# ifndef unlink
139# define unlink _unlink
140# endif
drhc5ea2d42019-01-22 16:44:59 +0000141# ifndef strdup
142# define strdup _strdup
143# endif
drh2ce15c32017-07-11 13:34:40 +0000144# undef popen
145# define popen _popen
146# undef pclose
147# define pclose _pclose
148#else
149 /* Make sure isatty() has a prototype. */
150 extern int isatty(int);
151
152# if !defined(__RTP__) && !defined(_WRS_KERNEL)
153 /* popen and pclose are not C89 functions and so are
154 ** sometimes omitted from the <stdio.h> header */
155 extern FILE *popen(const char*,const char*);
156 extern int pclose(FILE*);
157# else
158# define SQLITE_OMIT_POPEN 1
159# endif
160#endif
161
162#if defined(_WIN32_WCE)
163/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
164 * thus we always assume that we have a console. That can be
165 * overridden with the -batch command line option.
166 */
167#define isatty(x) 1
168#endif
169
170/* ctype macros that work with signed characters */
171#define IsSpace(X) isspace((unsigned char)X)
172#define IsDigit(X) isdigit((unsigned char)X)
173#define ToLower(X) (char)tolower((unsigned char)X)
174
175#if defined(_WIN32) || defined(WIN32)
176#include <windows.h>
177
178/* string conversion routines only needed on Win32 */
179extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
180extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
181extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
182extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
183#endif
184
185/* On Windows, we normally run with output mode of TEXT so that \n characters
186** are automatically translated into \r\n. However, this behavior needs
187** to be disabled in some cases (ex: when generating CSV output and when
188** rendering quoted strings that contain \n characters). The following
189** routines take care of that.
190*/
191#if defined(_WIN32) || defined(WIN32)
192static void setBinaryMode(FILE *file, int isOutput){
193 if( isOutput ) fflush(file);
194 _setmode(_fileno(file), _O_BINARY);
195}
196static void setTextMode(FILE *file, int isOutput){
197 if( isOutput ) fflush(file);
198 _setmode(_fileno(file), _O_TEXT);
199}
200#else
201# define setBinaryMode(X,Y)
202# define setTextMode(X,Y)
203#endif
204
205
206/* True if the timer is enabled */
207static int enableTimer = 0;
208
209/* Return the current wall-clock time */
210static sqlite3_int64 timeOfDay(void){
211 static sqlite3_vfs *clockVfs = 0;
212 sqlite3_int64 t;
213 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
214 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
215 clockVfs->xCurrentTimeInt64(clockVfs, &t);
216 }else{
217 double r;
218 clockVfs->xCurrentTime(clockVfs, &r);
219 t = (sqlite3_int64)(r*86400000.0);
220 }
221 return t;
222}
223
224#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
225#include <sys/time.h>
226#include <sys/resource.h>
227
228/* VxWorks does not support getrusage() as far as we can determine */
229#if defined(_WRS_KERNEL) || defined(__RTP__)
230struct rusage {
231 struct timeval ru_utime; /* user CPU time used */
232 struct timeval ru_stime; /* system CPU time used */
233};
234#define getrusage(A,B) memset(B,0,sizeof(*B))
235#endif
236
237/* Saved resource information for the beginning of an operation */
238static struct rusage sBegin; /* CPU time at start */
239static sqlite3_int64 iBegin; /* Wall-clock time at start */
240
241/*
242** Begin timing an operation
243*/
244static void beginTimer(void){
245 if( enableTimer ){
246 getrusage(RUSAGE_SELF, &sBegin);
247 iBegin = timeOfDay();
248 }
249}
250
251/* Return the difference of two time_structs in seconds */
252static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
253 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
254 (double)(pEnd->tv_sec - pStart->tv_sec);
255}
256
257/*
258** Print the timing results.
259*/
260static void endTimer(void){
261 if( enableTimer ){
262 sqlite3_int64 iEnd = timeOfDay();
263 struct rusage sEnd;
264 getrusage(RUSAGE_SELF, &sEnd);
265 printf("Run Time: real %.3f user %f sys %f\n",
266 (iEnd - iBegin)*0.001,
267 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
268 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
269 }
270}
271
272#define BEGIN_TIMER beginTimer()
273#define END_TIMER endTimer()
274#define HAS_TIMER 1
275
276#elif (defined(_WIN32) || defined(WIN32))
277
278/* Saved resource information for the beginning of an operation */
279static HANDLE hProcess;
280static FILETIME ftKernelBegin;
281static FILETIME ftUserBegin;
282static sqlite3_int64 ftWallBegin;
283typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
284 LPFILETIME, LPFILETIME);
285static GETPROCTIMES getProcessTimesAddr = NULL;
286
287/*
288** Check to see if we have timer support. Return 1 if necessary
289** support found (or found previously).
290*/
291static int hasTimer(void){
292 if( getProcessTimesAddr ){
293 return 1;
294 } else {
295 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
296 ** versions. See if the version we are running on has it, and if it
297 ** does, save off a pointer to it and the current process handle.
298 */
299 hProcess = GetCurrentProcess();
300 if( hProcess ){
301 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
302 if( NULL != hinstLib ){
303 getProcessTimesAddr =
304 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
305 if( NULL != getProcessTimesAddr ){
306 return 1;
307 }
308 FreeLibrary(hinstLib);
309 }
310 }
311 }
312 return 0;
313}
314
315/*
316** Begin timing an operation
317*/
318static void beginTimer(void){
319 if( enableTimer && getProcessTimesAddr ){
320 FILETIME ftCreation, ftExit;
321 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
322 &ftKernelBegin,&ftUserBegin);
323 ftWallBegin = timeOfDay();
324 }
325}
326
327/* Return the difference of two FILETIME structs in seconds */
328static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
329 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
330 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
331 return (double) ((i64End - i64Start) / 10000000.0);
332}
333
334/*
335** Print the timing results.
336*/
337static void endTimer(void){
338 if( enableTimer && getProcessTimesAddr){
339 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
340 sqlite3_int64 ftWallEnd = timeOfDay();
341 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
342 printf("Run Time: real %.3f user %f sys %f\n",
343 (ftWallEnd - ftWallBegin)*0.001,
344 timeDiff(&ftUserBegin, &ftUserEnd),
345 timeDiff(&ftKernelBegin, &ftKernelEnd));
346 }
347}
348
349#define BEGIN_TIMER beginTimer()
350#define END_TIMER endTimer()
351#define HAS_TIMER hasTimer()
352
353#else
354#define BEGIN_TIMER
355#define END_TIMER
356#define HAS_TIMER 0
357#endif
358
359/*
360** Used to prevent warnings about unused parameters
361*/
362#define UNUSED_PARAMETER(x) (void)(x)
363
364/*
drh5af06982018-01-10 00:53:55 +0000365** Number of elements in an array
366*/
367#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
368
369/*
drh2ce15c32017-07-11 13:34:40 +0000370** If the following flag is set, then command execution stops
371** at an error if we are not interactive.
372*/
373static int bail_on_error = 0;
374
375/*
376** Threat stdin as an interactive input if the following variable
377** is true. Otherwise, assume stdin is connected to a file or pipe.
378*/
379static int stdin_is_interactive = 1;
380
381/*
382** On Windows systems we have to know if standard output is a console
383** in order to translate UTF-8 into MBCS. The following variable is
384** true if translation is required.
385*/
386static int stdout_is_console = 1;
387
388/*
389** The following is the open SQLite database. We make a pointer
390** to this database a static variable so that it can be accessed
391** by the SIGINT handler to interrupt database processing.
392*/
393static sqlite3 *globalDb = 0;
394
395/*
396** True if an interrupt (Control-C) has been received.
397*/
398static volatile int seenInterrupt = 0;
399
400/*
401** This is the name of our program. It is set in main(), used
402** in a number of other places, mostly for error messages.
403*/
404static char *Argv0;
405
406/*
407** Prompt strings. Initialized in main. Settable with
408** .prompt main continue
409*/
410static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
411static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
412
413/*
414** Render output like fprintf(). Except, if the output is going to the
415** console and if this is running on a Windows machine, translate the
416** output from UTF-8 into MBCS.
417*/
418#if defined(_WIN32) || defined(WIN32)
419void utf8_printf(FILE *out, const char *zFormat, ...){
420 va_list ap;
421 va_start(ap, zFormat);
422 if( stdout_is_console && (out==stdout || out==stderr) ){
423 char *z1 = sqlite3_vmprintf(zFormat, ap);
424 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
425 sqlite3_free(z1);
426 fputs(z2, out);
427 sqlite3_free(z2);
428 }else{
429 vfprintf(out, zFormat, ap);
430 }
431 va_end(ap);
432}
433#elif !defined(utf8_printf)
434# define utf8_printf fprintf
435#endif
436
437/*
438** Render output like fprintf(). This should not be used on anything that
439** includes string formatting (e.g. "%s").
440*/
441#if !defined(raw_printf)
442# define raw_printf fprintf
443#endif
444
drh4b5345c2018-04-24 13:07:40 +0000445/* Indicate out-of-memory and exit. */
446static void shell_out_of_memory(void){
447 raw_printf(stderr,"Error: out of memory\n");
448 exit(1);
449}
450
drh2ce15c32017-07-11 13:34:40 +0000451/*
452** Write I/O traces to the following stream.
453*/
454#ifdef SQLITE_ENABLE_IOTRACE
455static FILE *iotrace = 0;
456#endif
457
458/*
459** This routine works like printf in that its first argument is a
460** format string and subsequent arguments are values to be substituted
461** in place of % fields. The result of formatting this string
462** is written to iotrace.
463*/
464#ifdef SQLITE_ENABLE_IOTRACE
465static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
466 va_list ap;
467 char *z;
468 if( iotrace==0 ) return;
469 va_start(ap, zFormat);
470 z = sqlite3_vmprintf(zFormat, ap);
471 va_end(ap);
472 utf8_printf(iotrace, "%s", z);
473 sqlite3_free(z);
474}
475#endif
476
477/*
478** Output string zUtf to stream pOut as w characters. If w is negative,
479** then right-justify the text. W is the width in UTF-8 characters, not
480** in bytes. This is different from the %*.*s specification in printf
481** since with %*.*s the width is measured in bytes, not characters.
482*/
483static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
484 int i;
485 int n;
486 int aw = w<0 ? -w : w;
487 char zBuf[1000];
488 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
489 for(i=n=0; zUtf[i]; i++){
490 if( (zUtf[i]&0xc0)!=0x80 ){
491 n++;
492 if( n==aw ){
493 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
494 break;
495 }
496 }
497 }
498 if( n>=aw ){
499 utf8_printf(pOut, "%.*s", i, zUtf);
500 }else if( w<0 ){
501 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
502 }else{
503 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
504 }
505}
506
507
508/*
509** Determines if a string is a number of not.
510*/
511static int isNumber(const char *z, int *realnum){
512 if( *z=='-' || *z=='+' ) z++;
513 if( !IsDigit(*z) ){
514 return 0;
515 }
516 z++;
517 if( realnum ) *realnum = 0;
518 while( IsDigit(*z) ){ z++; }
519 if( *z=='.' ){
520 z++;
521 if( !IsDigit(*z) ) return 0;
522 while( IsDigit(*z) ){ z++; }
523 if( realnum ) *realnum = 1;
524 }
525 if( *z=='e' || *z=='E' ){
526 z++;
527 if( *z=='+' || *z=='-' ) z++;
528 if( !IsDigit(*z) ) return 0;
529 while( IsDigit(*z) ){ z++; }
530 if( realnum ) *realnum = 1;
531 }
532 return *z==0;
533}
534
535/*
536** Compute a string length that is limited to what can be stored in
537** lower 30 bits of a 32-bit signed integer.
538*/
539static int strlen30(const char *z){
540 const char *z2 = z;
541 while( *z2 ){ z2++; }
542 return 0x3fffffff & (int)(z2 - z);
543}
544
545/*
546** Return the length of a string in characters. Multibyte UTF8 characters
547** count as a single character.
548*/
549static int strlenChar(const char *z){
550 int n = 0;
551 while( *z ){
552 if( (0xc0&*(z++))!=0x80 ) n++;
553 }
554 return n;
555}
556
557/*
558** This routine reads a line of text from FILE in, stores
559** the text in memory obtained from malloc() and returns a pointer
560** to the text. NULL is returned at end of file, or if malloc()
561** fails.
562**
563** If zLine is not NULL then it is a malloced buffer returned from
564** a previous call to this routine that may be reused.
565*/
566static char *local_getline(char *zLine, FILE *in){
567 int nLine = zLine==0 ? 0 : 100;
568 int n = 0;
569
570 while( 1 ){
571 if( n+100>nLine ){
572 nLine = nLine*2 + 100;
573 zLine = realloc(zLine, nLine);
drh884406b2018-07-29 18:56:35 +0000574 if( zLine==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000575 }
576 if( fgets(&zLine[n], nLine - n, in)==0 ){
577 if( n==0 ){
578 free(zLine);
579 return 0;
580 }
581 zLine[n] = 0;
582 break;
583 }
584 while( zLine[n] ) n++;
585 if( n>0 && zLine[n-1]=='\n' ){
586 n--;
587 if( n>0 && zLine[n-1]=='\r' ) n--;
588 zLine[n] = 0;
589 break;
590 }
591 }
592#if defined(_WIN32) || defined(WIN32)
593 /* For interactive input on Windows systems, translate the
594 ** multi-byte characterset characters into UTF-8. */
595 if( stdin_is_interactive && in==stdin ){
596 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
597 if( zTrans ){
598 int nTrans = strlen30(zTrans)+1;
599 if( nTrans>nLine ){
600 zLine = realloc(zLine, nTrans);
drh884406b2018-07-29 18:56:35 +0000601 if( zLine==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000602 }
603 memcpy(zLine, zTrans, nTrans);
604 sqlite3_free(zTrans);
605 }
606 }
607#endif /* defined(_WIN32) || defined(WIN32) */
608 return zLine;
609}
610
611/*
612** Retrieve a single line of input text.
613**
614** If in==0 then read from standard input and prompt before each line.
615** If isContinuation is true, then a continuation prompt is appropriate.
616** If isContinuation is zero, then the main prompt should be used.
617**
618** If zPrior is not NULL then it is a buffer from a prior call to this
619** routine that can be reused.
620**
621** The result is stored in space obtained from malloc() and must either
622** be freed by the caller or else passed back into this routine via the
623** zPrior argument for reuse.
624*/
625static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
626 char *zPrompt;
627 char *zResult;
628 if( in!=0 ){
629 zResult = local_getline(zPrior, in);
630 }else{
631 zPrompt = isContinuation ? continuePrompt : mainPrompt;
632#if SHELL_USE_LOCAL_GETLINE
633 printf("%s", zPrompt);
634 fflush(stdout);
635 zResult = local_getline(zPrior, stdin);
636#else
637 free(zPrior);
638 zResult = shell_readline(zPrompt);
639 if( zResult && *zResult ) shell_add_history(zResult);
640#endif
641 }
642 return zResult;
643}
drh5af06982018-01-10 00:53:55 +0000644
645
646/*
647** Return the value of a hexadecimal digit. Return -1 if the input
648** is not a hex digit.
649*/
650static int hexDigitValue(char c){
651 if( c>='0' && c<='9' ) return c - '0';
652 if( c>='a' && c<='f' ) return c - 'a' + 10;
653 if( c>='A' && c<='F' ) return c - 'A' + 10;
654 return -1;
655}
656
657/*
658** Interpret zArg as an integer value, possibly with suffixes.
659*/
660static sqlite3_int64 integerValue(const char *zArg){
661 sqlite3_int64 v = 0;
662 static const struct { char *zSuffix; int iMult; } aMult[] = {
663 { "KiB", 1024 },
664 { "MiB", 1024*1024 },
665 { "GiB", 1024*1024*1024 },
666 { "KB", 1000 },
667 { "MB", 1000000 },
668 { "GB", 1000000000 },
669 { "K", 1000 },
670 { "M", 1000000 },
671 { "G", 1000000000 },
672 };
673 int i;
674 int isNeg = 0;
675 if( zArg[0]=='-' ){
676 isNeg = 1;
677 zArg++;
678 }else if( zArg[0]=='+' ){
679 zArg++;
680 }
681 if( zArg[0]=='0' && zArg[1]=='x' ){
682 int x;
683 zArg += 2;
684 while( (x = hexDigitValue(zArg[0]))>=0 ){
685 v = (v<<4) + x;
686 zArg++;
687 }
688 }else{
689 while( IsDigit(zArg[0]) ){
690 v = v*10 + zArg[0] - '0';
691 zArg++;
692 }
693 }
694 for(i=0; i<ArraySize(aMult); i++){
695 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
696 v *= aMult[i].iMult;
697 break;
698 }
699 }
700 return isNeg? -v : v;
701}
702
drh2ce15c32017-07-11 13:34:40 +0000703/*
704** A variable length string to which one can append text.
705*/
706typedef struct ShellText ShellText;
707struct ShellText {
708 char *z;
709 int n;
710 int nAlloc;
711};
712
713/*
714** Initialize and destroy a ShellText object
715*/
716static void initText(ShellText *p){
717 memset(p, 0, sizeof(*p));
718}
719static void freeText(ShellText *p){
720 free(p->z);
721 initText(p);
722}
723
724/* zIn is either a pointer to a NULL-terminated string in memory obtained
725** from malloc(), or a NULL pointer. The string pointed to by zAppend is
726** added to zIn, and the result returned in memory obtained from malloc().
727** zIn, if it was not NULL, is freed.
728**
729** If the third argument, quote, is not '\0', then it is used as a
730** quote character for zAppend.
731*/
732static void appendText(ShellText *p, char const *zAppend, char quote){
733 int len;
734 int i;
735 int nAppend = strlen30(zAppend);
736
737 len = nAppend+p->n+1;
738 if( quote ){
739 len += 2;
740 for(i=0; i<nAppend; i++){
741 if( zAppend[i]==quote ) len++;
742 }
743 }
744
745 if( p->n+len>=p->nAlloc ){
746 p->nAlloc = p->nAlloc*2 + len + 20;
747 p->z = realloc(p->z, p->nAlloc);
drh884406b2018-07-29 18:56:35 +0000748 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +0000749 }
750
751 if( quote ){
752 char *zCsr = p->z+p->n;
753 *zCsr++ = quote;
754 for(i=0; i<nAppend; i++){
755 *zCsr++ = zAppend[i];
756 if( zAppend[i]==quote ) *zCsr++ = quote;
757 }
758 *zCsr++ = quote;
759 p->n = (int)(zCsr - p->z);
760 *zCsr = '\0';
761 }else{
762 memcpy(p->z+p->n, zAppend, nAppend);
763 p->n += nAppend;
764 p->z[p->n] = '\0';
765 }
766}
767
768/*
769** Attempt to determine if identifier zName needs to be quoted, either
770** because it contains non-alphanumeric characters, or because it is an
771** SQLite keyword. Be conservative in this estimate: When in doubt assume
772** that quoting is required.
773**
774** Return '"' if quoting is required. Return 0 if no quoting is required.
775*/
776static char quoteChar(const char *zName){
drhfc0ec3e2018-04-25 19:02:48 +0000777 int i;
drh2ce15c32017-07-11 13:34:40 +0000778 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
779 for(i=0; zName[i]; i++){
780 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
781 }
drhfc0ec3e2018-04-25 19:02:48 +0000782 return sqlite3_keyword_check(zName, i) ? '"' : 0;
drh2ce15c32017-07-11 13:34:40 +0000783}
784
785/*
drh667a2a22018-01-02 00:04:37 +0000786** Construct a fake object name and column list to describe the structure
787** of the view, virtual table, or table valued function zSchema.zName.
drhceba7922018-01-01 21:28:25 +0000788*/
drh667a2a22018-01-02 00:04:37 +0000789static char *shellFakeSchema(
drhceba7922018-01-01 21:28:25 +0000790 sqlite3 *db, /* The database connection containing the vtab */
791 const char *zSchema, /* Schema of the database holding the vtab */
792 const char *zName /* The name of the virtual table */
793){
794 sqlite3_stmt *pStmt = 0;
795 char *zSql;
drh1d315cf2018-01-01 21:49:43 +0000796 ShellText s;
797 char cQuote;
798 char *zDiv = "(";
drh667a2a22018-01-02 00:04:37 +0000799 int nRow = 0;
drhceba7922018-01-01 21:28:25 +0000800
drh1d315cf2018-01-01 21:49:43 +0000801 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
802 zSchema ? zSchema : "main", zName);
drhceba7922018-01-01 21:28:25 +0000803 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
804 sqlite3_free(zSql);
drh1d315cf2018-01-01 21:49:43 +0000805 initText(&s);
806 if( zSchema ){
807 cQuote = quoteChar(zSchema);
808 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
809 appendText(&s, zSchema, cQuote);
810 appendText(&s, ".", 0);
drhceba7922018-01-01 21:28:25 +0000811 }
drh1d315cf2018-01-01 21:49:43 +0000812 cQuote = quoteChar(zName);
813 appendText(&s, zName, cQuote);
814 while( sqlite3_step(pStmt)==SQLITE_ROW ){
815 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
drh667a2a22018-01-02 00:04:37 +0000816 nRow++;
drh1d315cf2018-01-01 21:49:43 +0000817 appendText(&s, zDiv, 0);
818 zDiv = ",";
819 cQuote = quoteChar(zCol);
820 appendText(&s, zCol, cQuote);
821 }
822 appendText(&s, ")", 0);
drhceba7922018-01-01 21:28:25 +0000823 sqlite3_finalize(pStmt);
drh667a2a22018-01-02 00:04:37 +0000824 if( nRow==0 ){
825 freeText(&s);
826 s.z = 0;
827 }
drh1d315cf2018-01-01 21:49:43 +0000828 return s.z;
drhceba7922018-01-01 21:28:25 +0000829}
830
831/*
drh667a2a22018-01-02 00:04:37 +0000832** SQL function: shell_module_schema(X)
833**
834** Return a fake schema for the table-valued function or eponymous virtual
835** table X.
836*/
837static void shellModuleSchema(
838 sqlite3_context *pCtx,
839 int nVal,
840 sqlite3_value **apVal
841){
842 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
843 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
drhb9685182018-01-17 13:15:23 +0000844 UNUSED_PARAMETER(nVal);
drh667a2a22018-01-02 00:04:37 +0000845 if( zFake ){
dandcfbff92018-01-08 17:05:32 +0000846 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
drh667a2a22018-01-02 00:04:37 +0000847 -1, sqlite3_free);
dandcfbff92018-01-08 17:05:32 +0000848 free(zFake);
drh667a2a22018-01-02 00:04:37 +0000849 }
850}
851
852/*
drh2ce15c32017-07-11 13:34:40 +0000853** SQL function: shell_add_schema(S,X)
854**
855** Add the schema name X to the CREATE statement in S and return the result.
856** Examples:
857**
858** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
859**
860** Also works on
861**
862** CREATE INDEX
863** CREATE UNIQUE INDEX
864** CREATE VIEW
865** CREATE TRIGGER
866** CREATE VIRTUAL TABLE
867**
868** This UDF is used by the .schema command to insert the schema name of
869** attached databases into the middle of the sqlite_master.sql field.
870*/
871static void shellAddSchemaName(
872 sqlite3_context *pCtx,
873 int nVal,
874 sqlite3_value **apVal
875){
876 static const char *aPrefix[] = {
877 "TABLE",
878 "INDEX",
879 "UNIQUE INDEX",
880 "VIEW",
881 "TRIGGER",
882 "VIRTUAL TABLE"
883 };
884 int i = 0;
885 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
886 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
drh667a2a22018-01-02 00:04:37 +0000887 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
drhceba7922018-01-01 21:28:25 +0000888 sqlite3 *db = sqlite3_context_db_handle(pCtx);
drhb9685182018-01-17 13:15:23 +0000889 UNUSED_PARAMETER(nVal);
drh2ce15c32017-07-11 13:34:40 +0000890 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
drh89997982017-07-11 18:11:33 +0000891 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
drh2ce15c32017-07-11 13:34:40 +0000892 int n = strlen30(aPrefix[i]);
893 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
drhceba7922018-01-01 21:28:25 +0000894 char *z = 0;
drh667a2a22018-01-02 00:04:37 +0000895 char *zFake = 0;
drhceba7922018-01-01 21:28:25 +0000896 if( zSchema ){
897 char cQuote = quoteChar(zSchema);
898 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
899 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
900 }else{
901 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
902 }
drh2ce15c32017-07-11 13:34:40 +0000903 }
drh667a2a22018-01-02 00:04:37 +0000904 if( zName
905 && aPrefix[i][0]=='V'
906 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
907 ){
908 if( z==0 ){
dandcfbff92018-01-08 17:05:32 +0000909 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
drh667a2a22018-01-02 00:04:37 +0000910 }else{
dandcfbff92018-01-08 17:05:32 +0000911 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
drh667a2a22018-01-02 00:04:37 +0000912 }
dandcfbff92018-01-08 17:05:32 +0000913 free(zFake);
drhceba7922018-01-01 21:28:25 +0000914 }
915 if( z ){
916 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
917 return;
918 }
drh2ce15c32017-07-11 13:34:40 +0000919 }
920 }
921 }
922 sqlite3_result_value(pCtx, apVal[0]);
923}
924
925/*
926** The source code for several run-time loadable extensions is inserted
927** below by the ../tool/mkshellc.tcl script. Before processing that included
928** code, we need to override some macros to make the included program code
929** work here in the middle of this regular program.
930*/
931#define SQLITE_EXTENSION_INIT1
drh89997982017-07-11 18:11:33 +0000932#define SQLITE_EXTENSION_INIT2(X) (void)(X)
drh2ce15c32017-07-11 13:34:40 +0000933
mistachkinacae8c32018-01-05 20:08:46 +0000934#if defined(_WIN32) && defined(_MSC_VER)
drh03491a12018-01-07 21:58:17 +0000935INCLUDE test_windirent.h
mistachkindfdfd8c2018-01-04 22:46:08 +0000936INCLUDE test_windirent.c
937#define dirent DIRENT
mistachkindfdfd8c2018-01-04 22:46:08 +0000938#endif
drh2ce15c32017-07-11 13:34:40 +0000939INCLUDE ../ext/misc/shathree.c
940INCLUDE ../ext/misc/fileio.c
drh56eb09b2017-07-11 13:59:07 +0000941INCLUDE ../ext/misc/completion.c
drh8682e122018-01-07 20:38:10 +0000942INCLUDE ../ext/misc/appendvfs.c
drh50b910a2019-01-21 14:55:03 +0000943INCLUDE ../ext/misc/memtrace.c
dan72afc3c2017-12-05 18:32:40 +0000944#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +0000945INCLUDE ../ext/misc/zipfile.c
dand1b51d42017-12-16 19:11:26 +0000946INCLUDE ../ext/misc/sqlar.c
dan72afc3c2017-12-05 18:32:40 +0000947#endif
dan43efc182017-12-19 17:42:13 +0000948INCLUDE ../ext/expert/sqlite3expert.h
949INCLUDE ../ext/expert/sqlite3expert.c
drh2ce15c32017-07-11 13:34:40 +0000950
dan68cb86e2019-04-20 20:57:28 +0000951INCLUDE ../ext/misc/dbdata.c
952
drh2ce15c32017-07-11 13:34:40 +0000953#if defined(SQLITE_ENABLE_SESSION)
954/*
955** State information for a single open session
956*/
957typedef struct OpenSession OpenSession;
958struct OpenSession {
959 char *zName; /* Symbolic name for this session */
960 int nFilter; /* Number of xFilter rejection GLOB patterns */
961 char **azFilter; /* Array of xFilter rejection GLOB patterns */
962 sqlite3_session *p; /* The open session */
963};
964#endif
965
966/*
967** Shell output mode information from before ".explain on",
968** saved so that it can be restored by ".explain off"
969*/
970typedef struct SavedModeInfo SavedModeInfo;
971struct SavedModeInfo {
972 int valid; /* Is there legit data in here? */
973 int mode; /* Mode prior to ".explain on" */
974 int showHeader; /* The ".header" setting prior to ".explain on" */
975 int colWidth[100]; /* Column widths prior to ".explain on" */
976};
977
dan43efc182017-12-19 17:42:13 +0000978typedef struct ExpertInfo ExpertInfo;
979struct ExpertInfo {
980 sqlite3expert *pExpert;
981 int bVerbose;
982};
983
drh4b5345c2018-04-24 13:07:40 +0000984/* A single line in the EQP output */
985typedef struct EQPGraphRow EQPGraphRow;
986struct EQPGraphRow {
drhe2ca99c2018-05-02 00:33:43 +0000987 int iEqpId; /* ID for this row */
988 int iParentId; /* ID of the parent row */
drh4b5345c2018-04-24 13:07:40 +0000989 EQPGraphRow *pNext; /* Next row in sequence */
990 char zText[1]; /* Text to display for this row */
991};
992
993/* All EQP output is collected into an instance of the following */
994typedef struct EQPGraph EQPGraph;
995struct EQPGraph {
996 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
997 EQPGraphRow *pLast; /* Last element of the pRow list */
998 char zPrefix[100]; /* Graph prefix */
999};
1000
drh2ce15c32017-07-11 13:34:40 +00001001/*
1002** State information about the database connection is contained in an
1003** instance of the following structure.
1004*/
1005typedef struct ShellState ShellState;
1006struct ShellState {
1007 sqlite3 *db; /* The database */
drh1fa6d9f2018-01-06 21:46:01 +00001008 u8 autoExplain; /* Automatically turn on .explain mode */
1009 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
drhe2ca99c2018-05-02 00:33:43 +00001010 u8 autoEQPtest; /* autoEQP is in test mode */
drhb4e50392019-01-26 15:40:04 +00001011 u8 autoEQPtrace; /* autoEQP is in trace mode */
drh1fa6d9f2018-01-06 21:46:01 +00001012 u8 statsOn; /* True to display memory stats before each finalize */
1013 u8 scanstatsOn; /* True to display scan stats before each finalize */
1014 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
drh13c20932018-01-10 21:41:55 +00001015 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
drh4b5345c2018-04-24 13:07:40 +00001016 u8 nEqpLevel; /* Depth of the EQP output graph */
drh707821f2018-12-05 13:39:06 +00001017 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */
drh4b5345c2018-04-24 13:07:40 +00001018 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
drh2ce15c32017-07-11 13:34:40 +00001019 int outCount; /* Revert to stdout when reaching zero */
1020 int cnt; /* Number of records displayed so far */
drh2c8ee022018-12-13 18:59:30 +00001021 int lineno; /* Line number of last line read from in */
drh60379d42018-12-13 18:30:01 +00001022 FILE *in; /* Read commands from this stream */
drh2ce15c32017-07-11 13:34:40 +00001023 FILE *out; /* Write results here */
1024 FILE *traceOut; /* Output for sqlite3_trace() */
1025 int nErr; /* Number of errors seen */
1026 int mode; /* An output mode setting */
drh3c484e82018-01-10 22:27:21 +00001027 int modePrior; /* Saved mode */
drh2ce15c32017-07-11 13:34:40 +00001028 int cMode; /* temporary output mode for the current query */
1029 int normalMode; /* Output mode before ".explain on" */
1030 int writableSchema; /* True if PRAGMA writable_schema=ON */
1031 int showHeader; /* True to show column names in List or Column mode */
1032 int nCheck; /* Number of ".check" commands run */
drh3f83f592019-02-04 14:53:18 +00001033 unsigned nProgress; /* Number of progress callbacks encountered */
1034 unsigned mxProgress; /* Maximum progress callbacks before failing */
1035 unsigned flgProgress; /* Flags for the progress callback */
drh2ce15c32017-07-11 13:34:40 +00001036 unsigned shellFlgs; /* Various flags */
drh6ca64482019-01-22 16:06:20 +00001037 sqlite3_int64 szMax; /* --maxsize argument to .open */
drh2ce15c32017-07-11 13:34:40 +00001038 char *zDestTable; /* Name of destination table when MODE_Insert */
drh13c20932018-01-10 21:41:55 +00001039 char *zTempFile; /* Temporary file that might need deleting */
drh2ce15c32017-07-11 13:34:40 +00001040 char zTestcase[30]; /* Name of current test case */
1041 char colSeparator[20]; /* Column separator character for several modes */
1042 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drh3c484e82018-01-10 22:27:21 +00001043 char colSepPrior[20]; /* Saved column separator */
1044 char rowSepPrior[20]; /* Saved row separator */
drh2ce15c32017-07-11 13:34:40 +00001045 int colWidth[100]; /* Requested width of each column when in column mode*/
1046 int actualWidth[100]; /* Actual width of each column */
1047 char nullValue[20]; /* The text to print when a NULL comes back from
1048 ** the database */
1049 char outfile[FILENAME_MAX]; /* Filename for *out */
1050 const char *zDbFilename; /* name of the database file */
1051 char *zFreeOnClose; /* Filename to free when closing */
1052 const char *zVfs; /* Name of VFS to use */
1053 sqlite3_stmt *pStmt; /* Current statement if any. */
1054 FILE *pLog; /* Write log output here */
1055 int *aiIndent; /* Array of indents used in MODE_Explain */
1056 int nIndent; /* Size of array aiIndent[] */
1057 int iIndent; /* Index of current op in aiIndent[] */
drh4b5345c2018-04-24 13:07:40 +00001058 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
drh2ce15c32017-07-11 13:34:40 +00001059#if defined(SQLITE_ENABLE_SESSION)
1060 int nSession; /* Number of active sessions */
1061 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1062#endif
dan43efc182017-12-19 17:42:13 +00001063 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
drh2ce15c32017-07-11 13:34:40 +00001064};
1065
drh1fa6d9f2018-01-06 21:46:01 +00001066
drhada70452017-12-21 21:02:27 +00001067/* Allowed values for ShellState.autoEQP
1068*/
drhe2ca99c2018-05-02 00:33:43 +00001069#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1070#define AUTOEQP_on 1 /* Automatic EQP is on */
1071#define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1072#define AUTOEQP_full 3 /* Show full EXPLAIN */
drhada70452017-12-21 21:02:27 +00001073
drh1fa6d9f2018-01-06 21:46:01 +00001074/* Allowed values for ShellState.openMode
1075*/
drh60f34ae2018-10-30 13:19:49 +00001076#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1077#define SHELL_OPEN_NORMAL 1 /* Normal database file */
1078#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1079#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1080#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1081#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
drh33746482018-12-13 15:06:26 +00001082#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */
drh1fa6d9f2018-01-06 21:46:01 +00001083
drh707821f2018-12-05 13:39:06 +00001084/* Allowed values for ShellState.eTraceType
1085*/
1086#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */
1087#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */
1088#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */
1089
drh3f83f592019-02-04 14:53:18 +00001090/* Bits in the ShellState.flgProgress variable */
drhfc4eeef2019-02-05 19:48:46 +00001091#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */
1092#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres
1093 ** callback limit is reached, and for each
1094 ** top-level SQL statement */
1095#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */
drh3f83f592019-02-04 14:53:18 +00001096
drh2ce15c32017-07-11 13:34:40 +00001097/*
1098** These are the allowed shellFlgs values
1099*/
drhb2a0f752017-08-28 15:51:35 +00001100#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1101#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1102#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1103#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1104#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1105#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1106#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
drh2ce15c32017-07-11 13:34:40 +00001107
1108/*
1109** Macros for testing and setting shellFlgs
1110*/
1111#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1112#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1113#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1114
1115/*
1116** These are the allowed modes.
1117*/
1118#define MODE_Line 0 /* One column per line. Blank line between records */
1119#define MODE_Column 1 /* One record per line in neat columns */
1120#define MODE_List 2 /* One record per line with a separator */
1121#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1122#define MODE_Html 4 /* Generate an XHTML table */
1123#define MODE_Insert 5 /* Generate SQL "insert" statements */
1124#define MODE_Quote 6 /* Quote values as for SQL */
1125#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1126#define MODE_Csv 8 /* Quote strings, numbers are plain */
1127#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1128#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1129#define MODE_Pretty 11 /* Pretty-print schemas */
drh4b5345c2018-04-24 13:07:40 +00001130#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
drh2ce15c32017-07-11 13:34:40 +00001131
1132static const char *modeDescr[] = {
1133 "line",
1134 "column",
1135 "list",
1136 "semi",
1137 "html",
1138 "insert",
1139 "quote",
1140 "tcl",
1141 "csv",
1142 "explain",
1143 "ascii",
1144 "prettyprint",
drh4b5345c2018-04-24 13:07:40 +00001145 "eqp"
drh2ce15c32017-07-11 13:34:40 +00001146};
1147
1148/*
1149** These are the column/row/line separators used by the various
1150** import/export modes.
1151*/
1152#define SEP_Column "|"
1153#define SEP_Row "\n"
1154#define SEP_Tab "\t"
1155#define SEP_Space " "
1156#define SEP_Comma ","
1157#define SEP_CrLf "\r\n"
1158#define SEP_Unit "\x1F"
1159#define SEP_Record "\x1E"
1160
1161/*
drh2ce15c32017-07-11 13:34:40 +00001162** A callback for the sqlite3_log() interface.
1163*/
1164static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1165 ShellState *p = (ShellState*)pArg;
1166 if( p->pLog==0 ) return;
1167 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1168 fflush(p->pLog);
1169}
1170
1171/*
drh634c70f2018-01-10 16:50:18 +00001172** SQL function: shell_putsnl(X)
1173**
1174** Write the text X to the screen (or whatever output is being directed)
1175** adding a newline at the end, and then return X.
1176*/
1177static void shellPutsFunc(
1178 sqlite3_context *pCtx,
1179 int nVal,
1180 sqlite3_value **apVal
1181){
1182 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
drhb9685182018-01-17 13:15:23 +00001183 (void)nVal;
drh634c70f2018-01-10 16:50:18 +00001184 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
1185 sqlite3_result_value(pCtx, apVal[0]);
1186}
1187
1188/*
drh97913132018-01-11 00:04:00 +00001189** SQL function: edit(VALUE)
1190** edit(VALUE,EDITOR)
1191**
1192** These steps:
1193**
1194** (1) Write VALUE into a temporary file.
1195** (2) Run program EDITOR on that temporary file.
1196** (3) Read the temporary file back and return its content as the result.
1197** (4) Delete the temporary file
1198**
1199** If the EDITOR argument is omitted, use the value in the VISUAL
1200** environment variable. If still there is no EDITOR, through an error.
1201**
1202** Also throw an error if the EDITOR program returns a non-zero exit code.
1203*/
drh04a28c32018-01-31 01:38:44 +00001204#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00001205static void editFunc(
1206 sqlite3_context *context,
1207 int argc,
1208 sqlite3_value **argv
1209){
1210 const char *zEditor;
1211 char *zTempFile = 0;
1212 sqlite3 *db;
1213 char *zCmd = 0;
1214 int bBin;
1215 int rc;
drhf018fd52018-08-06 02:08:53 +00001216 int hasCRNL = 0;
drh97913132018-01-11 00:04:00 +00001217 FILE *f = 0;
1218 sqlite3_int64 sz;
1219 sqlite3_int64 x;
1220 unsigned char *p = 0;
1221
1222 if( argc==2 ){
1223 zEditor = (const char*)sqlite3_value_text(argv[1]);
1224 }else{
1225 zEditor = getenv("VISUAL");
1226 }
1227 if( zEditor==0 ){
1228 sqlite3_result_error(context, "no editor for edit()", -1);
1229 return;
1230 }
1231 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
1232 sqlite3_result_error(context, "NULL input to edit()", -1);
1233 return;
1234 }
1235 db = sqlite3_context_db_handle(context);
1236 zTempFile = 0;
1237 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
1238 if( zTempFile==0 ){
1239 sqlite3_uint64 r = 0;
1240 sqlite3_randomness(sizeof(r), &r);
1241 zTempFile = sqlite3_mprintf("temp%llx", r);
1242 if( zTempFile==0 ){
1243 sqlite3_result_error_nomem(context);
1244 return;
1245 }
1246 }
1247 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
drhf018fd52018-08-06 02:08:53 +00001248 /* When writing the file to be edited, do \n to \r\n conversions on systems
1249 ** that want \r\n line endings */
drh97913132018-01-11 00:04:00 +00001250 f = fopen(zTempFile, bBin ? "wb" : "w");
1251 if( f==0 ){
1252 sqlite3_result_error(context, "edit() cannot open temp file", -1);
1253 goto edit_func_end;
1254 }
1255 sz = sqlite3_value_bytes(argv[0]);
1256 if( bBin ){
1257 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
1258 }else{
drhf018fd52018-08-06 02:08:53 +00001259 const char *z = (const char*)sqlite3_value_text(argv[0]);
1260 /* Remember whether or not the value originally contained \r\n */
1261 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
drh97913132018-01-11 00:04:00 +00001262 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
1263 }
1264 fclose(f);
1265 f = 0;
1266 if( x!=sz ){
1267 sqlite3_result_error(context, "edit() could not write the whole file", -1);
1268 goto edit_func_end;
1269 }
1270 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
1271 if( zCmd==0 ){
1272 sqlite3_result_error_nomem(context);
1273 goto edit_func_end;
1274 }
1275 rc = system(zCmd);
1276 sqlite3_free(zCmd);
1277 if( rc ){
1278 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
1279 goto edit_func_end;
1280 }
drhf018fd52018-08-06 02:08:53 +00001281 f = fopen(zTempFile, "rb");
drh97913132018-01-11 00:04:00 +00001282 if( f==0 ){
1283 sqlite3_result_error(context,
1284 "edit() cannot reopen temp file after edit", -1);
1285 goto edit_func_end;
1286 }
1287 fseek(f, 0, SEEK_END);
1288 sz = ftell(f);
1289 rewind(f);
1290 p = sqlite3_malloc64( sz+(bBin==0) );
1291 if( p==0 ){
1292 sqlite3_result_error_nomem(context);
1293 goto edit_func_end;
1294 }
drhf018fd52018-08-06 02:08:53 +00001295 x = fread(p, 1, sz, f);
drh97913132018-01-11 00:04:00 +00001296 fclose(f);
1297 f = 0;
1298 if( x!=sz ){
1299 sqlite3_result_error(context, "could not read back the whole file", -1);
1300 goto edit_func_end;
1301 }
1302 if( bBin ){
mistachkinb71aa092018-01-23 00:05:18 +00001303 sqlite3_result_blob64(context, p, sz, sqlite3_free);
drh97913132018-01-11 00:04:00 +00001304 }else{
dan60bdcf52018-10-03 11:13:30 +00001305 sqlite3_int64 i, j;
drhf018fd52018-08-06 02:08:53 +00001306 if( hasCRNL ){
1307 /* If the original contains \r\n then do no conversions back to \n */
1308 j = sz;
1309 }else{
1310 /* If the file did not originally contain \r\n then convert any new
1311 ** \r\n back into \n */
1312 for(i=j=0; i<sz; i++){
1313 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
1314 p[j++] = p[i];
1315 }
1316 sz = j;
1317 p[sz] = 0;
1318 }
mistachkinb71aa092018-01-23 00:05:18 +00001319 sqlite3_result_text64(context, (const char*)p, sz,
1320 sqlite3_free, SQLITE_UTF8);
drh97913132018-01-11 00:04:00 +00001321 }
1322 p = 0;
1323
1324edit_func_end:
1325 if( f ) fclose(f);
1326 unlink(zTempFile);
1327 sqlite3_free(zTempFile);
1328 sqlite3_free(p);
1329}
drh04a28c32018-01-31 01:38:44 +00001330#endif /* SQLITE_NOHAVE_SYSTEM */
drh97913132018-01-11 00:04:00 +00001331
1332/*
drh3c484e82018-01-10 22:27:21 +00001333** Save or restore the current output mode
1334*/
1335static void outputModePush(ShellState *p){
1336 p->modePrior = p->mode;
1337 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
1338 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
1339}
1340static void outputModePop(ShellState *p){
1341 p->mode = p->modePrior;
1342 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
1343 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
1344}
1345
1346/*
drh2ce15c32017-07-11 13:34:40 +00001347** Output the given string as a hex-encoded blob (eg. X'1234' )
1348*/
1349static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1350 int i;
1351 char *zBlob = (char *)pBlob;
1352 raw_printf(out,"X'");
1353 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1354 raw_printf(out,"'");
1355}
1356
1357/*
1358** Find a string that is not found anywhere in z[]. Return a pointer
1359** to that string.
1360**
1361** Try to use zA and zB first. If both of those are already found in z[]
1362** then make up some string and store it in the buffer zBuf.
1363*/
1364static const char *unused_string(
1365 const char *z, /* Result must not appear anywhere in z */
1366 const char *zA, const char *zB, /* Try these first */
1367 char *zBuf /* Space to store a generated string */
1368){
1369 unsigned i = 0;
1370 if( strstr(z, zA)==0 ) return zA;
1371 if( strstr(z, zB)==0 ) return zB;
1372 do{
1373 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1374 }while( strstr(z,zBuf)!=0 );
1375 return zBuf;
1376}
1377
1378/*
1379** Output the given string as a quoted string using SQL quoting conventions.
1380**
1381** See also: output_quoted_escaped_string()
1382*/
1383static void output_quoted_string(FILE *out, const char *z){
1384 int i;
1385 char c;
1386 setBinaryMode(out, 1);
1387 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1388 if( c==0 ){
1389 utf8_printf(out,"'%s'",z);
1390 }else{
1391 raw_printf(out, "'");
1392 while( *z ){
1393 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1394 if( c=='\'' ) i++;
1395 if( i ){
1396 utf8_printf(out, "%.*s", i, z);
1397 z += i;
1398 }
1399 if( c=='\'' ){
1400 raw_printf(out, "'");
1401 continue;
1402 }
1403 if( c==0 ){
1404 break;
1405 }
1406 z++;
1407 }
1408 raw_printf(out, "'");
1409 }
1410 setTextMode(out, 1);
1411}
1412
1413/*
1414** Output the given string as a quoted string using SQL quoting conventions.
1415** Additionallly , escape the "\n" and "\r" characters so that they do not
1416** get corrupted by end-of-line translation facilities in some operating
1417** systems.
1418**
1419** This is like output_quoted_string() but with the addition of the \r\n
1420** escape mechanism.
1421*/
1422static void output_quoted_escaped_string(FILE *out, const char *z){
1423 int i;
1424 char c;
1425 setBinaryMode(out, 1);
1426 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1427 if( c==0 ){
1428 utf8_printf(out,"'%s'",z);
1429 }else{
1430 const char *zNL = 0;
1431 const char *zCR = 0;
1432 int nNL = 0;
1433 int nCR = 0;
1434 char zBuf1[20], zBuf2[20];
1435 for(i=0; z[i]; i++){
1436 if( z[i]=='\n' ) nNL++;
1437 if( z[i]=='\r' ) nCR++;
1438 }
1439 if( nNL ){
1440 raw_printf(out, "replace(");
1441 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1442 }
1443 if( nCR ){
1444 raw_printf(out, "replace(");
1445 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1446 }
1447 raw_printf(out, "'");
1448 while( *z ){
1449 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1450 if( c=='\'' ) i++;
1451 if( i ){
1452 utf8_printf(out, "%.*s", i, z);
1453 z += i;
1454 }
1455 if( c=='\'' ){
1456 raw_printf(out, "'");
1457 continue;
1458 }
1459 if( c==0 ){
1460 break;
1461 }
1462 z++;
1463 if( c=='\n' ){
1464 raw_printf(out, "%s", zNL);
1465 continue;
1466 }
1467 raw_printf(out, "%s", zCR);
1468 }
1469 raw_printf(out, "'");
1470 if( nCR ){
1471 raw_printf(out, ",'%s',char(13))", zCR);
1472 }
1473 if( nNL ){
1474 raw_printf(out, ",'%s',char(10))", zNL);
1475 }
1476 }
1477 setTextMode(out, 1);
1478}
1479
1480/*
1481** Output the given string as a quoted according to C or TCL quoting rules.
1482*/
1483static void output_c_string(FILE *out, const char *z){
1484 unsigned int c;
1485 fputc('"', out);
1486 while( (c = *(z++))!=0 ){
1487 if( c=='\\' ){
1488 fputc(c, out);
1489 fputc(c, out);
1490 }else if( c=='"' ){
1491 fputc('\\', out);
1492 fputc('"', out);
1493 }else if( c=='\t' ){
1494 fputc('\\', out);
1495 fputc('t', out);
1496 }else if( c=='\n' ){
1497 fputc('\\', out);
1498 fputc('n', out);
1499 }else if( c=='\r' ){
1500 fputc('\\', out);
1501 fputc('r', out);
1502 }else if( !isprint(c&0xff) ){
1503 raw_printf(out, "\\%03o", c&0xff);
1504 }else{
1505 fputc(c, out);
1506 }
1507 }
1508 fputc('"', out);
1509}
1510
1511/*
1512** Output the given string with characters that are special to
1513** HTML escaped.
1514*/
1515static void output_html_string(FILE *out, const char *z){
1516 int i;
1517 if( z==0 ) z = "";
1518 while( *z ){
1519 for(i=0; z[i]
1520 && z[i]!='<'
1521 && z[i]!='&'
1522 && z[i]!='>'
1523 && z[i]!='\"'
1524 && z[i]!='\'';
1525 i++){}
1526 if( i>0 ){
1527 utf8_printf(out,"%.*s",i,z);
1528 }
1529 if( z[i]=='<' ){
1530 raw_printf(out,"&lt;");
1531 }else if( z[i]=='&' ){
1532 raw_printf(out,"&amp;");
1533 }else if( z[i]=='>' ){
1534 raw_printf(out,"&gt;");
1535 }else if( z[i]=='\"' ){
1536 raw_printf(out,"&quot;");
1537 }else if( z[i]=='\'' ){
1538 raw_printf(out,"&#39;");
1539 }else{
1540 break;
1541 }
1542 z += i + 1;
1543 }
1544}
1545
1546/*
1547** If a field contains any character identified by a 1 in the following
1548** array, then the string must be quoted for CSV.
1549*/
1550static const char needCsvQuote[] = {
1551 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1552 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1553 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1554 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1555 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1556 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1,
1559 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1560 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1561 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1562 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1563 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1564 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1565 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};
1568
1569/*
1570** Output a single term of CSV. Actually, p->colSeparator is used for
1571** the separator, which may or may not be a comma. p->nullValue is
1572** the null value. Strings are quoted if necessary. The separator
1573** is only issued if bSep is true.
1574*/
1575static void output_csv(ShellState *p, const char *z, int bSep){
1576 FILE *out = p->out;
1577 if( z==0 ){
1578 utf8_printf(out,"%s",p->nullValue);
1579 }else{
1580 int i;
1581 int nSep = strlen30(p->colSeparator);
1582 for(i=0; z[i]; i++){
1583 if( needCsvQuote[((unsigned char*)z)[i]]
1584 || (z[i]==p->colSeparator[0] &&
1585 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1586 i = 0;
1587 break;
1588 }
1589 }
1590 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001591 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1592 utf8_printf(out, "%s", zQuoted);
1593 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001594 }else{
1595 utf8_printf(out, "%s", z);
1596 }
1597 }
1598 if( bSep ){
1599 utf8_printf(p->out, "%s", p->colSeparator);
1600 }
1601}
1602
drh2ce15c32017-07-11 13:34:40 +00001603/*
1604** This routine runs when the user presses Ctrl-C
1605*/
1606static void interrupt_handler(int NotUsed){
1607 UNUSED_PARAMETER(NotUsed);
1608 seenInterrupt++;
1609 if( seenInterrupt>2 ) exit(1);
1610 if( globalDb ) sqlite3_interrupt(globalDb);
1611}
mistachkinb4bab902017-10-27 17:09:44 +00001612
1613#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1614/*
1615** This routine runs for console events (e.g. Ctrl-C) on Win32
1616*/
1617static BOOL WINAPI ConsoleCtrlHandler(
1618 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1619){
1620 if( dwCtrlType==CTRL_C_EVENT ){
1621 interrupt_handler(0);
1622 return TRUE;
1623 }
1624 return FALSE;
1625}
drh2ce15c32017-07-11 13:34:40 +00001626#endif
1627
1628#ifndef SQLITE_OMIT_AUTHORIZATION
1629/*
1630** When the ".auth ON" is set, the following authorizer callback is
1631** invoked. It always returns SQLITE_OK.
1632*/
1633static int shellAuth(
1634 void *pClientData,
1635 int op,
1636 const char *zA1,
1637 const char *zA2,
1638 const char *zA3,
1639 const char *zA4
1640){
1641 ShellState *p = (ShellState*)pClientData;
1642 static const char *azAction[] = { 0,
1643 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1644 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1645 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1646 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1647 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1648 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1649 "PRAGMA", "READ", "SELECT",
1650 "TRANSACTION", "UPDATE", "ATTACH",
1651 "DETACH", "ALTER_TABLE", "REINDEX",
1652 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1653 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1654 };
1655 int i;
1656 const char *az[4];
1657 az[0] = zA1;
1658 az[1] = zA2;
1659 az[2] = zA3;
1660 az[3] = zA4;
1661 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1662 for(i=0; i<4; i++){
1663 raw_printf(p->out, " ");
1664 if( az[i] ){
1665 output_c_string(p->out, az[i]);
1666 }else{
1667 raw_printf(p->out, "NULL");
1668 }
1669 }
1670 raw_printf(p->out, "\n");
1671 return SQLITE_OK;
1672}
1673#endif
1674
1675/*
1676** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1677**
1678** This routine converts some CREATE TABLE statements for shadow tables
1679** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1680*/
1681static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1682 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1683 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1684 }else{
1685 utf8_printf(out, "%s%s", z, zTail);
1686 }
1687}
1688static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1689 char c = z[n];
1690 z[n] = 0;
1691 printSchemaLine(out, z, zTail);
1692 z[n] = c;
1693}
1694
1695/*
drh11be81d2018-01-06 15:46:20 +00001696** Return true if string z[] has nothing but whitespace and comments to the
1697** end of the first line.
1698*/
1699static int wsToEol(const char *z){
1700 int i;
1701 for(i=0; z[i]; i++){
1702 if( z[i]=='\n' ) return 1;
1703 if( IsSpace(z[i]) ) continue;
1704 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1705 return 0;
1706 }
1707 return 1;
1708}
drh4b5345c2018-04-24 13:07:40 +00001709
1710/*
1711** Add a new entry to the EXPLAIN QUERY PLAN data
1712*/
drhe2ca99c2018-05-02 00:33:43 +00001713static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
drh4b5345c2018-04-24 13:07:40 +00001714 EQPGraphRow *pNew;
1715 int nText = strlen30(zText);
drhe2ca99c2018-05-02 00:33:43 +00001716 if( p->autoEQPtest ){
1717 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
1718 }
drh4b5345c2018-04-24 13:07:40 +00001719 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
1720 if( pNew==0 ) shell_out_of_memory();
drhe2ca99c2018-05-02 00:33:43 +00001721 pNew->iEqpId = iEqpId;
1722 pNew->iParentId = p2;
drh4b5345c2018-04-24 13:07:40 +00001723 memcpy(pNew->zText, zText, nText+1);
1724 pNew->pNext = 0;
1725 if( p->sGraph.pLast ){
1726 p->sGraph.pLast->pNext = pNew;
1727 }else{
1728 p->sGraph.pRow = pNew;
1729 }
1730 p->sGraph.pLast = pNew;
1731}
1732
1733/*
1734** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1735** in p->sGraph.
1736*/
1737static void eqp_reset(ShellState *p){
1738 EQPGraphRow *pRow, *pNext;
1739 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
1740 pNext = pRow->pNext;
1741 sqlite3_free(pRow);
1742 }
1743 memset(&p->sGraph, 0, sizeof(p->sGraph));
1744}
1745
drhe2ca99c2018-05-02 00:33:43 +00001746/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
drh4b5345c2018-04-24 13:07:40 +00001747** pOld, or return the first such line if pOld is NULL
1748*/
drhe2ca99c2018-05-02 00:33:43 +00001749static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
drh4b5345c2018-04-24 13:07:40 +00001750 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
drhe2ca99c2018-05-02 00:33:43 +00001751 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
drh4b5345c2018-04-24 13:07:40 +00001752 return pRow;
1753}
1754
drhe2ca99c2018-05-02 00:33:43 +00001755/* Render a single level of the graph that has iEqpId as its parent. Called
drh4b5345c2018-04-24 13:07:40 +00001756** recursively to render sublevels.
1757*/
drhe2ca99c2018-05-02 00:33:43 +00001758static void eqp_render_level(ShellState *p, int iEqpId){
drh4b5345c2018-04-24 13:07:40 +00001759 EQPGraphRow *pRow, *pNext;
drh4b5345c2018-04-24 13:07:40 +00001760 int n = strlen30(p->sGraph.zPrefix);
1761 char *z;
drhe2ca99c2018-05-02 00:33:43 +00001762 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
1763 pNext = eqp_next_row(p, iEqpId, pRow);
drh4b5345c2018-04-24 13:07:40 +00001764 z = pRow->zText;
1765 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
drhe2188f02018-05-07 11:37:34 +00001766 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
drh4b5345c2018-04-24 13:07:40 +00001767 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
drhe2ca99c2018-05-02 00:33:43 +00001768 eqp_render_level(p, pRow->iEqpId);
drh4b5345c2018-04-24 13:07:40 +00001769 p->sGraph.zPrefix[n] = 0;
1770 }
1771 }
1772}
1773
1774/*
1775** Display and reset the EXPLAIN QUERY PLAN data
1776*/
1777static void eqp_render(ShellState *p){
1778 EQPGraphRow *pRow = p->sGraph.pRow;
1779 if( pRow ){
1780 if( pRow->zText[0]=='-' ){
1781 if( pRow->pNext==0 ){
1782 eqp_reset(p);
1783 return;
1784 }
1785 utf8_printf(p->out, "%s\n", pRow->zText+3);
1786 p->sGraph.pRow = pRow->pNext;
1787 sqlite3_free(pRow);
1788 }else{
1789 utf8_printf(p->out, "QUERY PLAN\n");
1790 }
1791 p->sGraph.zPrefix[0] = 0;
1792 eqp_render_level(p, 0);
1793 eqp_reset(p);
1794 }
1795}
drh11be81d2018-01-06 15:46:20 +00001796
drh569b1d92019-02-05 20:51:41 +00001797#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh11be81d2018-01-06 15:46:20 +00001798/*
drh3f83f592019-02-04 14:53:18 +00001799** Progress handler callback.
1800*/
1801static int progress_handler(void *pClientData) {
1802 ShellState *p = (ShellState*)pClientData;
1803 p->nProgress++;
1804 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){
1805 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress);
drhfc4eeef2019-02-05 19:48:46 +00001806 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
1807 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0;
drh3f83f592019-02-04 14:53:18 +00001808 return 1;
1809 }
drhfc4eeef2019-02-05 19:48:46 +00001810 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){
drh3f83f592019-02-04 14:53:18 +00001811 raw_printf(p->out, "Progress %u\n", p->nProgress);
1812 }
1813 return 0;
1814}
drh569b1d92019-02-05 20:51:41 +00001815#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00001816
1817/*
drh2ce15c32017-07-11 13:34:40 +00001818** This is the callback routine that the shell
1819** invokes for each row of a query result.
1820*/
1821static int shell_callback(
1822 void *pArg,
1823 int nArg, /* Number of result columns */
1824 char **azArg, /* Text of each result column */
1825 char **azCol, /* Column names */
1826 int *aiType /* Column types */
1827){
1828 int i;
1829 ShellState *p = (ShellState*)pArg;
1830
drhb3c45232017-08-28 14:33:27 +00001831 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001832 switch( p->cMode ){
1833 case MODE_Line: {
1834 int w = 5;
1835 if( azArg==0 ) break;
1836 for(i=0; i<nArg; i++){
1837 int len = strlen30(azCol[i] ? azCol[i] : "");
1838 if( len>w ) w = len;
1839 }
1840 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1841 for(i=0; i<nArg; i++){
1842 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1843 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1844 }
1845 break;
1846 }
1847 case MODE_Explain:
1848 case MODE_Column: {
1849 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1850 const int *colWidth;
1851 int showHdr;
1852 char *rowSep;
1853 if( p->cMode==MODE_Column ){
1854 colWidth = p->colWidth;
1855 showHdr = p->showHeader;
1856 rowSep = p->rowSeparator;
1857 }else{
1858 colWidth = aExplainWidths;
1859 showHdr = 1;
1860 rowSep = SEP_Row;
1861 }
1862 if( p->cnt++==0 ){
1863 for(i=0; i<nArg; i++){
1864 int w, n;
1865 if( i<ArraySize(p->colWidth) ){
1866 w = colWidth[i];
1867 }else{
1868 w = 0;
1869 }
1870 if( w==0 ){
1871 w = strlenChar(azCol[i] ? azCol[i] : "");
1872 if( w<10 ) w = 10;
1873 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1874 if( w<n ) w = n;
1875 }
1876 if( i<ArraySize(p->actualWidth) ){
1877 p->actualWidth[i] = w;
1878 }
1879 if( showHdr ){
1880 utf8_width_print(p->out, w, azCol[i]);
1881 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1882 }
1883 }
1884 if( showHdr ){
1885 for(i=0; i<nArg; i++){
1886 int w;
1887 if( i<ArraySize(p->actualWidth) ){
1888 w = p->actualWidth[i];
1889 if( w<0 ) w = -w;
1890 }else{
1891 w = 10;
1892 }
1893 utf8_printf(p->out,"%-*.*s%s",w,w,
1894 "----------------------------------------------------------"
1895 "----------------------------------------------------------",
1896 i==nArg-1 ? rowSep : " ");
1897 }
1898 }
1899 }
1900 if( azArg==0 ) break;
1901 for(i=0; i<nArg; i++){
1902 int w;
1903 if( i<ArraySize(p->actualWidth) ){
1904 w = p->actualWidth[i];
1905 }else{
1906 w = 10;
1907 }
1908 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1909 w = strlenChar(azArg[i]);
1910 }
1911 if( i==1 && p->aiIndent && p->pStmt ){
1912 if( p->iIndent<p->nIndent ){
1913 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1914 }
1915 p->iIndent++;
1916 }
1917 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1918 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1919 }
1920 break;
1921 }
1922 case MODE_Semi: { /* .schema and .fullschema output */
1923 printSchemaLine(p->out, azArg[0], ";\n");
1924 break;
1925 }
1926 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1927 char *z;
1928 int j;
1929 int nParen = 0;
1930 char cEnd = 0;
1931 char c;
1932 int nLine = 0;
1933 assert( nArg==1 );
1934 if( azArg[0]==0 ) break;
1935 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1936 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1937 ){
1938 utf8_printf(p->out, "%s;\n", azArg[0]);
1939 break;
1940 }
1941 z = sqlite3_mprintf("%s", azArg[0]);
1942 j = 0;
1943 for(i=0; IsSpace(z[i]); i++){}
1944 for(; (c = z[i])!=0; i++){
1945 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001946 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001947 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1948 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1949 j--;
1950 }
1951 z[j++] = c;
1952 }
1953 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1954 z[j] = 0;
1955 if( strlen30(z)>=79 ){
drh11be81d2018-01-06 15:46:20 +00001956 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001957 if( c==cEnd ){
1958 cEnd = 0;
1959 }else if( c=='"' || c=='\'' || c=='`' ){
1960 cEnd = c;
1961 }else if( c=='[' ){
1962 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001963 }else if( c=='-' && z[i+1]=='-' ){
1964 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001965 }else if( c=='(' ){
1966 nParen++;
1967 }else if( c==')' ){
1968 nParen--;
1969 if( nLine>0 && nParen==0 && j>0 ){
1970 printSchemaLineN(p->out, z, j, "\n");
1971 j = 0;
1972 }
1973 }
1974 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001975 if( nParen==1 && cEnd==0
1976 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1977 ){
drh2ce15c32017-07-11 13:34:40 +00001978 if( c=='\n' ) j--;
1979 printSchemaLineN(p->out, z, j, "\n ");
1980 j = 0;
1981 nLine++;
1982 while( IsSpace(z[i+1]) ){ i++; }
1983 }
1984 }
1985 z[j] = 0;
1986 }
1987 printSchemaLine(p->out, z, ";\n");
1988 sqlite3_free(z);
1989 break;
1990 }
1991 case MODE_List: {
1992 if( p->cnt++==0 && p->showHeader ){
1993 for(i=0; i<nArg; i++){
1994 utf8_printf(p->out,"%s%s",azCol[i],
1995 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1996 }
1997 }
1998 if( azArg==0 ) break;
1999 for(i=0; i<nArg; i++){
2000 char *z = azArg[i];
2001 if( z==0 ) z = p->nullValue;
2002 utf8_printf(p->out, "%s", z);
2003 if( i<nArg-1 ){
2004 utf8_printf(p->out, "%s", p->colSeparator);
2005 }else{
2006 utf8_printf(p->out, "%s", p->rowSeparator);
2007 }
2008 }
2009 break;
2010 }
2011 case MODE_Html: {
2012 if( p->cnt++==0 && p->showHeader ){
2013 raw_printf(p->out,"<TR>");
2014 for(i=0; i<nArg; i++){
2015 raw_printf(p->out,"<TH>");
2016 output_html_string(p->out, azCol[i]);
2017 raw_printf(p->out,"</TH>\n");
2018 }
2019 raw_printf(p->out,"</TR>\n");
2020 }
2021 if( azArg==0 ) break;
2022 raw_printf(p->out,"<TR>");
2023 for(i=0; i<nArg; i++){
2024 raw_printf(p->out,"<TD>");
2025 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2026 raw_printf(p->out,"</TD>\n");
2027 }
2028 raw_printf(p->out,"</TR>\n");
2029 break;
2030 }
2031 case MODE_Tcl: {
2032 if( p->cnt++==0 && p->showHeader ){
2033 for(i=0; i<nArg; i++){
2034 output_c_string(p->out,azCol[i] ? azCol[i] : "");
2035 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2036 }
2037 utf8_printf(p->out, "%s", p->rowSeparator);
2038 }
2039 if( azArg==0 ) break;
2040 for(i=0; i<nArg; i++){
2041 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2042 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2043 }
2044 utf8_printf(p->out, "%s", p->rowSeparator);
2045 break;
2046 }
2047 case MODE_Csv: {
2048 setBinaryMode(p->out, 1);
2049 if( p->cnt++==0 && p->showHeader ){
2050 for(i=0; i<nArg; i++){
2051 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
2052 }
2053 utf8_printf(p->out, "%s", p->rowSeparator);
2054 }
2055 if( nArg>0 ){
2056 for(i=0; i<nArg; i++){
2057 output_csv(p, azArg[i], i<nArg-1);
2058 }
2059 utf8_printf(p->out, "%s", p->rowSeparator);
2060 }
2061 setTextMode(p->out, 1);
2062 break;
2063 }
2064 case MODE_Insert: {
2065 if( azArg==0 ) break;
2066 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2067 if( p->showHeader ){
2068 raw_printf(p->out,"(");
2069 for(i=0; i<nArg; i++){
2070 if( i>0 ) raw_printf(p->out, ",");
2071 if( quoteChar(azCol[i]) ){
2072 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2073 utf8_printf(p->out, "%s", z);
2074 sqlite3_free(z);
2075 }else{
2076 raw_printf(p->out, "%s", azCol[i]);
2077 }
2078 }
2079 raw_printf(p->out,")");
2080 }
2081 p->cnt++;
2082 for(i=0; i<nArg; i++){
2083 raw_printf(p->out, i>0 ? "," : " VALUES(");
2084 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2085 utf8_printf(p->out,"NULL");
2086 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2087 if( ShellHasFlag(p, SHFLG_Newlines) ){
2088 output_quoted_string(p->out, azArg[i]);
2089 }else{
2090 output_quoted_escaped_string(p->out, azArg[i]);
2091 }
2092 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2093 utf8_printf(p->out,"%s", azArg[i]);
2094 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2095 char z[50];
2096 double r = sqlite3_column_double(p->pStmt, i);
drh2f1f8802018-06-13 17:19:20 +00002097 sqlite3_uint64 ur;
2098 memcpy(&ur,&r,sizeof(r));
2099 if( ur==0x7ff0000000000000LL ){
2100 raw_printf(p->out, "1e999");
2101 }else if( ur==0xfff0000000000000LL ){
2102 raw_printf(p->out, "-1e999");
2103 }else{
2104 sqlite3_snprintf(50,z,"%!.20g", r);
2105 raw_printf(p->out, "%s", z);
2106 }
drh2ce15c32017-07-11 13:34:40 +00002107 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2108 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2109 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2110 output_hex_blob(p->out, pBlob, nBlob);
2111 }else if( isNumber(azArg[i], 0) ){
2112 utf8_printf(p->out,"%s", azArg[i]);
2113 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2114 output_quoted_string(p->out, azArg[i]);
2115 }else{
2116 output_quoted_escaped_string(p->out, azArg[i]);
2117 }
2118 }
2119 raw_printf(p->out,");\n");
2120 break;
2121 }
2122 case MODE_Quote: {
2123 if( azArg==0 ) break;
2124 if( p->cnt==0 && p->showHeader ){
2125 for(i=0; i<nArg; i++){
2126 if( i>0 ) raw_printf(p->out, ",");
2127 output_quoted_string(p->out, azCol[i]);
2128 }
2129 raw_printf(p->out,"\n");
2130 }
2131 p->cnt++;
2132 for(i=0; i<nArg; i++){
2133 if( i>0 ) raw_printf(p->out, ",");
2134 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2135 utf8_printf(p->out,"NULL");
2136 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2137 output_quoted_string(p->out, azArg[i]);
2138 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2139 utf8_printf(p->out,"%s", azArg[i]);
2140 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2141 char z[50];
2142 double r = sqlite3_column_double(p->pStmt, i);
2143 sqlite3_snprintf(50,z,"%!.20g", r);
2144 raw_printf(p->out, "%s", z);
2145 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2146 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2147 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2148 output_hex_blob(p->out, pBlob, nBlob);
2149 }else if( isNumber(azArg[i], 0) ){
2150 utf8_printf(p->out,"%s", azArg[i]);
2151 }else{
2152 output_quoted_string(p->out, azArg[i]);
2153 }
2154 }
2155 raw_printf(p->out,"\n");
2156 break;
2157 }
2158 case MODE_Ascii: {
2159 if( p->cnt++==0 && p->showHeader ){
2160 for(i=0; i<nArg; i++){
2161 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2162 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2163 }
2164 utf8_printf(p->out, "%s", p->rowSeparator);
2165 }
2166 if( azArg==0 ) break;
2167 for(i=0; i<nArg; i++){
2168 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2169 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2170 }
2171 utf8_printf(p->out, "%s", p->rowSeparator);
2172 break;
2173 }
drh4b5345c2018-04-24 13:07:40 +00002174 case MODE_EQP: {
drhe2ca99c2018-05-02 00:33:43 +00002175 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
drh4b5345c2018-04-24 13:07:40 +00002176 break;
2177 }
drh2ce15c32017-07-11 13:34:40 +00002178 }
2179 return 0;
2180}
2181
2182/*
2183** This is the callback routine that the SQLite library
2184** invokes for each row of a query result.
2185*/
2186static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2187 /* since we don't have type info, call the shell_callback with a NULL value */
2188 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2189}
2190
2191/*
2192** This is the callback routine from sqlite3_exec() that appends all
2193** output onto the end of a ShellText object.
2194*/
2195static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2196 ShellText *p = (ShellText*)pArg;
2197 int i;
2198 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00002199 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002200 if( p->n ) appendText(p, "|", 0);
2201 for(i=0; i<nArg; i++){
2202 if( i ) appendText(p, ",", 0);
2203 if( azArg[i] ) appendText(p, azArg[i], 0);
2204 }
2205 return 0;
2206}
2207
2208/*
2209** Generate an appropriate SELFTEST table in the main database.
2210*/
2211static void createSelftestTable(ShellState *p){
2212 char *zErrMsg = 0;
2213 sqlite3_exec(p->db,
2214 "SAVEPOINT selftest_init;\n"
2215 "CREATE TABLE IF NOT EXISTS selftest(\n"
2216 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2217 " op TEXT,\n" /* Operator: memo run */
2218 " cmd TEXT,\n" /* Command text */
2219 " ans TEXT\n" /* Desired answer */
2220 ");"
2221 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2222 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2223 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2224 " 'memo','Tests generated by --init');\n"
2225 "INSERT INTO [_shell$self]\n"
2226 " SELECT 'run',\n"
2227 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2228 "FROM sqlite_master ORDER BY 2'',224))',\n"
2229 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2230 "FROM sqlite_master ORDER BY 2',224));\n"
2231 "INSERT INTO [_shell$self]\n"
2232 " SELECT 'run',"
2233 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2234 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2235 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2236 " FROM (\n"
2237 " SELECT name FROM sqlite_master\n"
2238 " WHERE type='table'\n"
2239 " AND name<>'selftest'\n"
2240 " AND coalesce(rootpage,0)>0\n"
2241 " )\n"
2242 " ORDER BY name;\n"
2243 "INSERT INTO [_shell$self]\n"
2244 " VALUES('run','PRAGMA integrity_check','ok');\n"
2245 "INSERT INTO selftest(tno,op,cmd,ans)"
2246 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2247 "DROP TABLE [_shell$self];"
2248 ,0,0,&zErrMsg);
2249 if( zErrMsg ){
2250 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2251 sqlite3_free(zErrMsg);
2252 }
2253 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
2254}
2255
2256
2257/*
2258** Set the destination table field of the ShellState structure to
2259** the name of the table given. Escape any quote characters in the
2260** table name.
2261*/
2262static void set_table_name(ShellState *p, const char *zName){
2263 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00002264 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00002265 char *z;
2266
2267 if( p->zDestTable ){
2268 free(p->zDestTable);
2269 p->zDestTable = 0;
2270 }
2271 if( zName==0 ) return;
2272 cQuote = quoteChar(zName);
2273 n = strlen30(zName);
2274 if( cQuote ) n += n+2;
2275 z = p->zDestTable = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00002276 if( z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002277 n = 0;
2278 if( cQuote ) z[n++] = cQuote;
2279 for(i=0; zName[i]; i++){
2280 z[n++] = zName[i];
2281 if( zName[i]==cQuote ) z[n++] = cQuote;
2282 }
2283 if( cQuote ) z[n++] = cQuote;
2284 z[n] = 0;
2285}
2286
2287
2288/*
2289** Execute a query statement that will generate SQL output. Print
2290** the result columns, comma-separated, on a line and then add a
2291** semicolon terminator to the end of that line.
2292**
2293** If the number of columns is 1 and that column contains text "--"
2294** then write the semicolon on a separate line. That way, if a
2295** "--" comment occurs at the end of the statement, the comment
2296** won't consume the semicolon terminator.
2297*/
2298static int run_table_dump_query(
2299 ShellState *p, /* Query context */
2300 const char *zSelect, /* SELECT statement to extract content */
2301 const char *zFirstRow /* Print before first row, if not NULL */
2302){
2303 sqlite3_stmt *pSelect;
2304 int rc;
2305 int nResult;
2306 int i;
2307 const char *z;
2308 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2309 if( rc!=SQLITE_OK || !pSelect ){
2310 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2311 sqlite3_errmsg(p->db));
2312 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2313 return rc;
2314 }
2315 rc = sqlite3_step(pSelect);
2316 nResult = sqlite3_column_count(pSelect);
2317 while( rc==SQLITE_ROW ){
2318 if( zFirstRow ){
2319 utf8_printf(p->out, "%s", zFirstRow);
2320 zFirstRow = 0;
2321 }
2322 z = (const char*)sqlite3_column_text(pSelect, 0);
2323 utf8_printf(p->out, "%s", z);
2324 for(i=1; i<nResult; i++){
2325 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2326 }
2327 if( z==0 ) z = "";
2328 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2329 if( z[0] ){
2330 raw_printf(p->out, "\n;\n");
2331 }else{
2332 raw_printf(p->out, ";\n");
2333 }
2334 rc = sqlite3_step(pSelect);
2335 }
2336 rc = sqlite3_finalize(pSelect);
2337 if( rc!=SQLITE_OK ){
2338 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2339 sqlite3_errmsg(p->db));
2340 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2341 }
2342 return rc;
2343}
2344
2345/*
2346** Allocate space and save off current error string.
2347*/
2348static char *save_err_msg(
2349 sqlite3 *db /* Database to query */
2350){
2351 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
2352 char *zErrMsg = sqlite3_malloc64(nErrMsg);
2353 if( zErrMsg ){
2354 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2355 }
2356 return zErrMsg;
2357}
2358
2359#ifdef __linux__
2360/*
2361** Attempt to display I/O stats on Linux using /proc/PID/io
2362*/
2363static void displayLinuxIoStats(FILE *out){
2364 FILE *in;
2365 char z[200];
2366 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2367 in = fopen(z, "rb");
2368 if( in==0 ) return;
2369 while( fgets(z, sizeof(z), in)!=0 ){
2370 static const struct {
2371 const char *zPattern;
2372 const char *zDesc;
2373 } aTrans[] = {
2374 { "rchar: ", "Bytes received by read():" },
2375 { "wchar: ", "Bytes sent to write():" },
2376 { "syscr: ", "Read() system calls:" },
2377 { "syscw: ", "Write() system calls:" },
2378 { "read_bytes: ", "Bytes read from storage:" },
2379 { "write_bytes: ", "Bytes written to storage:" },
2380 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2381 };
2382 int i;
2383 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00002384 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00002385 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
2386 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
2387 break;
2388 }
2389 }
2390 }
2391 fclose(in);
2392}
2393#endif
2394
2395/*
2396** Display a single line of status using 64-bit values.
2397*/
2398static void displayStatLine(
2399 ShellState *p, /* The shell context */
2400 char *zLabel, /* Label for this one line */
2401 char *zFormat, /* Format for the result */
2402 int iStatusCtrl, /* Which status to display */
2403 int bReset /* True to reset the stats */
2404){
2405 sqlite3_int64 iCur = -1;
2406 sqlite3_int64 iHiwtr = -1;
2407 int i, nPercent;
2408 char zLine[200];
2409 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2410 for(i=0, nPercent=0; zFormat[i]; i++){
2411 if( zFormat[i]=='%' ) nPercent++;
2412 }
2413 if( nPercent>1 ){
2414 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2415 }else{
2416 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2417 }
2418 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2419}
2420
2421/*
2422** Display memory stats.
2423*/
2424static int display_stats(
2425 sqlite3 *db, /* Database to query */
2426 ShellState *pArg, /* Pointer to ShellState */
2427 int bReset /* True to reset the stats */
2428){
2429 int iCur;
2430 int iHiwtr;
drh393344f2018-03-09 16:37:05 +00002431 FILE *out;
2432 if( pArg==0 || pArg->out==0 ) return 0;
2433 out = pArg->out;
drh2ce15c32017-07-11 13:34:40 +00002434
drh393344f2018-03-09 16:37:05 +00002435 if( pArg->pStmt && (pArg->statsOn & 2) ){
2436 int nCol, i, x;
2437 sqlite3_stmt *pStmt = pArg->pStmt;
2438 char z[100];
2439 nCol = sqlite3_column_count(pStmt);
2440 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
2441 for(i=0; i<nCol; i++){
2442 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
2443 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002444#ifndef SQLITE_OMIT_DECLTYPE
drh393344f2018-03-09 16:37:05 +00002445 sqlite3_snprintf(30, z+x, "declared type:");
2446 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
drh929cce82018-03-17 16:26:36 +00002447#endif
2448#ifdef SQLITE_ENABLE_COLUMN_METADATA
drh393344f2018-03-09 16:37:05 +00002449 sqlite3_snprintf(30, z+x, "database name:");
2450 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
2451 sqlite3_snprintf(30, z+x, "table name:");
2452 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
2453 sqlite3_snprintf(30, z+x, "origin name:");
2454 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
drh929cce82018-03-17 16:26:36 +00002455#endif
drh2ce15c32017-07-11 13:34:40 +00002456 }
drh929cce82018-03-17 16:26:36 +00002457 }
drh2ce15c32017-07-11 13:34:40 +00002458
drh393344f2018-03-09 16:37:05 +00002459 displayStatLine(pArg, "Memory Used:",
2460 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2461 displayStatLine(pArg, "Number of Outstanding Allocations:",
2462 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2463 if( pArg->shellFlgs & SHFLG_Pagecache ){
2464 displayStatLine(pArg, "Number of Pcache Pages Used:",
2465 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2466 }
2467 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2468 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
2469 displayStatLine(pArg, "Largest Allocation:",
2470 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2471 displayStatLine(pArg, "Largest Pcache Allocation:",
2472 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2473#ifdef YYTRACKMAXSTACKDEPTH
2474 displayStatLine(pArg, "Deepest Parser Stack:",
2475 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2476#endif
2477
2478 if( db ){
drh2ce15c32017-07-11 13:34:40 +00002479 if( pArg->shellFlgs & SHFLG_Lookaside ){
2480 iHiwtr = iCur = -1;
2481 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2482 &iCur, &iHiwtr, bReset);
2483 raw_printf(pArg->out,
2484 "Lookaside Slots Used: %d (max %d)\n",
2485 iCur, iHiwtr);
2486 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2487 &iCur, &iHiwtr, bReset);
2488 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2489 iHiwtr);
2490 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2491 &iCur, &iHiwtr, bReset);
2492 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2493 iHiwtr);
2494 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2495 &iCur, &iHiwtr, bReset);
2496 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2497 iHiwtr);
2498 }
2499 iHiwtr = iCur = -1;
2500 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2501 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2502 iCur);
2503 iHiwtr = iCur = -1;
2504 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2505 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2506 iHiwtr = iCur = -1;
2507 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2508 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2509 iHiwtr = iCur = -1;
2510 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2511 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2512 iHiwtr = iCur = -1;
drhffc78a42018-03-14 14:53:50 +00002513 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
2514 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
2515 iHiwtr = iCur = -1;
drh2ce15c32017-07-11 13:34:40 +00002516 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2517 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2518 iCur);
2519 iHiwtr = iCur = -1;
2520 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2521 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2522 iCur);
2523 }
2524
drh393344f2018-03-09 16:37:05 +00002525 if( pArg->pStmt ){
drh2ce15c32017-07-11 13:34:40 +00002526 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2527 bReset);
2528 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2529 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2530 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2531 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2532 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2533 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2534 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
drh393344f2018-03-09 16:37:05 +00002535 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
2536 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
2537 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
2538 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
2539 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
2540 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
drh2ce15c32017-07-11 13:34:40 +00002541 }
2542
2543#ifdef __linux__
2544 displayLinuxIoStats(pArg->out);
2545#endif
2546
2547 /* Do not remove this machine readable comment: extra-stats-output-here */
2548
2549 return 0;
2550}
2551
2552/*
2553** Display scan stats.
2554*/
2555static void display_scanstats(
2556 sqlite3 *db, /* Database to query */
2557 ShellState *pArg /* Pointer to ShellState */
2558){
2559#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2560 UNUSED_PARAMETER(db);
2561 UNUSED_PARAMETER(pArg);
2562#else
2563 int i, k, n, mx;
2564 raw_printf(pArg->out, "-------- scanstats --------\n");
2565 mx = 0;
2566 for(k=0; k<=mx; k++){
2567 double rEstLoop = 1.0;
2568 for(i=n=0; 1; i++){
2569 sqlite3_stmt *p = pArg->pStmt;
2570 sqlite3_int64 nLoop, nVisit;
2571 double rEst;
2572 int iSid;
2573 const char *zExplain;
2574 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2575 break;
2576 }
2577 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2578 if( iSid>mx ) mx = iSid;
2579 if( iSid!=k ) continue;
2580 if( n==0 ){
2581 rEstLoop = (double)nLoop;
2582 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2583 }
2584 n++;
2585 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2586 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2587 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2588 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2589 rEstLoop *= rEst;
2590 raw_printf(pArg->out,
2591 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2592 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2593 );
2594 }
2595 }
2596 raw_printf(pArg->out, "---------------------------\n");
2597#endif
2598}
2599
2600/*
2601** Parameter azArray points to a zero-terminated array of strings. zStr
2602** points to a single nul-terminated string. Return non-zero if zStr
2603** is equal, according to strcmp(), to any of the strings in the array.
2604** Otherwise, return zero.
2605*/
2606static int str_in_array(const char *zStr, const char **azArray){
2607 int i;
2608 for(i=0; azArray[i]; i++){
2609 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2610 }
2611 return 0;
2612}
2613
2614/*
2615** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2616** and populate the ShellState.aiIndent[] array with the number of
2617** spaces each opcode should be indented before it is output.
2618**
2619** The indenting rules are:
2620**
2621** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2622** all opcodes that occur between the p2 jump destination and the opcode
2623** itself by 2 spaces.
2624**
2625** * For each "Goto", if the jump destination is earlier in the program
2626** and ends on one of:
2627** Yield SeekGt SeekLt RowSetRead Rewind
2628** or if the P1 parameter is one instead of zero,
2629** then indent all opcodes between the earlier instruction
2630** and "Goto" by 2 spaces.
2631*/
2632static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2633 const char *zSql; /* The text of the SQL statement */
2634 const char *z; /* Used to check if this is an EXPLAIN */
2635 int *abYield = 0; /* True if op is an OP_Yield */
2636 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2637 int iOp; /* Index of operation in p->aiIndent[] */
2638
drhf1949b62018-06-07 17:32:59 +00002639 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
drh2ce15c32017-07-11 13:34:40 +00002640 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2641 "Rewind", 0 };
2642 const char *azGoto[] = { "Goto", 0 };
2643
2644 /* Try to figure out if this is really an EXPLAIN statement. If this
2645 ** cannot be verified, return early. */
2646 if( sqlite3_column_count(pSql)!=8 ){
2647 p->cMode = p->mode;
2648 return;
2649 }
2650 zSql = sqlite3_sql(pSql);
2651 if( zSql==0 ) return;
2652 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2653 if( sqlite3_strnicmp(z, "explain", 7) ){
2654 p->cMode = p->mode;
2655 return;
2656 }
2657
2658 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2659 int i;
2660 int iAddr = sqlite3_column_int(pSql, 0);
2661 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2662
2663 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2664 ** p2 is an instruction address, set variable p2op to the index of that
2665 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2666 ** the current instruction is part of a sub-program generated by an
2667 ** SQL trigger or foreign key. */
2668 int p2 = sqlite3_column_int(pSql, 3);
2669 int p2op = (p2 + (iOp-iAddr));
2670
2671 /* Grow the p->aiIndent array as required */
2672 if( iOp>=nAlloc ){
2673 if( iOp==0 ){
2674 /* Do further verfication that this is explain output. Abort if
2675 ** it is not */
2676 static const char *explainCols[] = {
2677 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2678 int jj;
2679 for(jj=0; jj<ArraySize(explainCols); jj++){
2680 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2681 p->cMode = p->mode;
2682 sqlite3_reset(pSql);
2683 return;
2684 }
2685 }
2686 }
2687 nAlloc += 100;
2688 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002689 if( p->aiIndent==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002690 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
drh884406b2018-07-29 18:56:35 +00002691 if( abYield==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00002692 }
2693 abYield[iOp] = str_in_array(zOp, azYield);
2694 p->aiIndent[iOp] = 0;
2695 p->nIndent = iOp+1;
2696
2697 if( str_in_array(zOp, azNext) ){
2698 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2699 }
2700 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2701 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2702 ){
2703 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2704 }
2705 }
2706
2707 p->iIndent = 0;
2708 sqlite3_free(abYield);
2709 sqlite3_reset(pSql);
2710}
2711
2712/*
2713** Free the array allocated by explain_data_prepare().
2714*/
2715static void explain_data_delete(ShellState *p){
2716 sqlite3_free(p->aiIndent);
2717 p->aiIndent = 0;
2718 p->nIndent = 0;
2719 p->iIndent = 0;
2720}
2721
2722/*
2723** Disable and restore .wheretrace and .selecttrace settings.
2724*/
2725#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2726extern int sqlite3SelectTrace;
2727static int savedSelectTrace;
2728#endif
2729#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2730extern int sqlite3WhereTrace;
2731static int savedWhereTrace;
2732#endif
2733static void disable_debug_trace_modes(void){
2734#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2735 savedSelectTrace = sqlite3SelectTrace;
2736 sqlite3SelectTrace = 0;
2737#endif
2738#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2739 savedWhereTrace = sqlite3WhereTrace;
2740 sqlite3WhereTrace = 0;
2741#endif
2742}
2743static void restore_debug_trace_modes(void){
2744#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2745 sqlite3SelectTrace = savedSelectTrace;
2746#endif
2747#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2748 sqlite3WhereTrace = savedWhereTrace;
2749#endif
2750}
2751
drh9cb02642019-02-28 20:10:52 +00002752/* Create the TEMP table used to store parameter bindings */
2753static void bind_table_init(ShellState *p){
drh346f4e22019-03-25 21:35:41 +00002754 int wrSchema = 0;
2755 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
2756 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
drh9cb02642019-02-28 20:10:52 +00002757 sqlite3_exec(p->db,
drh65c29fd2019-03-25 21:56:26 +00002758 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n"
drh9cb02642019-02-28 20:10:52 +00002759 " key TEXT PRIMARY KEY,\n"
2760 " value ANY\n"
2761 ") WITHOUT ROWID;",
2762 0, 0, 0);
drh346f4e22019-03-25 21:35:41 +00002763 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
drh9cb02642019-02-28 20:10:52 +00002764}
2765
drh8b738d02019-02-25 18:43:54 +00002766/*
2767** Bind parameters on a prepared statement.
2768**
2769** Parameter bindings are taken from a TEMP table of the form:
2770**
drh1cb02632019-03-25 22:05:22 +00002771** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
drh8b738d02019-02-25 18:43:54 +00002772** WITHOUT ROWID;
2773**
2774** No bindings occur if this table does not exist. The special character '$'
2775** is included in the table name to help prevent collisions with actual tables.
2776** The table must be in the TEMP schema.
2777*/
2778static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
2779 int nVar;
2780 int i;
2781 int rc;
2782 sqlite3_stmt *pQ = 0;
2783
2784 nVar = sqlite3_bind_parameter_count(pStmt);
2785 if( nVar==0 ) return; /* Nothing to do */
drh65c29fd2019-03-25 21:56:26 +00002786 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters",
drh8b738d02019-02-25 18:43:54 +00002787 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){
2788 return; /* Parameter table does not exist */
2789 }
2790 rc = sqlite3_prepare_v2(pArg->db,
drh65c29fd2019-03-25 21:56:26 +00002791 "SELECT value FROM temp.sqlite_parameters"
drh8b738d02019-02-25 18:43:54 +00002792 " WHERE key=?1", -1, &pQ, 0);
2793 if( rc || pQ==0 ) return;
2794 for(i=1; i<=nVar; i++){
2795 char zNum[30];
2796 const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
2797 if( zVar==0 ){
2798 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
2799 zVar = zNum;
2800 }
2801 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
2802 if( sqlite3_step(pQ)==SQLITE_ROW ){
2803 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
2804 }else{
2805 sqlite3_bind_null(pStmt, i);
2806 }
2807 sqlite3_reset(pQ);
2808 }
2809 sqlite3_finalize(pQ);
2810}
2811
drh2ce15c32017-07-11 13:34:40 +00002812/*
2813** Run a prepared statement
2814*/
2815static void exec_prepared_stmt(
2816 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00002817 sqlite3_stmt *pStmt /* Statment to run */
drh2ce15c32017-07-11 13:34:40 +00002818){
2819 int rc;
2820
2821 /* perform the first step. this will tell us if we
2822 ** have a result set or not and how wide it is.
2823 */
2824 rc = sqlite3_step(pStmt);
2825 /* if we have a result set... */
2826 if( SQLITE_ROW == rc ){
drha10b9992018-03-09 15:24:33 +00002827 /* allocate space for col name ptr, value ptr, and type */
2828 int nCol = sqlite3_column_count(pStmt);
2829 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2830 if( !pData ){
2831 rc = SQLITE_NOMEM;
drh2ce15c32017-07-11 13:34:40 +00002832 }else{
drha10b9992018-03-09 15:24:33 +00002833 char **azCols = (char **)pData; /* Names of result columns */
2834 char **azVals = &azCols[nCol]; /* Results */
2835 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2836 int i, x;
2837 assert(sizeof(int) <= sizeof(char *));
2838 /* save off ptrs to column names */
2839 for(i=0; i<nCol; i++){
2840 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2841 }
drh2ce15c32017-07-11 13:34:40 +00002842 do{
drha10b9992018-03-09 15:24:33 +00002843 /* extract the data and data types */
2844 for(i=0; i<nCol; i++){
2845 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2846 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2847 azVals[i] = "";
2848 }else{
2849 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2850 }
2851 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2852 rc = SQLITE_NOMEM;
2853 break; /* from for */
2854 }
2855 } /* end for */
2856
2857 /* if data and types extracted successfully... */
2858 if( SQLITE_ROW == rc ){
2859 /* call the supplied callback with the result row data */
2860 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
2861 rc = SQLITE_ABORT;
2862 }else{
2863 rc = sqlite3_step(pStmt);
2864 }
2865 }
2866 } while( SQLITE_ROW == rc );
2867 sqlite3_free(pData);
drh2ce15c32017-07-11 13:34:40 +00002868 }
2869 }
2870}
2871
dan6b046be2018-01-09 15:25:55 +00002872#ifndef SQLITE_OMIT_VIRTUALTABLE
drh2ce15c32017-07-11 13:34:40 +00002873/*
dan43efc182017-12-19 17:42:13 +00002874** This function is called to process SQL if the previous shell command
2875** was ".expert". It passes the SQL in the second argument directly to
2876** the sqlite3expert object.
2877**
2878** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2879** code. In this case, (*pzErr) may be set to point to a buffer containing
2880** an English language error message. It is the responsibility of the
2881** caller to eventually free this buffer using sqlite3_free().
2882*/
2883static int expertHandleSQL(
2884 ShellState *pState,
2885 const char *zSql,
2886 char **pzErr
2887){
2888 assert( pState->expert.pExpert );
2889 assert( pzErr==0 || *pzErr==0 );
2890 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2891}
2892
2893/*
2894** This function is called either to silently clean up the object
2895** created by the ".expert" command (if bCancel==1), or to generate a
2896** report from it and then clean it up (if bCancel==0).
2897**
2898** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2899** code. In this case, (*pzErr) may be set to point to a buffer containing
2900** an English language error message. It is the responsibility of the
2901** caller to eventually free this buffer using sqlite3_free().
2902*/
2903static int expertFinish(
2904 ShellState *pState,
2905 int bCancel,
2906 char **pzErr
2907){
2908 int rc = SQLITE_OK;
2909 sqlite3expert *p = pState->expert.pExpert;
2910 assert( p );
2911 assert( bCancel || pzErr==0 || *pzErr==0 );
2912 if( bCancel==0 ){
2913 FILE *out = pState->out;
2914 int bVerbose = pState->expert.bVerbose;
2915
2916 rc = sqlite3_expert_analyze(p, pzErr);
2917 if( rc==SQLITE_OK ){
2918 int nQuery = sqlite3_expert_count(p);
2919 int i;
2920
2921 if( bVerbose ){
2922 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2923 raw_printf(out, "-- Candidates -----------------------------\n");
2924 raw_printf(out, "%s\n", zCand);
2925 }
2926 for(i=0; i<nQuery; i++){
2927 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2928 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2929 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2930 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2931 if( bVerbose ){
2932 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2933 raw_printf(out, "%s\n\n", zSql);
2934 }
2935 raw_printf(out, "%s\n", zIdx);
2936 raw_printf(out, "%s\n", zEQP);
2937 }
2938 }
2939 }
2940 sqlite3_expert_destroy(p);
2941 pState->expert.pExpert = 0;
2942 return rc;
2943}
2944
dan6b046be2018-01-09 15:25:55 +00002945/*
2946** Implementation of ".expert" dot command.
2947*/
2948static int expertDotCommand(
2949 ShellState *pState, /* Current shell tool state */
2950 char **azArg, /* Array of arguments passed to dot command */
2951 int nArg /* Number of entries in azArg[] */
2952){
2953 int rc = SQLITE_OK;
2954 char *zErr = 0;
2955 int i;
2956 int iSample = 0;
2957
2958 assert( pState->expert.pExpert==0 );
2959 memset(&pState->expert, 0, sizeof(ExpertInfo));
2960
2961 for(i=1; rc==SQLITE_OK && i<nArg; i++){
2962 char *z = azArg[i];
2963 int n;
2964 if( z[0]=='-' && z[1]=='-' ) z++;
2965 n = strlen30(z);
2966 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
2967 pState->expert.bVerbose = 1;
2968 }
2969 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
2970 if( i==(nArg-1) ){
2971 raw_printf(stderr, "option requires an argument: %s\n", z);
2972 rc = SQLITE_ERROR;
2973 }else{
2974 iSample = (int)integerValue(azArg[++i]);
2975 if( iSample<0 || iSample>100 ){
2976 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
2977 rc = SQLITE_ERROR;
2978 }
2979 }
2980 }
2981 else{
2982 raw_printf(stderr, "unknown option: %s\n", z);
2983 rc = SQLITE_ERROR;
2984 }
2985 }
2986
2987 if( rc==SQLITE_OK ){
2988 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
2989 if( pState->expert.pExpert==0 ){
2990 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
2991 rc = SQLITE_ERROR;
2992 }else{
2993 sqlite3_expert_config(
2994 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
2995 );
2996 }
2997 }
2998
2999 return rc;
3000}
3001#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
dan43efc182017-12-19 17:42:13 +00003002
3003/*
drh2ce15c32017-07-11 13:34:40 +00003004** Execute a statement or set of statements. Print
3005** any result rows/columns depending on the current mode
3006** set via the supplied callback.
3007**
3008** This is very similar to SQLite's built-in sqlite3_exec()
3009** function except it takes a slightly different callback
3010** and callback data argument.
3011*/
3012static int shell_exec(
drh2ce15c32017-07-11 13:34:40 +00003013 ShellState *pArg, /* Pointer to ShellState */
drha10b9992018-03-09 15:24:33 +00003014 const char *zSql, /* SQL to be evaluated */
drh2ce15c32017-07-11 13:34:40 +00003015 char **pzErrMsg /* Error msg written here */
3016){
3017 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
3018 int rc = SQLITE_OK; /* Return Code */
3019 int rc2;
3020 const char *zLeftover; /* Tail of unprocessed SQL */
drha10b9992018-03-09 15:24:33 +00003021 sqlite3 *db = pArg->db;
drh2ce15c32017-07-11 13:34:40 +00003022
3023 if( pzErrMsg ){
3024 *pzErrMsg = NULL;
3025 }
3026
dan6b046be2018-01-09 15:25:55 +00003027#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00003028 if( pArg->expert.pExpert ){
3029 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
3030 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
3031 }
dan6b046be2018-01-09 15:25:55 +00003032#endif
dan43efc182017-12-19 17:42:13 +00003033
drh2ce15c32017-07-11 13:34:40 +00003034 while( zSql[0] && (SQLITE_OK == rc) ){
3035 static const char *zStmtSql;
3036 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3037 if( SQLITE_OK != rc ){
3038 if( pzErrMsg ){
3039 *pzErrMsg = save_err_msg(db);
3040 }
3041 }else{
3042 if( !pStmt ){
3043 /* this happens for a comment or white-space */
3044 zSql = zLeftover;
3045 while( IsSpace(zSql[0]) ) zSql++;
3046 continue;
3047 }
3048 zStmtSql = sqlite3_sql(pStmt);
3049 if( zStmtSql==0 ) zStmtSql = "";
3050 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
3051
3052 /* save off the prepared statment handle and reset row count */
3053 if( pArg ){
3054 pArg->pStmt = pStmt;
3055 pArg->cnt = 0;
3056 }
3057
3058 /* echo the sql statement if echo on */
3059 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
3060 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
3061 }
3062
3063 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drh39c5c4a2019-03-06 14:53:27 +00003064 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){
drh2ce15c32017-07-11 13:34:40 +00003065 sqlite3_stmt *pExplain;
3066 char *zEQP;
drhada70452017-12-21 21:02:27 +00003067 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00003068 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00003069 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
3070 if( pArg->autoEQP>=AUTOEQP_trigger ){
3071 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
3072 }
drh2ce15c32017-07-11 13:34:40 +00003073 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
3074 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3075 if( rc==SQLITE_OK ){
3076 while( sqlite3_step(pExplain)==SQLITE_ROW ){
drh4b5345c2018-04-24 13:07:40 +00003077 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
drhe2ca99c2018-05-02 00:33:43 +00003078 int iEqpId = sqlite3_column_int(pExplain, 0);
3079 int iParentId = sqlite3_column_int(pExplain, 1);
drh4b5345c2018-04-24 13:07:40 +00003080 if( zEQPLine[0]=='-' ) eqp_render(pArg);
drhe2ca99c2018-05-02 00:33:43 +00003081 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
drh2ce15c32017-07-11 13:34:40 +00003082 }
drh4b5345c2018-04-24 13:07:40 +00003083 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003084 }
3085 sqlite3_finalize(pExplain);
3086 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00003087 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00003088 /* Also do an EXPLAIN for ".eqp full" mode */
3089 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3090 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3091 if( rc==SQLITE_OK ){
3092 pArg->cMode = MODE_Explain;
3093 explain_data_prepare(pArg, pExplain);
drha10b9992018-03-09 15:24:33 +00003094 exec_prepared_stmt(pArg, pExplain);
drh2ce15c32017-07-11 13:34:40 +00003095 explain_data_delete(pArg);
3096 }
3097 sqlite3_finalize(pExplain);
3098 sqlite3_free(zEQP);
3099 }
drh51efe092018-03-20 12:04:38 +00003100 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
3101 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
3102 /* Reprepare pStmt before reactiving trace modes */
3103 sqlite3_finalize(pStmt);
3104 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
drh3c49eaf2018-06-07 15:23:43 +00003105 if( pArg ) pArg->pStmt = pStmt;
drh51efe092018-03-20 12:04:38 +00003106 }
drh2ce15c32017-07-11 13:34:40 +00003107 restore_debug_trace_modes();
3108 }
3109
3110 if( pArg ){
3111 pArg->cMode = pArg->mode;
drh4b5345c2018-04-24 13:07:40 +00003112 if( pArg->autoExplain ){
drh39c5c4a2019-03-06 14:53:27 +00003113 if( sqlite3_stmt_isexplain(pStmt)==1 ){
drh4b5345c2018-04-24 13:07:40 +00003114 pArg->cMode = MODE_Explain;
3115 }
drh39c5c4a2019-03-06 14:53:27 +00003116 if( sqlite3_stmt_isexplain(pStmt)==2 ){
drh4b5345c2018-04-24 13:07:40 +00003117 pArg->cMode = MODE_EQP;
3118 }
drh2ce15c32017-07-11 13:34:40 +00003119 }
3120
3121 /* If the shell is currently in ".explain" mode, gather the extra
3122 ** data required to add indents to the output.*/
3123 if( pArg->cMode==MODE_Explain ){
3124 explain_data_prepare(pArg, pStmt);
3125 }
3126 }
3127
drh8b738d02019-02-25 18:43:54 +00003128 bind_prepared_stmt(pArg, pStmt);
drha10b9992018-03-09 15:24:33 +00003129 exec_prepared_stmt(pArg, pStmt);
drh2ce15c32017-07-11 13:34:40 +00003130 explain_data_delete(pArg);
drh4b5345c2018-04-24 13:07:40 +00003131 eqp_render(pArg);
drh2ce15c32017-07-11 13:34:40 +00003132
3133 /* print usage stats if stats on */
3134 if( pArg && pArg->statsOn ){
3135 display_stats(db, pArg, 0);
3136 }
3137
3138 /* print loop-counters if required */
3139 if( pArg && pArg->scanstatsOn ){
3140 display_scanstats(db, pArg);
3141 }
3142
3143 /* Finalize the statement just executed. If this fails, save a
3144 ** copy of the error message. Otherwise, set zSql to point to the
3145 ** next statement to execute. */
3146 rc2 = sqlite3_finalize(pStmt);
3147 if( rc!=SQLITE_NOMEM ) rc = rc2;
3148 if( rc==SQLITE_OK ){
3149 zSql = zLeftover;
3150 while( IsSpace(zSql[0]) ) zSql++;
3151 }else if( pzErrMsg ){
3152 *pzErrMsg = save_err_msg(db);
3153 }
3154
3155 /* clear saved stmt handle */
3156 if( pArg ){
3157 pArg->pStmt = NULL;
3158 }
3159 }
3160 } /* end while */
3161
3162 return rc;
3163}
3164
3165/*
3166** Release memory previously allocated by tableColumnList().
3167*/
3168static void freeColumnList(char **azCol){
3169 int i;
3170 for(i=1; azCol[i]; i++){
3171 sqlite3_free(azCol[i]);
3172 }
3173 /* azCol[0] is a static string */
3174 sqlite3_free(azCol);
3175}
3176
3177/*
3178** Return a list of pointers to strings which are the names of all
3179** columns in table zTab. The memory to hold the names is dynamically
3180** allocated and must be released by the caller using a subsequent call
3181** to freeColumnList().
3182**
3183** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3184** value that needs to be preserved, then azCol[0] is filled in with the
3185** name of the rowid column.
3186**
3187** The first regular column in the table is azCol[1]. The list is terminated
3188** by an entry with azCol[i]==0.
3189*/
3190static char **tableColumnList(ShellState *p, const char *zTab){
3191 char **azCol = 0;
3192 sqlite3_stmt *pStmt;
3193 char *zSql;
3194 int nCol = 0;
3195 int nAlloc = 0;
3196 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3197 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
3198 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
3199 int rc;
3200
3201 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3202 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3203 sqlite3_free(zSql);
3204 if( rc ) return 0;
3205 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3206 if( nCol>=nAlloc-2 ){
3207 nAlloc = nAlloc*2 + nCol + 10;
3208 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
drh4b5345c2018-04-24 13:07:40 +00003209 if( azCol==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00003210 }
3211 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3212 if( sqlite3_column_int(pStmt, 5) ){
3213 nPK++;
3214 if( nPK==1
3215 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3216 "INTEGER")==0
3217 ){
3218 isIPK = 1;
3219 }else{
3220 isIPK = 0;
3221 }
3222 }
3223 }
3224 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00003225 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003226 azCol[0] = 0;
3227 azCol[nCol+1] = 0;
3228
3229 /* The decision of whether or not a rowid really needs to be preserved
3230 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3231 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3232 ** rowids on tables where the rowid is inaccessible because there are other
3233 ** columns in the table named "rowid", "_rowid_", and "oid".
3234 */
3235 if( preserveRowid && isIPK ){
3236 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3237 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3238 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3239 ** ROWID aliases. To distinguish these cases, check to see if
3240 ** there is a "pk" entry in "PRAGMA index_list". There will be
3241 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3242 */
3243 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3244 " WHERE origin='pk'", zTab);
3245 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3246 sqlite3_free(zSql);
3247 if( rc ){
3248 freeColumnList(azCol);
3249 return 0;
3250 }
3251 rc = sqlite3_step(pStmt);
3252 sqlite3_finalize(pStmt);
3253 preserveRowid = rc==SQLITE_ROW;
3254 }
3255 if( preserveRowid ){
3256 /* Only preserve the rowid if we can find a name to use for the
3257 ** rowid */
3258 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3259 int i, j;
3260 for(j=0; j<3; j++){
3261 for(i=1; i<=nCol; i++){
3262 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3263 }
3264 if( i>nCol ){
3265 /* At this point, we know that azRowid[j] is not the name of any
3266 ** ordinary column in the table. Verify that azRowid[j] is a valid
3267 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3268 ** tables will fail this last check */
3269 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3270 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3271 break;
3272 }
3273 }
3274 }
3275 return azCol;
3276}
3277
3278/*
3279** Toggle the reverse_unordered_selects setting.
3280*/
3281static void toggleSelectOrder(sqlite3 *db){
3282 sqlite3_stmt *pStmt = 0;
3283 int iSetting = 0;
3284 char zStmt[100];
3285 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3286 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3287 iSetting = sqlite3_column_int(pStmt, 0);
3288 }
3289 sqlite3_finalize(pStmt);
3290 sqlite3_snprintf(sizeof(zStmt), zStmt,
3291 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3292 sqlite3_exec(db, zStmt, 0, 0, 0);
3293}
3294
3295/*
3296** This is a different callback routine used for dumping the database.
3297** Each row received by this callback consists of a table name,
3298** the table type ("index" or "table") and SQL to create the table.
3299** This routine should print text sufficient to recreate the table.
3300*/
3301static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
3302 int rc;
3303 const char *zTable;
3304 const char *zType;
3305 const char *zSql;
3306 ShellState *p = (ShellState *)pArg;
3307
3308 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00003309 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00003310 zTable = azArg[0];
3311 zType = azArg[1];
3312 zSql = azArg[2];
3313
3314 if( strcmp(zTable, "sqlite_sequence")==0 ){
3315 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
3316 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
3317 raw_printf(p->out, "ANALYZE sqlite_master;\n");
3318 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3319 return 0;
3320 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3321 char *zIns;
3322 if( !p->writableSchema ){
3323 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
3324 p->writableSchema = 1;
3325 }
3326 zIns = sqlite3_mprintf(
3327 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3328 "VALUES('table','%q','%q',0,'%q');",
3329 zTable, zTable, zSql);
3330 utf8_printf(p->out, "%s\n", zIns);
3331 sqlite3_free(zIns);
3332 return 0;
3333 }else{
3334 printSchemaLine(p->out, zSql, ";\n");
3335 }
3336
3337 if( strcmp(zType, "table")==0 ){
3338 ShellText sSelect;
3339 ShellText sTable;
3340 char **azCol;
3341 int i;
3342 char *savedDestTable;
3343 int savedMode;
3344
3345 azCol = tableColumnList(p, zTable);
3346 if( azCol==0 ){
3347 p->nErr++;
3348 return 0;
3349 }
3350
3351 /* Always quote the table name, even if it appears to be pure ascii,
3352 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3353 initText(&sTable);
3354 appendText(&sTable, zTable, quoteChar(zTable));
3355 /* If preserving the rowid, add a column list after the table name.
3356 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3357 ** instead of the usual "INSERT INTO tab VALUES(...)".
3358 */
3359 if( azCol[0] ){
3360 appendText(&sTable, "(", 0);
3361 appendText(&sTable, azCol[0], 0);
3362 for(i=1; azCol[i]; i++){
3363 appendText(&sTable, ",", 0);
3364 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
3365 }
3366 appendText(&sTable, ")", 0);
3367 }
3368
3369 /* Build an appropriate SELECT statement */
3370 initText(&sSelect);
3371 appendText(&sSelect, "SELECT ", 0);
3372 if( azCol[0] ){
3373 appendText(&sSelect, azCol[0], 0);
3374 appendText(&sSelect, ",", 0);
3375 }
3376 for(i=1; azCol[i]; i++){
3377 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
3378 if( azCol[i+1] ){
3379 appendText(&sSelect, ",", 0);
3380 }
3381 }
3382 freeColumnList(azCol);
3383 appendText(&sSelect, " FROM ", 0);
3384 appendText(&sSelect, zTable, quoteChar(zTable));
3385
3386 savedDestTable = p->zDestTable;
3387 savedMode = p->mode;
3388 p->zDestTable = sTable.z;
3389 p->mode = p->cMode = MODE_Insert;
drha10b9992018-03-09 15:24:33 +00003390 rc = shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003391 if( (rc&0xff)==SQLITE_CORRUPT ){
3392 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3393 toggleSelectOrder(p->db);
drha10b9992018-03-09 15:24:33 +00003394 shell_exec(p, sSelect.z, 0);
drh2ce15c32017-07-11 13:34:40 +00003395 toggleSelectOrder(p->db);
3396 }
3397 p->zDestTable = savedDestTable;
3398 p->mode = savedMode;
3399 freeText(&sTable);
3400 freeText(&sSelect);
3401 if( rc ) p->nErr++;
3402 }
3403 return 0;
3404}
3405
3406/*
3407** Run zQuery. Use dump_callback() as the callback routine so that
3408** the contents of the query are output as SQL statements.
3409**
3410** If we get a SQLITE_CORRUPT error, rerun the query after appending
3411** "ORDER BY rowid DESC" to the end.
3412*/
3413static int run_schema_dump_query(
3414 ShellState *p,
3415 const char *zQuery
3416){
3417 int rc;
3418 char *zErr = 0;
3419 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
3420 if( rc==SQLITE_CORRUPT ){
3421 char *zQ2;
3422 int len = strlen30(zQuery);
3423 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3424 if( zErr ){
3425 utf8_printf(p->out, "/****** %s ******/\n", zErr);
3426 sqlite3_free(zErr);
3427 zErr = 0;
3428 }
3429 zQ2 = malloc( len+100 );
3430 if( zQ2==0 ) return rc;
3431 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
3432 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3433 if( rc ){
3434 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
3435 }else{
3436 rc = SQLITE_CORRUPT;
3437 }
3438 sqlite3_free(zErr);
3439 free(zQ2);
3440 }
3441 return rc;
3442}
3443
3444/*
drh98aa2ab2018-09-26 16:53:51 +00003445** Text of help messages.
3446**
3447** The help text for each individual command begins with a line that starts
3448** with ".". Subsequent lines are supplimental information.
3449**
3450** There must be two or more spaces between the end of the command and the
3451** start of the description of what that command does.
drh2ce15c32017-07-11 13:34:40 +00003452*/
drh98aa2ab2018-09-26 16:53:51 +00003453static const char *(azHelp[]) = {
drhe37c0e12018-01-06 19:19:50 +00003454#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drh98aa2ab2018-09-26 16:53:51 +00003455 ".archive ... Manage SQL archives",
3456 " Each command must have exactly one of the following options:",
3457 " -c, --create Create a new archive",
drhaf5a2e12019-03-25 15:09:19 +00003458 " -u, --update Add files or update files with changed mtime",
drhb17ea912019-03-25 14:24:19 +00003459 " -i, --insert Like -u but always add even if mtime unchanged",
drh98aa2ab2018-09-26 16:53:51 +00003460 " -t, --list List contents of archive",
3461 " -x, --extract Extract files from archive",
3462 " Optional arguments:",
3463 " -v, --verbose Print each filename as it is processed",
3464 " -f FILE, --file FILE Operate on archive FILE (default is current db)",
3465 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS",
3466 " -C DIR, --directory DIR Change to directory DIR to read/extract files",
3467 " -n, --dryrun Show the SQL that would have occurred",
3468 " Examples:",
3469 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar",
3470 " .ar -tf archive.sar # List members of archive.sar",
3471 " .ar -xvf archive.sar # Verbosely extract files from archive.sar",
3472 " See also:",
3473 " http://sqlite.org/cli.html#sqlar_archive_support",
drhe37c0e12018-01-06 19:19:50 +00003474#endif
drh2ce15c32017-07-11 13:34:40 +00003475#ifndef SQLITE_OMIT_AUTHORIZATION
drh98aa2ab2018-09-26 16:53:51 +00003476 ".auth ON|OFF Show authorizer callbacks",
drh2ce15c32017-07-11 13:34:40 +00003477#endif
drh98aa2ab2018-09-26 16:53:51 +00003478 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3479 " --append Use the appendvfs",
drha50bffb2018-12-08 01:09:14 +00003480 " --async Write to FILE without a journal and without fsync()",
drh98aa2ab2018-09-26 16:53:51 +00003481 ".bail on|off Stop after hitting an error. Default OFF",
3482 ".binary on|off Turn binary output on or off. Default OFF",
3483 ".cd DIRECTORY Change the working directory to DIRECTORY",
3484 ".changes on|off Show number of rows changed by SQL",
3485 ".check GLOB Fail if output since .testcase does not match",
3486 ".clone NEWDB Clone data into NEWDB from the existing database",
3487 ".databases List names and files of attached databases",
3488 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3489 ".dbinfo ?DB? Show status information about the database",
drheb7f2a02018-09-26 18:02:32 +00003490 ".dump ?TABLE? ... Render all database content as SQL",
3491 " Options:",
3492 " --preserve-rowids Include ROWID values in the output",
3493 " --newlines Allow unescaped newline characters in output",
drhe551b512019-04-17 13:58:07 +00003494 " TABLE is a LIKE pattern for the tables to dump",
drh98aa2ab2018-09-26 16:53:51 +00003495 ".echo on|off Turn command echo on or off",
drhb4e50392019-01-26 15:40:04 +00003496 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN",
3497 " Other Modes:",
3498#ifdef SQLITE_DEBUG
3499 " test Show raw EXPLAIN QUERY PLAN output",
3500 " trace Like \"full\" but also enable \"PRAGMA vdbe_trace\"",
3501#endif
3502 " trigger Like \"full\" but also show trigger bytecode",
drh98aa2ab2018-09-26 16:53:51 +00003503 ".excel Display the output of next command in a spreadsheet",
drheb7f2a02018-09-26 18:02:32 +00003504 ".exit ?CODE? Exit this program with return-code CODE",
drh98aa2ab2018-09-26 16:53:51 +00003505 ".expert EXPERIMENTAL. Suggest indexes for specified queries",
drh2ce15c32017-07-11 13:34:40 +00003506/* Because explain mode comes on automatically now, the ".explain" mode
3507** is removed from the help screen. It is still supported for legacy, however */
drh98aa2ab2018-09-26 16:53:51 +00003508/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/
3509 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3510 ".headers on|off Turn display of headers on or off",
3511 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3512 ".import FILE TABLE Import data from FILE into TABLE",
drh2ce15c32017-07-11 13:34:40 +00003513#ifndef SQLITE_OMIT_TEST_CONTROL
drh98aa2ab2018-09-26 16:53:51 +00003514 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
drh2ce15c32017-07-11 13:34:40 +00003515#endif
drh98aa2ab2018-09-26 16:53:51 +00003516 ".indexes ?TABLE? Show names of indexes",
3517 " If TABLE is specified, only show indexes for",
3518 " tables matching TABLE using the LIKE operator.",
drh2ce15c32017-07-11 13:34:40 +00003519#ifdef SQLITE_ENABLE_IOTRACE
drh98aa2ab2018-09-26 16:53:51 +00003520 ".iotrace FILE Enable I/O diagnostic logging to FILE",
drh2ce15c32017-07-11 13:34:40 +00003521#endif
drh98aa2ab2018-09-26 16:53:51 +00003522 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3523 ".lint OPTIONS Report potential schema issues.",
3524 " Options:",
3525 " fkey-indexes Find missing foreign key indexes",
drh2ce15c32017-07-11 13:34:40 +00003526#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh98aa2ab2018-09-26 16:53:51 +00003527 ".load FILE ?ENTRY? Load an extension library",
drh2ce15c32017-07-11 13:34:40 +00003528#endif
drh98aa2ab2018-09-26 16:53:51 +00003529 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3530 ".mode MODE ?TABLE? Set output mode",
3531 " MODE is one of:",
3532 " ascii Columns/rows delimited by 0x1F and 0x1E",
3533 " csv Comma-separated values",
3534 " column Left-aligned columns. (See .width)",
3535 " html HTML <table> code",
3536 " insert SQL insert statements for TABLE",
3537 " line One value per line",
3538 " list Values delimited by \"|\"",
3539 " quote Escape answers as for SQL",
3540 " tabs Tab-separated values",
3541 " tcl TCL list elements",
3542 ".nullvalue STRING Use STRING in place of NULL values",
3543 ".once (-e|-x|FILE) Output for the next SQL command only to FILE",
3544 " If FILE begins with '|' then open as a pipe",
3545 " Other options:",
3546 " -e Invoke system text editor",
3547 " -x Open in a spreadsheet",
3548 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3549 " Options:",
drh60f34ae2018-10-30 13:19:49 +00003550 " --append Use appendvfs to append database to the end of FILE",
drha751f392018-10-30 15:31:22 +00003551#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00003552 " --deserialize Load into memory useing sqlite3_deserialize()",
drh33746482018-12-13 15:06:26 +00003553 " --hexdb Load the output of \"dbtotxt\" as an in-memory database",
drh6ca64482019-01-22 16:06:20 +00003554 " --maxsize N Maximum size for --hexdb or --deserialized database",
drha751f392018-10-30 15:31:22 +00003555#endif
drh60f34ae2018-10-30 13:19:49 +00003556 " --new Initialize FILE to an empty database",
3557 " --readonly Open FILE readonly",
3558 " --zip FILE is a ZIP archive",
drh98aa2ab2018-09-26 16:53:51 +00003559 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
3560 " If FILE begins with '|' then open it as a pipe.",
drh9cb02642019-02-28 20:10:52 +00003561 ".parameter CMD ... Manage SQL parameter bindings",
3562 " clear Erase all bindings",
3563 " init Initialize the TEMP table that holds bindings",
3564 " list List the current parameter bindings",
3565 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE",
3566 " PARAMETER should start with '$', ':', '@', or '?'",
3567 " unset PARAMETER Remove PARAMETER from the binding table",
drh98aa2ab2018-09-26 16:53:51 +00003568 ".print STRING... Print literal STRING",
drh569b1d92019-02-05 20:51:41 +00003569#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00003570 ".progress N Invoke progress handler after every N opcodes",
3571 " --limit N Interrupt after N progress callbacks",
3572 " --once Do no more than one progress interrupt",
3573 " --quiet|-q No output except at interrupts",
3574 " --reset Reset the count for each input and interrupt",
drh569b1d92019-02-05 20:51:41 +00003575#endif
drh98aa2ab2018-09-26 16:53:51 +00003576 ".prompt MAIN CONTINUE Replace the standard prompts",
3577 ".quit Exit this program",
3578 ".read FILE Read input from FILE",
dan42ebb012019-04-27 18:47:03 +00003579 ".recover Recover as much data as possible from corrupt db.",
drh98aa2ab2018-09-26 16:53:51 +00003580 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
3581 ".save FILE Write in-memory database into FILE",
3582 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
3583 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
3584 " Options:",
3585 " --indent Try to pretty-print the schema",
drheb7f2a02018-09-26 18:02:32 +00003586 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
3587 " Options:",
3588 " --init Create a new SELFTEST table",
3589 " -v Verbose output",
drh98aa2ab2018-09-26 16:53:51 +00003590 ".separator COL ?ROW? Change the column and row separators",
drh2ce15c32017-07-11 13:34:40 +00003591#if defined(SQLITE_ENABLE_SESSION)
drheb7f2a02018-09-26 18:02:32 +00003592 ".session ?NAME? CMD ... Create or control sessions",
3593 " Subcommands:",
3594 " attach TABLE Attach TABLE",
3595 " changeset FILE Write a changeset into FILE",
3596 " close Close one session",
3597 " enable ?BOOLEAN? Set or query the enable bit",
3598 " filter GLOB... Reject tables matching GLOBs",
3599 " indirect ?BOOLEAN? Mark or query the indirect status",
3600 " isempty Query whether the session is empty",
3601 " list List currently open session names",
3602 " open DB NAME Open a new session on DB",
3603 " patchset FILE Write a patchset into FILE",
3604 " If ?NAME? is omitted, the first defined session is used.",
drh2ce15c32017-07-11 13:34:40 +00003605#endif
drheb7f2a02018-09-26 18:02:32 +00003606 ".sha3sum ... Compute a SHA3 hash of database content",
3607 " Options:",
3608 " --schema Also hash the sqlite_master table",
3609 " --sha3-224 Use the sha3-224 algorithm",
3610 " --sha3-256 Use the sha3-256 algorithm. This is the default.",
3611 " --sha3-384 Use the sha3-384 algorithm",
3612 " --sha3-512 Use the sha3-512 algorithm",
3613 " Any other argument is a LIKE pattern for tables to hash",
drh04a28c32018-01-31 01:38:44 +00003614#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003615 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003616#endif
drh98aa2ab2018-09-26 16:53:51 +00003617 ".show Show the current values for various settings",
3618 ".stats ?on|off? Show stats or turn stats on or off",
drh04a28c32018-01-31 01:38:44 +00003619#ifndef SQLITE_NOHAVE_SYSTEM
drh98aa2ab2018-09-26 16:53:51 +00003620 ".system CMD ARGS... Run CMD ARGS... in a system shell",
drh04a28c32018-01-31 01:38:44 +00003621#endif
drh98aa2ab2018-09-26 16:53:51 +00003622 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
3623 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
3624 ".timeout MS Try opening locked tables for MS milliseconds",
3625 ".timer on|off Turn SQL timer on or off",
drh707821f2018-12-05 13:39:06 +00003626#ifndef SQLITE_OMIT_TRACE
3627 ".trace ?OPTIONS? Output each SQL statement as it is run",
3628 " FILE Send output to FILE",
3629 " stdout Send output to stdout",
3630 " stderr Send output to stderr",
3631 " off Disable tracing",
3632 " --expanded Expand query parameters",
3633#ifdef SQLITE_ENABLE_NORMALIZE
3634 " --normalized Normal the SQL statements",
3635#endif
3636 " --plain Show SQL as it is input",
3637 " --stmt Trace statement execution (SQLITE_TRACE_STMT)",
3638 " --profile Profile statements (SQLITE_TRACE_PROFILE)",
3639 " --row Trace each row (SQLITE_TRACE_ROW)",
3640 " --close Trace connection close (SQLITE_TRACE_CLOSE)",
3641#endif /* SQLITE_OMIT_TRACE */
drh98aa2ab2018-09-26 16:53:51 +00003642 ".vfsinfo ?AUX? Information about the top-level VFS",
3643 ".vfslist List all available VFSes",
3644 ".vfsname ?AUX? Print the name of the VFS stack",
3645 ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
3646 " Negative values right-justify",
3647};
3648
3649/*
3650** Output help text.
3651**
3652** zPattern describes the set of commands for which help text is provided.
3653** If zPattern is NULL, then show all commands, but only give a one-line
3654** description of each.
3655**
3656** Return the number of matches.
3657*/
3658static int showHelp(FILE *out, const char *zPattern){
drhe93f8262018-10-11 16:53:37 +00003659 int i = 0;
3660 int j = 0;
drh98aa2ab2018-09-26 16:53:51 +00003661 int n = 0;
3662 char *zPat;
drh488cddf2018-10-06 14:38:17 +00003663 if( zPattern==0
3664 || zPattern[0]=='0'
3665 || strcmp(zPattern,"-a")==0
3666 || strcmp(zPattern,"-all")==0
3667 ){
drh98aa2ab2018-09-26 16:53:51 +00003668 /* Show all commands, but only one line per command */
drh488cddf2018-10-06 14:38:17 +00003669 if( zPattern==0 ) zPattern = "";
drh98aa2ab2018-09-26 16:53:51 +00003670 for(i=0; i<ArraySize(azHelp); i++){
drh488cddf2018-10-06 14:38:17 +00003671 if( azHelp[i][0]=='.' || zPattern[0] ){
drh98aa2ab2018-09-26 16:53:51 +00003672 utf8_printf(out, "%s\n", azHelp[i]);
3673 n++;
3674 }
3675 }
3676 }else{
3677 /* Look for commands that for which zPattern is an exact prefix */
3678 zPat = sqlite3_mprintf(".%s*", zPattern);
3679 for(i=0; i<ArraySize(azHelp); i++){
3680 if( sqlite3_strglob(zPat, azHelp[i])==0 ){
3681 utf8_printf(out, "%s\n", azHelp[i]);
drheb7f2a02018-09-26 18:02:32 +00003682 j = i+1;
drh98aa2ab2018-09-26 16:53:51 +00003683 n++;
3684 }
3685 }
3686 sqlite3_free(zPat);
drheb7f2a02018-09-26 18:02:32 +00003687 if( n ){
3688 if( n==1 ){
3689 /* when zPattern is a prefix of exactly one command, then include the
3690 ** details of that command, which should begin at offset j */
3691 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){
3692 utf8_printf(out, "%s\n", azHelp[j]);
3693 j++;
3694 }
3695 }
3696 return n;
3697 }
3698 /* Look for commands that contain zPattern anywhere. Show the complete
3699 ** text of all commands that match. */
drh98aa2ab2018-09-26 16:53:51 +00003700 zPat = sqlite3_mprintf("%%%s%%", zPattern);
3701 for(i=0; i<ArraySize(azHelp); i++){
3702 if( azHelp[i][0]=='.' ) j = i;
3703 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){
3704 utf8_printf(out, "%s\n", azHelp[j]);
3705 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){
3706 j++;
3707 utf8_printf(out, "%s\n", azHelp[j]);
3708 }
3709 i = j;
3710 n++;
3711 }
3712 }
3713 sqlite3_free(zPat);
3714 }
3715 return n;
3716}
drh2ce15c32017-07-11 13:34:40 +00003717
drh2ce15c32017-07-11 13:34:40 +00003718/* Forward reference */
drh60379d42018-12-13 18:30:01 +00003719static int process_input(ShellState *p);
drh2ce15c32017-07-11 13:34:40 +00003720
3721/*
3722** Read the content of file zName into memory obtained from sqlite3_malloc64()
3723** and return a pointer to the buffer. The caller is responsible for freeing
3724** the memory.
3725**
3726** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3727** read.
3728**
3729** For convenience, a nul-terminator byte is always appended to the data read
3730** from the file before the buffer is returned. This byte is not included in
3731** the final value of (*pnByte), if applicable.
3732**
3733** NULL is returned if any error is encountered. The final value of *pnByte
3734** is undefined in this case.
3735*/
3736static char *readFile(const char *zName, int *pnByte){
3737 FILE *in = fopen(zName, "rb");
3738 long nIn;
3739 size_t nRead;
3740 char *pBuf;
3741 if( in==0 ) return 0;
3742 fseek(in, 0, SEEK_END);
3743 nIn = ftell(in);
3744 rewind(in);
3745 pBuf = sqlite3_malloc64( nIn+1 );
drh1dbb1472018-10-11 10:37:24 +00003746 if( pBuf==0 ){ fclose(in); return 0; }
drh2ce15c32017-07-11 13:34:40 +00003747 nRead = fread(pBuf, nIn, 1, in);
3748 fclose(in);
3749 if( nRead!=1 ){
3750 sqlite3_free(pBuf);
3751 return 0;
3752 }
3753 pBuf[nIn] = 0;
3754 if( pnByte ) *pnByte = nIn;
3755 return pBuf;
3756}
3757
3758#if defined(SQLITE_ENABLE_SESSION)
3759/*
3760** Close a single OpenSession object and release all of its associated
3761** resources.
3762*/
3763static void session_close(OpenSession *pSession){
3764 int i;
3765 sqlite3session_delete(pSession->p);
3766 sqlite3_free(pSession->zName);
3767 for(i=0; i<pSession->nFilter; i++){
3768 sqlite3_free(pSession->azFilter[i]);
3769 }
3770 sqlite3_free(pSession->azFilter);
3771 memset(pSession, 0, sizeof(OpenSession));
3772}
3773#endif
3774
3775/*
3776** Close all OpenSession objects and release all associated resources.
3777*/
3778#if defined(SQLITE_ENABLE_SESSION)
3779static void session_close_all(ShellState *p){
3780 int i;
3781 for(i=0; i<p->nSession; i++){
3782 session_close(&p->aSession[i]);
3783 }
3784 p->nSession = 0;
3785}
3786#else
3787# define session_close_all(X)
3788#endif
3789
3790/*
3791** Implementation of the xFilter function for an open session. Omit
3792** any tables named by ".session filter" but let all other table through.
3793*/
3794#if defined(SQLITE_ENABLE_SESSION)
3795static int session_filter(void *pCtx, const char *zTab){
3796 OpenSession *pSession = (OpenSession*)pCtx;
3797 int i;
3798 for(i=0; i<pSession->nFilter; i++){
3799 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3800 }
3801 return 1;
3802}
3803#endif
3804
3805/*
drh1fa6d9f2018-01-06 21:46:01 +00003806** Try to deduce the type of file for zName based on its content. Return
3807** one of the SHELL_OPEN_* constants.
drh1bf208c2018-03-09 21:54:01 +00003808**
3809** If the file does not exist or is empty but its name looks like a ZIP
3810** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3811** Otherwise, assume an ordinary database regardless of the filename if
3812** the type cannot be determined from content.
drh1fa6d9f2018-01-06 21:46:01 +00003813*/
drhfc97c1c2018-05-14 00:41:12 +00003814int deduceDatabaseType(const char *zName, int dfltZip){
drh1fa6d9f2018-01-06 21:46:01 +00003815 FILE *f = fopen(zName, "rb");
3816 size_t n;
3817 int rc = SHELL_OPEN_UNSPEC;
3818 char zBuf[100];
drh1bf208c2018-03-09 21:54:01 +00003819 if( f==0 ){
drhbe4ccb22018-05-17 20:04:24 +00003820 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
3821 return SHELL_OPEN_ZIPFILE;
3822 }else{
3823 return SHELL_OPEN_NORMAL;
3824 }
drh1bf208c2018-03-09 21:54:01 +00003825 }
drh2b3c4af2018-10-30 14:36:21 +00003826 n = fread(zBuf, 16, 1, f);
3827 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){
3828 fclose(f);
3829 return SHELL_OPEN_NORMAL;
3830 }
drh1fa6d9f2018-01-06 21:46:01 +00003831 fseek(f, -25, SEEK_END);
3832 n = fread(zBuf, 25, 1, f);
3833 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
3834 rc = SHELL_OPEN_APPENDVFS;
3835 }else{
3836 fseek(f, -22, SEEK_END);
3837 n = fread(zBuf, 22, 1, f);
3838 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
3839 && zBuf[3]==0x06 ){
3840 rc = SHELL_OPEN_ZIPFILE;
drh1bf208c2018-03-09 21:54:01 +00003841 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
mistachkina3926f42018-05-14 12:23:04 +00003842 rc = SHELL_OPEN_ZIPFILE;
drh1fa6d9f2018-01-06 21:46:01 +00003843 }
3844 }
3845 fclose(f);
3846 return rc;
3847}
3848
drh33746482018-12-13 15:06:26 +00003849#ifdef SQLITE_ENABLE_DESERIALIZE
3850/*
3851** Reconstruct an in-memory database using the output from the "dbtotxt"
3852** program. Read content from the file in p->zDbFilename. If p->zDbFilename
3853** is 0, then read from standard input.
3854*/
3855static unsigned char *readHexDb(ShellState *p, int *pnData){
3856 unsigned char *a = 0;
drh2c8ee022018-12-13 18:59:30 +00003857 int nLine;
drh33746482018-12-13 15:06:26 +00003858 int n = 0;
3859 int pgsz = 0;
3860 int iOffset = 0;
3861 int j, k;
3862 int rc;
3863 FILE *in;
drh3ea557e2019-04-23 15:30:58 +00003864 unsigned int x[16];
drh2c8ee022018-12-13 18:59:30 +00003865 char zLine[1000];
drh33746482018-12-13 15:06:26 +00003866 if( p->zDbFilename ){
3867 in = fopen(p->zDbFilename, "r");
3868 if( in==0 ){
3869 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename);
3870 return 0;
3871 }
drh2c8ee022018-12-13 18:59:30 +00003872 nLine = 0;
drh33746482018-12-13 15:06:26 +00003873 }else{
drh60379d42018-12-13 18:30:01 +00003874 in = p->in;
drh2c8ee022018-12-13 18:59:30 +00003875 nLine = p->lineno;
drh33746482018-12-13 15:06:26 +00003876 }
3877 *pnData = 0;
drh2c8ee022018-12-13 18:59:30 +00003878 nLine++;
drh33746482018-12-13 15:06:26 +00003879 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error;
3880 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz);
3881 if( rc!=2 ) goto readHexDb_error;
3882 if( n<=0 ) goto readHexDb_error;
3883 a = sqlite3_malloc( n );
3884 if( a==0 ){
3885 utf8_printf(stderr, "Out of memory!\n");
3886 goto readHexDb_error;
3887 }
3888 memset(a, 0, n);
3889 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){
3890 utf8_printf(stderr, "invalid pagesize\n");
3891 goto readHexDb_error;
3892 }
drh2c8ee022018-12-13 18:59:30 +00003893 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){
drh33746482018-12-13 15:06:26 +00003894 rc = sscanf(zLine, "| page %d offset %d", &j, &k);
3895 if( rc==2 ){
3896 iOffset = k;
3897 continue;
3898 }
3899 if( strncmp(zLine, "| end ", 6)==0 ){
3900 break;
3901 }
drh3ea557e2019-04-23 15:30:58 +00003902 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x",
drh33746482018-12-13 15:06:26 +00003903 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7],
3904 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]);
3905 if( rc==17 ){
3906 k = iOffset+j;
drhf354e772018-12-13 22:58:52 +00003907 if( k+16<=n ){
drh3ea557e2019-04-23 15:30:58 +00003908 int ii;
3909 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff;
drh33746482018-12-13 15:06:26 +00003910 }
drh33746482018-12-13 15:06:26 +00003911 }
3912 }
3913 *pnData = n;
drh2c8ee022018-12-13 18:59:30 +00003914 if( in!=p->in ){
3915 fclose(in);
3916 }else{
3917 p->lineno = nLine;
3918 }
drh33746482018-12-13 15:06:26 +00003919 return a;
3920
3921readHexDb_error:
3922 if( in!=stdin ){
3923 fclose(in);
3924 }else{
drh60379d42018-12-13 18:30:01 +00003925 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){
drh2c8ee022018-12-13 18:59:30 +00003926 nLine++;
drh33746482018-12-13 15:06:26 +00003927 if(strncmp(zLine, "| end ", 6)==0 ) break;
3928 }
drh2c8ee022018-12-13 18:59:30 +00003929 p->lineno = nLine;
drh33746482018-12-13 15:06:26 +00003930 }
3931 sqlite3_free(a);
3932 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine);
3933 return 0;
3934}
3935#endif /* SQLITE_ENABLE_DESERIALIZE */
3936
danb1825882019-04-23 20:48:32 +00003937/*
dan9c014f82019-04-25 19:23:15 +00003938** Scalar function "shell_int32". The first argument to this function
3939** must be a blob. The second a non-negative integer. This function
3940** reads and returns a 32-bit big-endian integer from byte
3941** offset (4*<arg2>) of the blob.
3942*/
3943static void shellInt32(
3944 sqlite3_context *context,
3945 int argc,
3946 sqlite3_value **argv
3947){
3948 const unsigned char *pBlob;
3949 int nBlob;
3950 int iInt;
3951
3952 nBlob = sqlite3_value_bytes(argv[0]);
3953 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]);
3954 iInt = sqlite3_value_int(argv[1]);
3955
3956 if( iInt>=0 && (iInt+1)*4<=nBlob ){
3957 const unsigned char *a = &pBlob[iInt*4];
3958 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24)
3959 + ((sqlite3_int64)a[1]<<16)
3960 + ((sqlite3_int64)a[2]<< 8)
3961 + ((sqlite3_int64)a[3]<< 0);
3962 sqlite3_result_int64(context, iVal);
3963 }
3964}
3965
3966/*
danb1825882019-04-23 20:48:32 +00003967** Scalar function "shell_escape_crnl" used by the .recover command.
3968** The argument passed to this function is the output of built-in
3969** function quote(). If the first character of the input is "'",
3970** indicating that the value passed to quote() was a text value,
3971** then this function searches the input for "\n" and "\r" characters
3972** and adds a wrapper similar to the following:
3973**
3974** replace(replace(<input>, '\n', char(10), '\r', char(13));
3975**
3976** Or, if the first character of the input is not "'", then a copy
3977** of the input is returned.
3978*/
3979static void shellEscapeCrnl(
3980 sqlite3_context *context,
3981 int argc,
3982 sqlite3_value **argv
3983){
3984 const char *zText = (const char*)sqlite3_value_text(argv[0]);
3985 if( zText[0]=='\'' ){
3986 int nText = sqlite3_value_bytes(argv[0]);
3987 int i;
3988 char zBuf1[20];
3989 char zBuf2[20];
3990 const char *zNL = 0;
3991 const char *zCR = 0;
3992 int nCR = 0;
3993 int nNL = 0;
3994
3995 for(i=0; zText[i]; i++){
3996 if( zNL==0 && zText[i]=='\n' ){
3997 zNL = unused_string(zText, "\\n", "\\012", zBuf1);
3998 nNL = (int)strlen(zNL);
3999 }
4000 if( zCR==0 && zText[i]=='\r' ){
4001 zCR = unused_string(zText, "\\r", "\\015", zBuf2);
4002 nCR = (int)strlen(zCR);
4003 }
4004 }
4005
4006 if( zNL || zCR ){
4007 int iOut = 0;
4008 i64 nMax = (nNL > nCR) ? nNL : nCR;
4009 i64 nAlloc = nMax * nText + (nMax+12)*2;
4010 char *zOut = (char*)sqlite3_malloc64(nAlloc);
4011 if( zOut==0 ){
4012 sqlite3_result_error_nomem(context);
4013 return;
4014 }
4015
4016 if( zNL && zCR ){
4017 memcpy(&zOut[iOut], "replace(replace(", 16);
4018 iOut += 16;
4019 }else{
4020 memcpy(&zOut[iOut], "replace(", 8);
4021 iOut += 8;
4022 }
4023 for(i=0; zText[i]; i++){
4024 if( zText[i]=='\n' ){
4025 memcpy(&zOut[iOut], zNL, nNL);
4026 iOut += nNL;
4027 }else if( zText[i]=='\r' ){
4028 memcpy(&zOut[iOut], zCR, nCR);
4029 iOut += nCR;
4030 }else{
4031 zOut[iOut] = zText[i];
4032 iOut++;
4033 }
4034 }
4035
4036 if( zNL ){
4037 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4038 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL;
4039 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12;
4040 }
4041 if( zCR ){
4042 memcpy(&zOut[iOut], ",'", 2); iOut += 2;
4043 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR;
4044 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12;
4045 }
4046
4047 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT);
4048 sqlite3_free(zOut);
4049 return;
4050 }
4051 }
4052
4053 sqlite3_result_value(context, argv[0]);
4054}
4055
drhbe4ccb22018-05-17 20:04:24 +00004056/* Flags for open_db().
4057**
4058** The default behavior of open_db() is to exit(1) if the database fails to
4059** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
4060** but still returns without calling exit.
4061**
4062** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
4063** ZIP archive if the file does not exist or is empty and its name matches
4064** the *.zip pattern.
4065*/
4066#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
4067#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
4068
drh1fa6d9f2018-01-06 21:46:01 +00004069/*
drh2ce15c32017-07-11 13:34:40 +00004070** Make sure the database is open. If it is not, then open it. If
4071** the database fails to open, print an error message and exit.
4072*/
drhbe4ccb22018-05-17 20:04:24 +00004073static void open_db(ShellState *p, int openFlags){
drh2ce15c32017-07-11 13:34:40 +00004074 if( p->db==0 ){
drhf2072d12018-05-11 15:10:11 +00004075 if( p->openMode==SHELL_OPEN_UNSPEC ){
4076 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
4077 p->openMode = SHELL_OPEN_NORMAL;
drhbe4ccb22018-05-17 20:04:24 +00004078 }else{
4079 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
4080 (openFlags & OPEN_DB_ZIPFILE)!=0);
drhf2072d12018-05-11 15:10:11 +00004081 }
drh1fa6d9f2018-01-06 21:46:01 +00004082 }
4083 switch( p->openMode ){
4084 case SHELL_OPEN_APPENDVFS: {
4085 sqlite3_open_v2(p->zDbFilename, &p->db,
4086 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
4087 break;
4088 }
drh33746482018-12-13 15:06:26 +00004089 case SHELL_OPEN_HEXDB:
drh60f34ae2018-10-30 13:19:49 +00004090 case SHELL_OPEN_DESERIALIZE: {
4091 sqlite3_open(0, &p->db);
4092 break;
4093 }
drh1fa6d9f2018-01-06 21:46:01 +00004094 case SHELL_OPEN_ZIPFILE: {
4095 sqlite3_open(":memory:", &p->db);
4096 break;
4097 }
drhee269a62018-02-14 23:27:43 +00004098 case SHELL_OPEN_READONLY: {
4099 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
4100 break;
4101 }
drh1fa6d9f2018-01-06 21:46:01 +00004102 case SHELL_OPEN_UNSPEC:
4103 case SHELL_OPEN_NORMAL: {
4104 sqlite3_open(p->zDbFilename, &p->db);
4105 break;
4106 }
4107 }
drh2ce15c32017-07-11 13:34:40 +00004108 globalDb = p->db;
4109 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
4110 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
4111 p->zDbFilename, sqlite3_errmsg(p->db));
drhf25cc4f2019-01-04 14:29:21 +00004112 if( openFlags & OPEN_DB_KEEPALIVE ){
4113 sqlite3_open(":memory:", &p->db);
4114 return;
4115 }
drh2ce15c32017-07-11 13:34:40 +00004116 exit(1);
4117 }
4118#ifndef SQLITE_OMIT_LOAD_EXTENSION
4119 sqlite3_enable_load_extension(p->db, 1);
4120#endif
4121 sqlite3_fileio_init(p->db, 0, 0);
4122 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00004123 sqlite3_completion_init(p->db, 0, 0);
dan68cb86e2019-04-20 20:57:28 +00004124 sqlite3_dbdata_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00004125#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00004126 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00004127 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00004128#endif
drhceba7922018-01-01 21:28:25 +00004129 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00004130 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00004131 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
4132 shellModuleSchema, 0, 0);
drh634c70f2018-01-10 16:50:18 +00004133 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
4134 shellPutsFunc, 0, 0);
danb1825882019-04-23 20:48:32 +00004135 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0,
4136 shellEscapeCrnl, 0, 0);
dan9c014f82019-04-25 19:23:15 +00004137 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0,
4138 shellInt32, 0, 0);
drh04a28c32018-01-31 01:38:44 +00004139#ifndef SQLITE_NOHAVE_SYSTEM
drh97913132018-01-11 00:04:00 +00004140 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
4141 editFunc, 0, 0);
4142 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
4143 editFunc, 0, 0);
drh04a28c32018-01-31 01:38:44 +00004144#endif
drh1fa6d9f2018-01-06 21:46:01 +00004145 if( p->openMode==SHELL_OPEN_ZIPFILE ){
4146 char *zSql = sqlite3_mprintf(
4147 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
4148 sqlite3_exec(p->db, zSql, 0, 0, 0);
4149 sqlite3_free(zSql);
drha751f392018-10-30 15:31:22 +00004150 }
4151#ifdef SQLITE_ENABLE_DESERIALIZE
drh33746482018-12-13 15:06:26 +00004152 else
4153 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){
mistachkin99490932018-12-17 22:19:57 +00004154 int rc;
drh60f34ae2018-10-30 13:19:49 +00004155 int nData = 0;
drh33746482018-12-13 15:06:26 +00004156 unsigned char *aData;
4157 if( p->openMode==SHELL_OPEN_DESERIALIZE ){
4158 aData = (unsigned char*)readFile(p->zDbFilename, &nData);
4159 }else{
4160 aData = readHexDb(p, &nData);
4161 if( aData==0 ){
4162 utf8_printf(stderr, "Error in hexdb input\n");
4163 return;
4164 }
4165 }
mistachkin99490932018-12-17 22:19:57 +00004166 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData,
drh60f34ae2018-10-30 13:19:49 +00004167 SQLITE_DESERIALIZE_RESIZEABLE |
4168 SQLITE_DESERIALIZE_FREEONCLOSE);
4169 if( rc ){
4170 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc);
4171 }
drh6ca64482019-01-22 16:06:20 +00004172 if( p->szMax>0 ){
4173 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax);
4174 }
drh1fa6d9f2018-01-06 21:46:01 +00004175 }
drha751f392018-10-30 15:31:22 +00004176#endif
drh2ce15c32017-07-11 13:34:40 +00004177 }
4178}
4179
drh9e804032018-05-18 17:11:50 +00004180/*
4181** Attempt to close the databaes connection. Report errors.
4182*/
4183void close_db(sqlite3 *db){
4184 int rc = sqlite3_close(db);
4185 if( rc ){
4186 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
4187 rc, sqlite3_errmsg(db));
4188 }
4189}
4190
drh56eb09b2017-07-11 13:59:07 +00004191#if HAVE_READLINE || HAVE_EDITLINE
4192/*
4193** Readline completion callbacks
4194*/
4195static char *readline_completion_generator(const char *text, int state){
4196 static sqlite3_stmt *pStmt = 0;
4197 char *zRet;
4198 if( state==0 ){
4199 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00004200 sqlite3_finalize(pStmt);
4201 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4202 " FROM completion(%Q) ORDER BY 1", text);
4203 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4204 sqlite3_free(zSql);
4205 }
4206 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00004207 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00004208 }else{
4209 sqlite3_finalize(pStmt);
4210 pStmt = 0;
4211 zRet = 0;
4212 }
4213 return zRet;
4214}
4215static char **readline_completion(const char *zText, int iStart, int iEnd){
4216 rl_attempted_completion_over = 1;
4217 return rl_completion_matches(zText, readline_completion_generator);
4218}
4219
4220#elif HAVE_LINENOISE
4221/*
4222** Linenoise completion callback
4223*/
4224static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00004225 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00004226 int i, iStart;
4227 sqlite3_stmt *pStmt = 0;
4228 char *zSql;
4229 char zBuf[1000];
4230
4231 if( nLine>sizeof(zBuf)-30 ) return;
drh1615c372018-05-12 23:56:22 +00004232 if( zLine[0]=='.' || zLine[0]=='#') return;
drh56eb09b2017-07-11 13:59:07 +00004233 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4234 if( i==nLine-1 ) return;
4235 iStart = i+1;
4236 memcpy(zBuf, zLine, iStart);
4237 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4238 " FROM completion(%Q,%Q) ORDER BY 1",
4239 &zLine[iStart], zLine);
4240 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4241 sqlite3_free(zSql);
4242 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4243 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4244 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4245 int nCompletion = sqlite3_column_bytes(pStmt, 0);
4246 if( iStart+nCompletion < sizeof(zBuf)-1 ){
4247 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4248 linenoiseAddCompletion(lc, zBuf);
4249 }
4250 }
4251 sqlite3_finalize(pStmt);
4252}
4253#endif
4254
drh2ce15c32017-07-11 13:34:40 +00004255/*
4256** Do C-language style dequoting.
4257**
4258** \a -> alarm
4259** \b -> backspace
4260** \t -> tab
4261** \n -> newline
4262** \v -> vertical tab
4263** \f -> form feed
4264** \r -> carriage return
4265** \s -> space
4266** \" -> "
4267** \' -> '
4268** \\ -> backslash
4269** \NNN -> ascii character NNN in octal
4270*/
4271static void resolve_backslashes(char *z){
4272 int i, j;
4273 char c;
4274 while( *z && *z!='\\' ) z++;
4275 for(i=j=0; (c = z[i])!=0; i++, j++){
4276 if( c=='\\' && z[i+1]!=0 ){
4277 c = z[++i];
4278 if( c=='a' ){
4279 c = '\a';
4280 }else if( c=='b' ){
4281 c = '\b';
4282 }else if( c=='t' ){
4283 c = '\t';
4284 }else if( c=='n' ){
4285 c = '\n';
4286 }else if( c=='v' ){
4287 c = '\v';
4288 }else if( c=='f' ){
4289 c = '\f';
4290 }else if( c=='r' ){
4291 c = '\r';
4292 }else if( c=='"' ){
4293 c = '"';
4294 }else if( c=='\'' ){
4295 c = '\'';
4296 }else if( c=='\\' ){
4297 c = '\\';
4298 }else if( c>='0' && c<='7' ){
4299 c -= '0';
4300 if( z[i+1]>='0' && z[i+1]<='7' ){
4301 i++;
4302 c = (c<<3) + z[i] - '0';
4303 if( z[i+1]>='0' && z[i+1]<='7' ){
4304 i++;
4305 c = (c<<3) + z[i] - '0';
4306 }
4307 }
4308 }
4309 }
4310 z[j] = c;
4311 }
4312 if( j<i ) z[j] = 0;
4313}
4314
4315/*
drh2ce15c32017-07-11 13:34:40 +00004316** Interpret zArg as either an integer or a boolean value. Return 1 or 0
4317** for TRUE and FALSE. Return the integer value if appropriate.
4318*/
4319static int booleanValue(const char *zArg){
4320 int i;
4321 if( zArg[0]=='0' && zArg[1]=='x' ){
4322 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4323 }else{
4324 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4325 }
4326 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4327 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4328 return 1;
4329 }
4330 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4331 return 0;
4332 }
4333 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
4334 zArg);
4335 return 0;
4336}
4337
4338/*
4339** Set or clear a shell flag according to a boolean value.
4340*/
4341static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4342 if( booleanValue(zArg) ){
4343 ShellSetFlag(p, mFlag);
4344 }else{
4345 ShellClearFlag(p, mFlag);
4346 }
4347}
4348
4349/*
4350** Close an output file, assuming it is not stderr or stdout
4351*/
4352static void output_file_close(FILE *f){
4353 if( f && f!=stdout && f!=stderr ) fclose(f);
4354}
4355
4356/*
4357** Try to open an output file. The names "stdout" and "stderr" are
4358** recognized and do the right thing. NULL is returned if the output
4359** filename is "off".
4360*/
drha92a01a2018-01-10 22:15:37 +00004361static FILE *output_file_open(const char *zFile, int bTextMode){
drh2ce15c32017-07-11 13:34:40 +00004362 FILE *f;
4363 if( strcmp(zFile,"stdout")==0 ){
4364 f = stdout;
4365 }else if( strcmp(zFile, "stderr")==0 ){
4366 f = stderr;
4367 }else if( strcmp(zFile, "off")==0 ){
4368 f = 0;
4369 }else{
drha92a01a2018-01-10 22:15:37 +00004370 f = fopen(zFile, bTextMode ? "w" : "wb");
drh2ce15c32017-07-11 13:34:40 +00004371 if( f==0 ){
4372 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
4373 }
4374 }
4375 return f;
4376}
4377
drh707821f2018-12-05 13:39:06 +00004378#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00004379/*
4380** A routine for handling output from sqlite3_trace().
4381*/
4382static int sql_trace_callback(
drh707821f2018-12-05 13:39:06 +00004383 unsigned mType, /* The trace type */
4384 void *pArg, /* The ShellState pointer */
4385 void *pP, /* Usually a pointer to sqlite_stmt */
4386 void *pX /* Auxiliary output */
drh2ce15c32017-07-11 13:34:40 +00004387){
drh707821f2018-12-05 13:39:06 +00004388 ShellState *p = (ShellState*)pArg;
4389 sqlite3_stmt *pStmt;
4390 const char *zSql;
4391 int nSql;
4392 if( p->traceOut==0 ) return 0;
4393 if( mType==SQLITE_TRACE_CLOSE ){
4394 utf8_printf(p->traceOut, "-- closing database connection\n");
4395 return 0;
4396 }
4397 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){
4398 zSql = (const char*)pX;
4399 }else{
4400 pStmt = (sqlite3_stmt*)pP;
4401 switch( p->eTraceType ){
4402 case SHELL_TRACE_EXPANDED: {
4403 zSql = sqlite3_expanded_sql(pStmt);
4404 break;
4405 }
4406#ifdef SQLITE_ENABLE_NORMALIZE
4407 case SHELL_TRACE_NORMALIZED: {
4408 zSql = sqlite3_normalized_sql(pStmt);
4409 break;
4410 }
4411#endif
4412 default: {
4413 zSql = sqlite3_sql(pStmt);
4414 break;
4415 }
4416 }
4417 }
4418 if( zSql==0 ) return 0;
4419 nSql = strlen30(zSql);
4420 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; }
4421 switch( mType ){
4422 case SQLITE_TRACE_ROW:
4423 case SQLITE_TRACE_STMT: {
4424 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql);
4425 break;
4426 }
4427 case SQLITE_TRACE_PROFILE: {
4428 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX;
4429 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec);
4430 break;
4431 }
drh2ce15c32017-07-11 13:34:40 +00004432 }
4433 return 0;
4434}
4435#endif
drh2ce15c32017-07-11 13:34:40 +00004436
4437/*
4438** A no-op routine that runs with the ".breakpoint" doc-command. This is
4439** a useful spot to set a debugger breakpoint.
4440*/
4441static void test_breakpoint(void){
4442 static int nCall = 0;
4443 nCall++;
4444}
4445
4446/*
4447** An object used to read a CSV and other files for import.
4448*/
4449typedef struct ImportCtx ImportCtx;
4450struct ImportCtx {
4451 const char *zFile; /* Name of the input file */
4452 FILE *in; /* Read the CSV text from this input stream */
4453 char *z; /* Accumulated text for a field */
4454 int n; /* Number of bytes in z */
4455 int nAlloc; /* Space allocated for z[] */
4456 int nLine; /* Current line number */
4457 int bNotFirst; /* True if one or more bytes already read */
4458 int cTerm; /* Character that terminated the most recent field */
4459 int cColSep; /* The column separator character. (Usually ",") */
4460 int cRowSep; /* The row separator character. (Usually "\n") */
4461};
4462
4463/* Append a single byte to z[] */
4464static void import_append_char(ImportCtx *p, int c){
4465 if( p->n+1>=p->nAlloc ){
4466 p->nAlloc += p->nAlloc + 100;
4467 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drh4b5345c2018-04-24 13:07:40 +00004468 if( p->z==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004469 }
4470 p->z[p->n++] = (char)c;
4471}
4472
4473/* Read a single field of CSV text. Compatible with rfc4180 and extended
4474** with the option of having a separator other than ",".
4475**
4476** + Input comes from p->in.
4477** + Store results in p->z of length p->n. Space to hold p->z comes
4478** from sqlite3_malloc64().
4479** + Use p->cSep as the column separator. The default is ",".
4480** + Use p->rSep as the row separator. The default is "\n".
4481** + Keep track of the line number in p->nLine.
4482** + Store the character that terminates the field in p->cTerm. Store
4483** EOF on end-of-file.
4484** + Report syntax errors on stderr
4485*/
4486static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
4487 int c;
4488 int cSep = p->cColSep;
4489 int rSep = p->cRowSep;
4490 p->n = 0;
4491 c = fgetc(p->in);
4492 if( c==EOF || seenInterrupt ){
4493 p->cTerm = EOF;
4494 return 0;
4495 }
4496 if( c=='"' ){
4497 int pc, ppc;
4498 int startLine = p->nLine;
4499 int cQuote = c;
4500 pc = ppc = 0;
4501 while( 1 ){
4502 c = fgetc(p->in);
4503 if( c==rSep ) p->nLine++;
4504 if( c==cQuote ){
4505 if( pc==cQuote ){
4506 pc = 0;
4507 continue;
4508 }
4509 }
4510 if( (c==cSep && pc==cQuote)
4511 || (c==rSep && pc==cQuote)
4512 || (c==rSep && pc=='\r' && ppc==cQuote)
4513 || (c==EOF && pc==cQuote)
4514 ){
4515 do{ p->n--; }while( p->z[p->n]!=cQuote );
4516 p->cTerm = c;
4517 break;
4518 }
4519 if( pc==cQuote && c!='\r' ){
4520 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
4521 p->zFile, p->nLine, cQuote);
4522 }
4523 if( c==EOF ){
4524 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
4525 p->zFile, startLine, cQuote);
4526 p->cTerm = c;
4527 break;
4528 }
4529 import_append_char(p, c);
4530 ppc = pc;
4531 pc = c;
4532 }
4533 }else{
4534 /* If this is the first field being parsed and it begins with the
4535 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4536 if( (c&0xff)==0xef && p->bNotFirst==0 ){
4537 import_append_char(p, c);
4538 c = fgetc(p->in);
4539 if( (c&0xff)==0xbb ){
4540 import_append_char(p, c);
4541 c = fgetc(p->in);
4542 if( (c&0xff)==0xbf ){
4543 p->bNotFirst = 1;
4544 p->n = 0;
4545 return csv_read_one_field(p);
4546 }
4547 }
4548 }
4549 while( c!=EOF && c!=cSep && c!=rSep ){
4550 import_append_char(p, c);
4551 c = fgetc(p->in);
4552 }
4553 if( c==rSep ){
4554 p->nLine++;
4555 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
4556 }
4557 p->cTerm = c;
4558 }
4559 if( p->z ) p->z[p->n] = 0;
4560 p->bNotFirst = 1;
4561 return p->z;
4562}
4563
4564/* Read a single field of ASCII delimited text.
4565**
4566** + Input comes from p->in.
4567** + Store results in p->z of length p->n. Space to hold p->z comes
4568** from sqlite3_malloc64().
4569** + Use p->cSep as the column separator. The default is "\x1F".
4570** + Use p->rSep as the row separator. The default is "\x1E".
4571** + Keep track of the row number in p->nLine.
4572** + Store the character that terminates the field in p->cTerm. Store
4573** EOF on end-of-file.
4574** + Report syntax errors on stderr
4575*/
4576static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
4577 int c;
4578 int cSep = p->cColSep;
4579 int rSep = p->cRowSep;
4580 p->n = 0;
4581 c = fgetc(p->in);
4582 if( c==EOF || seenInterrupt ){
4583 p->cTerm = EOF;
4584 return 0;
4585 }
4586 while( c!=EOF && c!=cSep && c!=rSep ){
4587 import_append_char(p, c);
4588 c = fgetc(p->in);
4589 }
4590 if( c==rSep ){
4591 p->nLine++;
4592 }
4593 p->cTerm = c;
4594 if( p->z ) p->z[p->n] = 0;
4595 return p->z;
4596}
4597
4598/*
4599** Try to transfer data for table zTable. If an error is seen while
4600** moving forward, try to go backwards. The backwards movement won't
4601** work for WITHOUT ROWID tables.
4602*/
4603static void tryToCloneData(
4604 ShellState *p,
4605 sqlite3 *newDb,
4606 const char *zTable
4607){
4608 sqlite3_stmt *pQuery = 0;
4609 sqlite3_stmt *pInsert = 0;
4610 char *zQuery = 0;
4611 char *zInsert = 0;
4612 int rc;
4613 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00004614 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00004615 int k = 0;
4616 int cnt = 0;
4617 const int spinRate = 10000;
4618
4619 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4620 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4621 if( rc ){
4622 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4623 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4624 zQuery);
4625 goto end_data_xfer;
4626 }
4627 n = sqlite3_column_count(pQuery);
4628 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh4b5345c2018-04-24 13:07:40 +00004629 if( zInsert==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00004630 sqlite3_snprintf(200+nTable,zInsert,
4631 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00004632 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00004633 for(j=1; j<n; j++){
4634 memcpy(zInsert+i, ",?", 2);
4635 i += 2;
4636 }
4637 memcpy(zInsert+i, ");", 3);
4638 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4639 if( rc ){
4640 utf8_printf(stderr, "Error %d: %s on [%s]\n",
4641 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4642 zQuery);
4643 goto end_data_xfer;
4644 }
4645 for(k=0; k<2; k++){
4646 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4647 for(i=0; i<n; i++){
4648 switch( sqlite3_column_type(pQuery, i) ){
4649 case SQLITE_NULL: {
4650 sqlite3_bind_null(pInsert, i+1);
4651 break;
4652 }
4653 case SQLITE_INTEGER: {
4654 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4655 break;
4656 }
4657 case SQLITE_FLOAT: {
4658 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4659 break;
4660 }
4661 case SQLITE_TEXT: {
4662 sqlite3_bind_text(pInsert, i+1,
4663 (const char*)sqlite3_column_text(pQuery,i),
4664 -1, SQLITE_STATIC);
4665 break;
4666 }
4667 case SQLITE_BLOB: {
4668 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4669 sqlite3_column_bytes(pQuery,i),
4670 SQLITE_STATIC);
4671 break;
4672 }
4673 }
4674 } /* End for */
4675 rc = sqlite3_step(pInsert);
4676 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
4677 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
4678 sqlite3_errmsg(newDb));
4679 }
4680 sqlite3_reset(pInsert);
4681 cnt++;
4682 if( (cnt%spinRate)==0 ){
4683 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4684 fflush(stdout);
4685 }
4686 } /* End while */
4687 if( rc==SQLITE_DONE ) break;
4688 sqlite3_finalize(pQuery);
4689 sqlite3_free(zQuery);
4690 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4691 zTable);
4692 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4693 if( rc ){
4694 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
4695 break;
4696 }
4697 } /* End for(k=0...) */
4698
4699end_data_xfer:
4700 sqlite3_finalize(pQuery);
4701 sqlite3_finalize(pInsert);
4702 sqlite3_free(zQuery);
4703 sqlite3_free(zInsert);
4704}
4705
4706
4707/*
4708** Try to transfer all rows of the schema that match zWhere. For
4709** each row, invoke xForEach() on the object defined by that row.
4710** If an error is encountered while moving forward through the
4711** sqlite_master table, try again moving backwards.
4712*/
4713static void tryToCloneSchema(
4714 ShellState *p,
4715 sqlite3 *newDb,
4716 const char *zWhere,
4717 void (*xForEach)(ShellState*,sqlite3*,const char*)
4718){
4719 sqlite3_stmt *pQuery = 0;
4720 char *zQuery = 0;
4721 int rc;
4722 const unsigned char *zName;
4723 const unsigned char *zSql;
4724 char *zErrMsg = 0;
4725
4726 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4727 " WHERE %s", zWhere);
4728 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4729 if( rc ){
4730 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4731 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4732 zQuery);
4733 goto end_schema_xfer;
4734 }
4735 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4736 zName = sqlite3_column_text(pQuery, 0);
4737 zSql = sqlite3_column_text(pQuery, 1);
4738 printf("%s... ", zName); fflush(stdout);
4739 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4740 if( zErrMsg ){
4741 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4742 sqlite3_free(zErrMsg);
4743 zErrMsg = 0;
4744 }
4745 if( xForEach ){
4746 xForEach(p, newDb, (const char*)zName);
4747 }
4748 printf("done\n");
4749 }
4750 if( rc!=SQLITE_DONE ){
4751 sqlite3_finalize(pQuery);
4752 sqlite3_free(zQuery);
4753 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4754 " WHERE %s ORDER BY rowid DESC", zWhere);
4755 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4756 if( rc ){
4757 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
4758 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4759 zQuery);
4760 goto end_schema_xfer;
4761 }
4762 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4763 zName = sqlite3_column_text(pQuery, 0);
4764 zSql = sqlite3_column_text(pQuery, 1);
4765 printf("%s... ", zName); fflush(stdout);
4766 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4767 if( zErrMsg ){
4768 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
4769 sqlite3_free(zErrMsg);
4770 zErrMsg = 0;
4771 }
4772 if( xForEach ){
4773 xForEach(p, newDb, (const char*)zName);
4774 }
4775 printf("done\n");
4776 }
4777 }
4778end_schema_xfer:
4779 sqlite3_finalize(pQuery);
4780 sqlite3_free(zQuery);
4781}
4782
4783/*
4784** Open a new database file named "zNewDb". Try to recover as much information
4785** as possible out of the main database (which might be corrupt) and write it
4786** into zNewDb.
4787*/
4788static void tryToClone(ShellState *p, const char *zNewDb){
4789 int rc;
4790 sqlite3 *newDb = 0;
4791 if( access(zNewDb,0)==0 ){
4792 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
4793 return;
4794 }
4795 rc = sqlite3_open(zNewDb, &newDb);
4796 if( rc ){
4797 utf8_printf(stderr, "Cannot create output database: %s\n",
4798 sqlite3_errmsg(newDb));
4799 }else{
4800 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
4801 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
4802 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4803 tryToCloneSchema(p, newDb, "type!='table'", 0);
4804 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
4805 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4806 }
drh9e804032018-05-18 17:11:50 +00004807 close_db(newDb);
drh2ce15c32017-07-11 13:34:40 +00004808}
4809
4810/*
drh13c20932018-01-10 21:41:55 +00004811** Change the output file back to stdout.
4812**
4813** If the p->doXdgOpen flag is set, that means the output was being
4814** redirected to a temporary file named by p->zTempFile. In that case,
4815** launch start/open/xdg-open on that temporary file.
drh2ce15c32017-07-11 13:34:40 +00004816*/
4817static void output_reset(ShellState *p){
4818 if( p->outfile[0]=='|' ){
4819#ifndef SQLITE_OMIT_POPEN
4820 pclose(p->out);
4821#endif
4822 }else{
4823 output_file_close(p->out);
drh04a28c32018-01-31 01:38:44 +00004824#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00004825 if( p->doXdgOpen ){
4826 const char *zXdgOpenCmd =
4827#if defined(_WIN32)
4828 "start";
4829#elif defined(__APPLE__)
4830 "open";
4831#else
4832 "xdg-open";
4833#endif
4834 char *zCmd;
4835 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
drha92a01a2018-01-10 22:15:37 +00004836 if( system(zCmd) ){
4837 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
4838 }
drh13c20932018-01-10 21:41:55 +00004839 sqlite3_free(zCmd);
drh3c484e82018-01-10 22:27:21 +00004840 outputModePop(p);
drh13c20932018-01-10 21:41:55 +00004841 p->doXdgOpen = 0;
4842 }
drh04a28c32018-01-31 01:38:44 +00004843#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00004844 }
4845 p->outfile[0] = 0;
4846 p->out = stdout;
4847}
4848
4849/*
4850** Run an SQL command and return the single integer result.
4851*/
4852static int db_int(ShellState *p, const char *zSql){
4853 sqlite3_stmt *pStmt;
4854 int res = 0;
4855 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4856 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4857 res = sqlite3_column_int(pStmt,0);
4858 }
4859 sqlite3_finalize(pStmt);
4860 return res;
4861}
4862
4863/*
4864** Convert a 2-byte or 4-byte big-endian integer into a native integer
4865*/
4866static unsigned int get2byteInt(unsigned char *a){
4867 return (a[0]<<8) + a[1];
4868}
4869static unsigned int get4byteInt(unsigned char *a){
4870 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4871}
4872
4873/*
4874** Implementation of the ".info" command.
4875**
4876** Return 1 on error, 2 to exit, and 0 otherwise.
4877*/
4878static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
4879 static const struct { const char *zName; int ofst; } aField[] = {
4880 { "file change counter:", 24 },
4881 { "database page count:", 28 },
4882 { "freelist page count:", 36 },
4883 { "schema cookie:", 40 },
4884 { "schema format:", 44 },
4885 { "default cache size:", 48 },
4886 { "autovacuum top root:", 52 },
4887 { "incremental vacuum:", 64 },
4888 { "text encoding:", 56 },
4889 { "user version:", 60 },
4890 { "application id:", 68 },
4891 { "software version:", 96 },
4892 };
4893 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4894 { "number of tables:",
4895 "SELECT count(*) FROM %s WHERE type='table'" },
4896 { "number of indexes:",
4897 "SELECT count(*) FROM %s WHERE type='index'" },
4898 { "number of triggers:",
4899 "SELECT count(*) FROM %s WHERE type='trigger'" },
4900 { "number of views:",
4901 "SELECT count(*) FROM %s WHERE type='view'" },
4902 { "schema size:",
4903 "SELECT total(length(sql)) FROM %s" },
4904 };
drh87c889c2019-03-20 18:22:51 +00004905 int i, rc;
drhea99a312018-07-18 19:09:07 +00004906 unsigned iDataVersion;
drh2ce15c32017-07-11 13:34:40 +00004907 char *zSchemaTab;
4908 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004909 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00004910 unsigned char aHdr[100];
4911 open_db(p, 0);
4912 if( p->db==0 ) return 1;
drh87c889c2019-03-20 18:22:51 +00004913 rc = sqlite3_prepare_v2(p->db,
4914 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4915 -1, &pStmt, 0);
4916 if( rc ){
4917 if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){
4918 utf8_printf(stderr, "the \".dbinfo\" command requires the "
4919 "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n");
4920 }else{
4921 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
4922 }
4923 sqlite3_finalize(pStmt);
4924 return 1;
4925 }
drh512e6c32017-10-11 17:51:08 +00004926 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4927 if( sqlite3_step(pStmt)==SQLITE_ROW
4928 && sqlite3_column_bytes(pStmt,0)>100
4929 ){
4930 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4931 sqlite3_finalize(pStmt);
4932 }else{
drh2ce15c32017-07-11 13:34:40 +00004933 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004934 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00004935 return 1;
4936 }
4937 i = get2byteInt(aHdr+16);
4938 if( i==1 ) i = 65536;
4939 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4940 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4941 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4942 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
4943 for(i=0; i<ArraySize(aField); i++){
4944 int ofst = aField[i].ofst;
4945 unsigned int val = get4byteInt(aHdr + ofst);
4946 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
4947 switch( ofst ){
4948 case 56: {
4949 if( val==1 ) raw_printf(p->out, " (utf8)");
4950 if( val==2 ) raw_printf(p->out, " (utf16le)");
4951 if( val==3 ) raw_printf(p->out, " (utf16be)");
4952 }
4953 }
4954 raw_printf(p->out, "\n");
4955 }
4956 if( zDb==0 ){
4957 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4958 }else if( strcmp(zDb,"temp")==0 ){
4959 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4960 }else{
4961 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4962 }
4963 for(i=0; i<ArraySize(aQuery); i++){
4964 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4965 int val = db_int(p, zSql);
4966 sqlite3_free(zSql);
4967 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
4968 }
4969 sqlite3_free(zSchemaTab);
drhea99a312018-07-18 19:09:07 +00004970 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
4971 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
drh2ce15c32017-07-11 13:34:40 +00004972 return 0;
4973}
4974
4975/*
4976** Print the current sqlite3_errmsg() value to stderr and return 1.
4977*/
4978static int shellDatabaseError(sqlite3 *db){
4979 const char *zErr = sqlite3_errmsg(db);
4980 utf8_printf(stderr, "Error: %s\n", zErr);
4981 return 1;
4982}
4983
4984/*
drh2ce15c32017-07-11 13:34:40 +00004985** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4986** if they match and FALSE (0) if they do not match.
4987**
4988** Globbing rules:
4989**
4990** '*' Matches any sequence of zero or more characters.
4991**
4992** '?' Matches exactly one character.
4993**
4994** [...] Matches one character from the enclosed list of
4995** characters.
4996**
4997** [^...] Matches one character not in the enclosed list.
4998**
4999** '#' Matches any sequence of one or more digits with an
5000** optional + or - sign in front
5001**
5002** ' ' Any span of whitespace matches any other span of
5003** whitespace.
5004**
5005** Extra whitespace at the end of z[] is ignored.
5006*/
5007static int testcase_glob(const char *zGlob, const char *z){
5008 int c, c2;
5009 int invert;
5010 int seen;
5011
5012 while( (c = (*(zGlob++)))!=0 ){
5013 if( IsSpace(c) ){
5014 if( !IsSpace(*z) ) return 0;
5015 while( IsSpace(*zGlob) ) zGlob++;
5016 while( IsSpace(*z) ) z++;
5017 }else if( c=='*' ){
5018 while( (c=(*(zGlob++))) == '*' || c=='?' ){
5019 if( c=='?' && (*(z++))==0 ) return 0;
5020 }
5021 if( c==0 ){
5022 return 1;
5023 }else if( c=='[' ){
5024 while( *z && testcase_glob(zGlob-1,z)==0 ){
5025 z++;
5026 }
5027 return (*z)!=0;
5028 }
5029 while( (c2 = (*(z++)))!=0 ){
5030 while( c2!=c ){
5031 c2 = *(z++);
5032 if( c2==0 ) return 0;
5033 }
5034 if( testcase_glob(zGlob,z) ) return 1;
5035 }
5036 return 0;
5037 }else if( c=='?' ){
5038 if( (*(z++))==0 ) return 0;
5039 }else if( c=='[' ){
5040 int prior_c = 0;
5041 seen = 0;
5042 invert = 0;
5043 c = *(z++);
5044 if( c==0 ) return 0;
5045 c2 = *(zGlob++);
5046 if( c2=='^' ){
5047 invert = 1;
5048 c2 = *(zGlob++);
5049 }
5050 if( c2==']' ){
5051 if( c==']' ) seen = 1;
5052 c2 = *(zGlob++);
5053 }
5054 while( c2 && c2!=']' ){
5055 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5056 c2 = *(zGlob++);
5057 if( c>=prior_c && c<=c2 ) seen = 1;
5058 prior_c = 0;
5059 }else{
5060 if( c==c2 ){
5061 seen = 1;
5062 }
5063 prior_c = c2;
5064 }
5065 c2 = *(zGlob++);
5066 }
5067 if( c2==0 || (seen ^ invert)==0 ) return 0;
5068 }else if( c=='#' ){
5069 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5070 if( !IsDigit(z[0]) ) return 0;
5071 z++;
5072 while( IsDigit(z[0]) ){ z++; }
5073 }else{
5074 if( c!=(*(z++)) ) return 0;
5075 }
5076 }
5077 while( IsSpace(*z) ){ z++; }
5078 return *z==0;
5079}
5080
5081
5082/*
5083** Compare the string as a command-line option with either one or two
5084** initial "-" characters.
5085*/
5086static int optionMatch(const char *zStr, const char *zOpt){
5087 if( zStr[0]!='-' ) return 0;
5088 zStr++;
5089 if( zStr[0]=='-' ) zStr++;
5090 return strcmp(zStr, zOpt)==0;
5091}
5092
5093/*
5094** Delete a file.
5095*/
5096int shellDeleteFile(const char *zFilename){
5097 int rc;
5098#ifdef _WIN32
5099 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
5100 rc = _wunlink(z);
5101 sqlite3_free(z);
5102#else
5103 rc = unlink(zFilename);
5104#endif
5105 return rc;
5106}
5107
drh13c20932018-01-10 21:41:55 +00005108/*
5109** Try to delete the temporary file (if there is one) and free the
5110** memory used to hold the name of the temp file.
5111*/
5112static void clearTempFile(ShellState *p){
5113 if( p->zTempFile==0 ) return;
drh536c3452018-01-11 00:38:39 +00005114 if( p->doXdgOpen ) return;
drh13c20932018-01-10 21:41:55 +00005115 if( shellDeleteFile(p->zTempFile) ) return;
5116 sqlite3_free(p->zTempFile);
5117 p->zTempFile = 0;
5118}
5119
5120/*
5121** Create a new temp file name with the given suffix.
5122*/
5123static void newTempFile(ShellState *p, const char *zSuffix){
5124 clearTempFile(p);
5125 sqlite3_free(p->zTempFile);
5126 p->zTempFile = 0;
drh7f3bf8a2018-01-10 21:50:08 +00005127 if( p->db ){
5128 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
5129 }
drh13c20932018-01-10 21:41:55 +00005130 if( p->zTempFile==0 ){
5131 sqlite3_uint64 r;
5132 sqlite3_randomness(sizeof(r), &r);
5133 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
5134 }else{
5135 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
5136 }
5137 if( p->zTempFile==0 ){
5138 raw_printf(stderr, "out of memory\n");
5139 exit(1);
5140 }
5141}
5142
drh2ce15c32017-07-11 13:34:40 +00005143
5144/*
5145** The implementation of SQL scalar function fkey_collate_clause(), used
5146** by the ".lint fkey-indexes" command. This scalar function is always
5147** called with four arguments - the parent table name, the parent column name,
5148** the child table name and the child column name.
5149**
5150** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5151**
5152** If either of the named tables or columns do not exist, this function
5153** returns an empty string. An empty string is also returned if both tables
5154** and columns exist but have the same default collation sequence. Or,
5155** if both exist but the default collation sequences are different, this
5156** function returns the string " COLLATE <parent-collation>", where
5157** <parent-collation> is the default collation sequence of the parent column.
5158*/
5159static void shellFkeyCollateClause(
5160 sqlite3_context *pCtx,
5161 int nVal,
5162 sqlite3_value **apVal
5163){
5164 sqlite3 *db = sqlite3_context_db_handle(pCtx);
5165 const char *zParent;
5166 const char *zParentCol;
5167 const char *zParentSeq;
5168 const char *zChild;
5169 const char *zChildCol;
5170 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
5171 int rc;
5172
5173 assert( nVal==4 );
5174 zParent = (const char*)sqlite3_value_text(apVal[0]);
5175 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5176 zChild = (const char*)sqlite3_value_text(apVal[2]);
5177 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5178
5179 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5180 rc = sqlite3_table_column_metadata(
5181 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5182 );
5183 if( rc==SQLITE_OK ){
5184 rc = sqlite3_table_column_metadata(
5185 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5186 );
5187 }
5188
5189 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5190 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5191 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5192 sqlite3_free(z);
5193 }
5194}
5195
5196
5197/*
5198** The implementation of dot-command ".lint fkey-indexes".
5199*/
5200static int lintFkeyIndexes(
5201 ShellState *pState, /* Current shell tool state */
5202 char **azArg, /* Array of arguments passed to dot command */
5203 int nArg /* Number of entries in azArg[] */
5204){
5205 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
5206 FILE *out = pState->out; /* Stream to write non-error output to */
5207 int bVerbose = 0; /* If -verbose is present */
5208 int bGroupByParent = 0; /* If -groupbyparent is present */
5209 int i; /* To iterate through azArg[] */
5210 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
5211 int rc; /* Return code */
5212 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
5213
5214 /*
5215 ** This SELECT statement returns one row for each foreign key constraint
5216 ** in the schema of the main database. The column values are:
5217 **
5218 ** 0. The text of an SQL statement similar to:
5219 **
danf9679312017-12-01 18:40:18 +00005220 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00005221 **
danf9679312017-12-01 18:40:18 +00005222 ** This SELECT is similar to the one that the foreign keys implementation
5223 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00005224 ** be used to optimize this query, then it can also be used by the FK
5225 ** implementation to optimize DELETE or UPDATE statements on the parent
5226 ** table.
5227 **
5228 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5229 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5230 ** contains an index that can be used to optimize the query.
5231 **
5232 ** 2. Human readable text that describes the child table and columns. e.g.
5233 **
5234 ** "child_table(child_key1, child_key2)"
5235 **
5236 ** 3. Human readable text that describes the parent table and columns. e.g.
5237 **
5238 ** "parent_table(parent_key1, parent_key2)"
5239 **
5240 ** 4. A full CREATE INDEX statement for an index that could be used to
5241 ** optimize DELETE or UPDATE statements on the parent table. e.g.
5242 **
5243 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
5244 **
5245 ** 5. The name of the parent table.
5246 **
5247 ** These six values are used by the C logic below to generate the report.
5248 */
5249 const char *zSql =
5250 "SELECT "
danf9679312017-12-01 18:40:18 +00005251 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00005252 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
5253 " || fkey_collate_clause("
5254 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
5255 ", "
5256 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
5257 " || group_concat('*=?', ' AND ') || ')'"
5258 ", "
5259 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
5260 ", "
5261 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
5262 ", "
5263 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5264 " || ' ON ' || quote(s.name) || '('"
5265 " || group_concat(quote(f.[from]) ||"
5266 " fkey_collate_clause("
5267 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
5268 " || ');'"
5269 ", "
5270 " f.[table] "
5271 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
5272 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
5273 "GROUP BY s.name, f.id "
5274 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
5275 ;
5276 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
5277
5278 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00005279 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00005280 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5281 bVerbose = 1;
5282 }
5283 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5284 bGroupByParent = 1;
5285 zIndent = " ";
5286 }
5287 else{
5288 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5289 azArg[0], azArg[1]
5290 );
5291 return SQLITE_ERROR;
5292 }
5293 }
5294
5295 /* Register the fkey_collate_clause() SQL function */
5296 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5297 0, shellFkeyCollateClause, 0, 0
5298 );
5299
5300
5301 if( rc==SQLITE_OK ){
5302 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5303 }
5304 if( rc==SQLITE_OK ){
5305 sqlite3_bind_int(pSql, 1, bGroupByParent);
5306 }
5307
5308 if( rc==SQLITE_OK ){
5309 int rc2;
5310 char *zPrev = 0;
5311 while( SQLITE_ROW==sqlite3_step(pSql) ){
5312 int res = -1;
5313 sqlite3_stmt *pExplain = 0;
5314 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5315 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5316 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5317 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5318 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
5319 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
5320
5321 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5322 if( rc!=SQLITE_OK ) break;
5323 if( SQLITE_ROW==sqlite3_step(pExplain) ){
5324 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
5325 res = (
5326 0==sqlite3_strglob(zGlob, zPlan)
5327 || 0==sqlite3_strglob(zGlobIPK, zPlan)
5328 );
5329 }
5330 rc = sqlite3_finalize(pExplain);
5331 if( rc!=SQLITE_OK ) break;
5332
5333 if( res<0 ){
5334 raw_printf(stderr, "Error: internal error");
5335 break;
5336 }else{
5337 if( bGroupByParent
5338 && (bVerbose || res==0)
5339 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
5340 ){
5341 raw_printf(out, "-- Parent table %s\n", zParent);
5342 sqlite3_free(zPrev);
5343 zPrev = sqlite3_mprintf("%s", zParent);
5344 }
5345
5346 if( res==0 ){
5347 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5348 }else if( bVerbose ){
5349 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
5350 zIndent, zFrom, zTarget
5351 );
5352 }
5353 }
5354 }
5355 sqlite3_free(zPrev);
5356
5357 if( rc!=SQLITE_OK ){
5358 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5359 }
5360
5361 rc2 = sqlite3_finalize(pSql);
5362 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5363 rc = rc2;
5364 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5365 }
5366 }else{
5367 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5368 }
5369
5370 return rc;
5371}
5372
5373/*
5374** Implementation of ".lint" dot command.
5375*/
5376static int lintDotCommand(
5377 ShellState *pState, /* Current shell tool state */
5378 char **azArg, /* Array of arguments passed to dot command */
5379 int nArg /* Number of entries in azArg[] */
5380){
5381 int n;
drhaf2770f2018-01-05 14:55:43 +00005382 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00005383 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5384 return lintFkeyIndexes(pState, azArg, nArg);
5385
5386 usage:
5387 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5388 raw_printf(stderr, "Where sub-commands are:\n");
5389 raw_printf(stderr, " fkey-indexes\n");
5390 return SQLITE_ERROR;
5391}
5392
drhe37c0e12018-01-06 19:19:50 +00005393#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5394/*********************************************************************************
5395** The ".archive" or ".ar" command.
5396*/
danfd0245d2017-12-07 15:44:29 +00005397static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00005398 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00005399 int *pRc,
5400 const char *zSql,
5401 sqlite3_stmt **ppStmt
5402){
5403 *ppStmt = 0;
5404 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00005405 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00005406 if( rc!=SQLITE_OK ){
5407 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00005408 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00005409 );
5410 *pRc = rc;
5411 }
5412 }
5413}
5414
danac15e2d2017-12-14 19:15:07 +00005415static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00005416 sqlite3 *db,
5417 int *pRc,
danac15e2d2017-12-14 19:15:07 +00005418 sqlite3_stmt **ppStmt,
5419 const char *zFmt,
5420 ...
dan3f67ddf2017-12-13 20:04:53 +00005421){
danac15e2d2017-12-14 19:15:07 +00005422 *ppStmt = 0;
5423 if( *pRc==SQLITE_OK ){
5424 va_list ap;
5425 char *z;
5426 va_start(ap, zFmt);
5427 z = sqlite3_vmprintf(zFmt, ap);
drh1dbb1472018-10-11 10:37:24 +00005428 va_end(ap);
dan3f67ddf2017-12-13 20:04:53 +00005429 if( z==0 ){
5430 *pRc = SQLITE_NOMEM;
5431 }else{
5432 shellPrepare(db, pRc, z, ppStmt);
5433 sqlite3_free(z);
5434 }
dan3f67ddf2017-12-13 20:04:53 +00005435 }
5436}
5437
danfd0245d2017-12-07 15:44:29 +00005438static void shellFinalize(
5439 int *pRc,
5440 sqlite3_stmt *pStmt
5441){
dan25c12182017-12-07 21:03:33 +00005442 if( pStmt ){
5443 sqlite3 *db = sqlite3_db_handle(pStmt);
5444 int rc = sqlite3_finalize(pStmt);
5445 if( *pRc==SQLITE_OK ){
5446 if( rc!=SQLITE_OK ){
5447 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5448 }
5449 *pRc = rc;
5450 }
5451 }
danfd0245d2017-12-07 15:44:29 +00005452}
5453
5454static void shellReset(
5455 int *pRc,
5456 sqlite3_stmt *pStmt
5457){
5458 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00005459 if( *pRc==SQLITE_OK ){
5460 if( rc!=SQLITE_OK ){
5461 sqlite3 *db = sqlite3_db_handle(pStmt);
5462 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
5463 }
5464 *pRc = rc;
5465 }
danfd0245d2017-12-07 15:44:29 +00005466}
drhe37c0e12018-01-06 19:19:50 +00005467/*
dan88be0202017-12-09 17:58:02 +00005468** Structure representing a single ".ar" command.
5469*/
5470typedef struct ArCommand ArCommand;
5471struct ArCommand {
drhb376b3d2018-01-10 13:11:51 +00005472 u8 eCmd; /* An AR_CMD_* value */
5473 u8 bVerbose; /* True if --verbose */
drha5676c42018-01-10 15:17:34 +00005474 u8 bZip; /* True if the archive is a ZIP */
drhb376b3d2018-01-10 13:11:51 +00005475 u8 bDryRun; /* True if --dry-run */
drha5676c42018-01-10 15:17:34 +00005476 u8 bAppend; /* True if --append */
drhd0f9cdc2018-05-17 14:09:06 +00005477 u8 fromCmdLine; /* Run from -A instead of .archive */
drhb376b3d2018-01-10 13:11:51 +00005478 int nArg; /* Number of command arguments */
drha5676c42018-01-10 15:17:34 +00005479 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
dan88be0202017-12-09 17:58:02 +00005480 const char *zFile; /* --file argument, or NULL */
5481 const char *zDir; /* --directory argument, or NULL */
dan88be0202017-12-09 17:58:02 +00005482 char **azArg; /* Array of command arguments */
drhb376b3d2018-01-10 13:11:51 +00005483 ShellState *p; /* Shell state */
5484 sqlite3 *db; /* Database containing the archive */
dan88be0202017-12-09 17:58:02 +00005485};
5486
5487/*
5488** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5489*/
dan0d0547f2017-12-14 15:40:42 +00005490static int arUsage(FILE *f){
drh98aa2ab2018-09-26 16:53:51 +00005491 showHelp(f,"archive");
dan0d0547f2017-12-14 15:40:42 +00005492 return SQLITE_ERROR;
5493}
5494
5495/*
5496** Print an error message for the .ar command to stderr and return
5497** SQLITE_ERROR.
5498*/
drhd0f9cdc2018-05-17 14:09:06 +00005499static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
dan0d0547f2017-12-14 15:40:42 +00005500 va_list ap;
5501 char *z;
5502 va_start(ap, zFmt);
5503 z = sqlite3_vmprintf(zFmt, ap);
5504 va_end(ap);
drhd0f9cdc2018-05-17 14:09:06 +00005505 utf8_printf(stderr, "Error: %s\n", z);
5506 if( pAr->fromCmdLine ){
5507 utf8_printf(stderr, "Use \"-A\" for more help\n");
5508 }else{
5509 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
5510 }
dan0d0547f2017-12-14 15:40:42 +00005511 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00005512 return SQLITE_ERROR;
5513}
5514
5515/*
5516** Values for ArCommand.eCmd.
5517*/
dand4b56e52017-12-12 20:04:59 +00005518#define AR_CMD_CREATE 1
drhb17ea912019-03-25 14:24:19 +00005519#define AR_CMD_UPDATE 2
5520#define AR_CMD_INSERT 3
5521#define AR_CMD_EXTRACT 4
5522#define AR_CMD_LIST 5
5523#define AR_CMD_HELP 6
dand4b56e52017-12-12 20:04:59 +00005524
5525/*
5526** Other (non-command) switches.
5527*/
drhb17ea912019-03-25 14:24:19 +00005528#define AR_SWITCH_VERBOSE 7
5529#define AR_SWITCH_FILE 8
5530#define AR_SWITCH_DIRECTORY 9
5531#define AR_SWITCH_APPEND 10
5532#define AR_SWITCH_DRYRUN 11
dand4b56e52017-12-12 20:04:59 +00005533
5534static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
5535 switch( eSwitch ){
5536 case AR_CMD_CREATE:
5537 case AR_CMD_EXTRACT:
5538 case AR_CMD_LIST:
5539 case AR_CMD_UPDATE:
drhb17ea912019-03-25 14:24:19 +00005540 case AR_CMD_INSERT:
dan0d0547f2017-12-14 15:40:42 +00005541 case AR_CMD_HELP:
5542 if( pAr->eCmd ){
drhd0f9cdc2018-05-17 14:09:06 +00005543 return arErrorMsg(pAr, "multiple command options");
dan0d0547f2017-12-14 15:40:42 +00005544 }
dand4b56e52017-12-12 20:04:59 +00005545 pAr->eCmd = eSwitch;
5546 break;
5547
drhb376b3d2018-01-10 13:11:51 +00005548 case AR_SWITCH_DRYRUN:
5549 pAr->bDryRun = 1;
5550 break;
dand4b56e52017-12-12 20:04:59 +00005551 case AR_SWITCH_VERBOSE:
5552 pAr->bVerbose = 1;
5553 break;
drha5676c42018-01-10 15:17:34 +00005554 case AR_SWITCH_APPEND:
5555 pAr->bAppend = 1;
drhca7733b2018-01-10 18:09:20 +00005556 /* Fall thru into --file */
dand4b56e52017-12-12 20:04:59 +00005557 case AR_SWITCH_FILE:
5558 pAr->zFile = zArg;
5559 break;
5560 case AR_SWITCH_DIRECTORY:
5561 pAr->zDir = zArg;
5562 break;
5563 }
5564
5565 return SQLITE_OK;
5566}
dan88be0202017-12-09 17:58:02 +00005567
5568/*
5569** Parse the command line for an ".ar" command. The results are written into
5570** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5571** successfully, otherwise an error message is written to stderr and
5572** SQLITE_ERROR returned.
5573*/
5574static int arParseCommand(
5575 char **azArg, /* Array of arguments passed to dot command */
5576 int nArg, /* Number of entries in azArg[] */
5577 ArCommand *pAr /* Populate this object */
5578){
dand4b56e52017-12-12 20:04:59 +00005579 struct ArSwitch {
dand4b56e52017-12-12 20:04:59 +00005580 const char *zLong;
drhb376b3d2018-01-10 13:11:51 +00005581 char cShort;
5582 u8 eSwitch;
5583 u8 bArg;
dand4b56e52017-12-12 20:04:59 +00005584 } aSwitch[] = {
drhb376b3d2018-01-10 13:11:51 +00005585 { "create", 'c', AR_CMD_CREATE, 0 },
5586 { "extract", 'x', AR_CMD_EXTRACT, 0 },
drhb17ea912019-03-25 14:24:19 +00005587 { "insert", 'i', AR_CMD_INSERT, 0 },
drhb376b3d2018-01-10 13:11:51 +00005588 { "list", 't', AR_CMD_LIST, 0 },
5589 { "update", 'u', AR_CMD_UPDATE, 0 },
5590 { "help", 'h', AR_CMD_HELP, 0 },
5591 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
5592 { "file", 'f', AR_SWITCH_FILE, 1 },
drhca7733b2018-01-10 18:09:20 +00005593 { "append", 'a', AR_SWITCH_APPEND, 1 },
drhb376b3d2018-01-10 13:11:51 +00005594 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
drhb376b3d2018-01-10 13:11:51 +00005595 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
dand4b56e52017-12-12 20:04:59 +00005596 };
5597 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
5598 struct ArSwitch *pEnd = &aSwitch[nSwitch];
5599
dan88be0202017-12-09 17:58:02 +00005600 if( nArg<=1 ){
drh98aa2ab2018-09-26 16:53:51 +00005601 utf8_printf(stderr, "Wrong number of arguments. Usage:\n");
dan0d0547f2017-12-14 15:40:42 +00005602 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00005603 }else{
5604 char *z = azArg[1];
dan88be0202017-12-09 17:58:02 +00005605 if( z[0]!='-' ){
5606 /* Traditional style [tar] invocation */
5607 int i;
5608 int iArg = 2;
5609 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00005610 const char *zArg = 0;
5611 struct ArSwitch *pOpt;
5612 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5613 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00005614 }
dan0d0547f2017-12-14 15:40:42 +00005615 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005616 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005617 }
dand4b56e52017-12-12 20:04:59 +00005618 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005619 if( iArg>=nArg ){
drhd0f9cdc2018-05-17 14:09:06 +00005620 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005621 }
dand4b56e52017-12-12 20:04:59 +00005622 zArg = azArg[iArg++];
5623 }
5624 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00005625 }
dan88be0202017-12-09 17:58:02 +00005626 pAr->nArg = nArg-iArg;
5627 if( pAr->nArg>0 ){
5628 pAr->azArg = &azArg[iArg];
5629 }
dand4b56e52017-12-12 20:04:59 +00005630 }else{
5631 /* Non-traditional invocation */
5632 int iArg;
5633 for(iArg=1; iArg<nArg; iArg++){
5634 int n;
5635 z = azArg[iArg];
5636 if( z[0]!='-' ){
5637 /* All remaining command line words are command arguments. */
5638 pAr->azArg = &azArg[iArg];
5639 pAr->nArg = nArg-iArg;
5640 break;
5641 }
drhaf2770f2018-01-05 14:55:43 +00005642 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00005643
5644 if( z[1]!='-' ){
5645 int i;
5646 /* One or more short options */
5647 for(i=1; i<n; i++){
5648 const char *zArg = 0;
5649 struct ArSwitch *pOpt;
5650 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5651 if( z[i]==pOpt->cShort ) break;
5652 }
dan0d0547f2017-12-14 15:40:42 +00005653 if( pOpt==pEnd ){
drhd0f9cdc2018-05-17 14:09:06 +00005654 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
dan0d0547f2017-12-14 15:40:42 +00005655 }
dand4b56e52017-12-12 20:04:59 +00005656 if( pOpt->bArg ){
5657 if( i<(n-1) ){
5658 zArg = &z[i+1];
5659 i = n;
5660 }else{
dan0d0547f2017-12-14 15:40:42 +00005661 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005662 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
dan0d0547f2017-12-14 15:40:42 +00005663 }
dand4b56e52017-12-12 20:04:59 +00005664 zArg = azArg[++iArg];
5665 }
5666 }
5667 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
5668 }
5669 }else if( z[2]=='\0' ){
5670 /* A -- option, indicating that all remaining command line words
5671 ** are command arguments. */
5672 pAr->azArg = &azArg[iArg+1];
5673 pAr->nArg = nArg-iArg-1;
5674 break;
5675 }else{
5676 /* A long option */
5677 const char *zArg = 0; /* Argument for option, if any */
5678 struct ArSwitch *pMatch = 0; /* Matching option */
5679 struct ArSwitch *pOpt; /* Iterator */
5680 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
5681 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00005682 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00005683 if( pMatch ){
drhd0f9cdc2018-05-17 14:09:06 +00005684 return arErrorMsg(pAr, "ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00005685 }else{
5686 pMatch = pOpt;
5687 }
5688 }
5689 }
5690
5691 if( pMatch==0 ){
drhd0f9cdc2018-05-17 14:09:06 +00005692 return arErrorMsg(pAr, "unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00005693 }
5694 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00005695 if( iArg>=(nArg-1) ){
drhd0f9cdc2018-05-17 14:09:06 +00005696 return arErrorMsg(pAr, "option requires an argument: %s", z);
dan0d0547f2017-12-14 15:40:42 +00005697 }
dand4b56e52017-12-12 20:04:59 +00005698 zArg = azArg[++iArg];
5699 }
5700 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
5701 }
5702 }
dan88be0202017-12-09 17:58:02 +00005703 }
5704 }
5705
5706 return SQLITE_OK;
5707}
5708
5709/*
dan3f67ddf2017-12-13 20:04:53 +00005710** This function assumes that all arguments within the ArCommand.azArg[]
5711** array refer to archive members, as for the --extract or --list commands.
5712** It checks that each of them are present. If any specified file is not
5713** present in the archive, an error is printed to stderr and an error
5714** code returned. Otherwise, if all specified arguments are present in
5715** the archive, SQLITE_OK is returned.
5716**
5717** This function strips any trailing '/' characters from each argument.
5718** This is consistent with the way the [tar] command seems to work on
5719** Linux.
5720*/
drhb376b3d2018-01-10 13:11:51 +00005721static int arCheckEntries(ArCommand *pAr){
dan3f67ddf2017-12-13 20:04:53 +00005722 int rc = SQLITE_OK;
5723 if( pAr->nArg ){
drhb376b3d2018-01-10 13:11:51 +00005724 int i, j;
dan3f67ddf2017-12-13 20:04:53 +00005725 sqlite3_stmt *pTest = 0;
5726
drhb376b3d2018-01-10 13:11:51 +00005727 shellPreparePrintf(pAr->db, &rc, &pTest,
5728 "SELECT name FROM %s WHERE name=$name",
5729 pAr->zSrcTable
dan5a78b812017-12-27 18:54:11 +00005730 );
drhb376b3d2018-01-10 13:11:51 +00005731 j = sqlite3_bind_parameter_index(pTest, "$name");
dan3f67ddf2017-12-13 20:04:53 +00005732 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
5733 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00005734 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00005735 int bOk = 0;
5736 while( n>0 && z[n-1]=='/' ) n--;
5737 z[n] = '\0';
drhb376b3d2018-01-10 13:11:51 +00005738 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
dan3f67ddf2017-12-13 20:04:53 +00005739 if( SQLITE_ROW==sqlite3_step(pTest) ){
5740 bOk = 1;
5741 }
5742 shellReset(&rc, pTest);
5743 if( rc==SQLITE_OK && bOk==0 ){
drhb376b3d2018-01-10 13:11:51 +00005744 utf8_printf(stderr, "not found in archive: %s\n", z);
dan3f67ddf2017-12-13 20:04:53 +00005745 rc = SQLITE_ERROR;
5746 }
5747 }
5748 shellFinalize(&rc, pTest);
5749 }
dan3f67ddf2017-12-13 20:04:53 +00005750 return rc;
5751}
5752
5753/*
5754** Format a WHERE clause that can be used against the "sqlar" table to
5755** identify all archive members that match the command arguments held
5756** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5757** The caller is responsible for eventually calling sqlite3_free() on
5758** any non-NULL (*pzWhere) value.
5759*/
5760static void arWhereClause(
5761 int *pRc,
5762 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00005763 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00005764){
5765 char *zWhere = 0;
5766 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00005767 if( pAr->nArg==0 ){
5768 zWhere = sqlite3_mprintf("1");
5769 }else{
5770 int i;
5771 const char *zSep = "";
5772 for(i=0; i<pAr->nArg; i++){
5773 const char *z = pAr->azArg[i];
5774 zWhere = sqlite3_mprintf(
drhb376b3d2018-01-10 13:11:51 +00005775 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5776 zWhere, zSep, z, strlen30(z)+1, z
5777 );
danac15e2d2017-12-14 19:15:07 +00005778 if( zWhere==0 ){
5779 *pRc = SQLITE_NOMEM;
5780 break;
5781 }
5782 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00005783 }
dan3f67ddf2017-12-13 20:04:53 +00005784 }
5785 }
5786 *pzWhere = zWhere;
5787}
5788
5789/*
dan88be0202017-12-09 17:58:02 +00005790** Implementation of .ar "lisT" command.
5791*/
drhb376b3d2018-01-10 13:11:51 +00005792static int arListCommand(ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00005793 const char *zSql = "SELECT %s FROM %s WHERE %s";
danb5090e42017-12-27 21:13:21 +00005794 const char *azCols[] = {
5795 "name",
drh410cad92018-01-10 17:19:16 +00005796 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
danb5090e42017-12-27 21:13:21 +00005797 };
dan5a78b812017-12-27 18:54:11 +00005798
dan3f67ddf2017-12-13 20:04:53 +00005799 char *zWhere = 0;
5800 sqlite3_stmt *pSql = 0;
5801 int rc;
5802
drhb376b3d2018-01-10 13:11:51 +00005803 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005804 arWhereClause(&rc, pAr, &zWhere);
5805
drhb376b3d2018-01-10 13:11:51 +00005806 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
5807 pAr->zSrcTable, zWhere);
drhb376b3d2018-01-10 13:11:51 +00005808 if( pAr->bDryRun ){
5809 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5810 }else{
5811 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5812 if( pAr->bVerbose ){
drh410cad92018-01-10 17:19:16 +00005813 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
5814 sqlite3_column_text(pSql, 0),
drhb376b3d2018-01-10 13:11:51 +00005815 sqlite3_column_int(pSql, 1),
5816 sqlite3_column_text(pSql, 2),
5817 sqlite3_column_text(pSql, 3)
5818 );
5819 }else{
5820 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5821 }
danb5090e42017-12-27 21:13:21 +00005822 }
dan3f67ddf2017-12-13 20:04:53 +00005823 }
dan5a78b812017-12-27 18:54:11 +00005824 shellFinalize(&rc, pSql);
drhd0f9cdc2018-05-17 14:09:06 +00005825 sqlite3_free(zWhere);
dan3f67ddf2017-12-13 20:04:53 +00005826 return rc;
dan88be0202017-12-09 17:58:02 +00005827}
5828
5829
danfd0245d2017-12-07 15:44:29 +00005830/*
5831** Implementation of .ar "eXtract" command.
5832*/
drhb376b3d2018-01-10 13:11:51 +00005833static int arExtractCommand(ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00005834 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00005835 "SELECT "
drhb376b3d2018-01-10 13:11:51 +00005836 " ($dir || name),"
5837 " writefile(($dir || name), %s, mode, mtime) "
drh0cfd46a2018-06-06 01:18:01 +00005838 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5839 " AND name NOT GLOB '*..[/\\]*'";
dan5a78b812017-12-27 18:54:11 +00005840
5841 const char *azExtraArg[] = {
5842 "sqlar_uncompress(data, sz)",
dan7c15ac12018-01-08 19:59:59 +00005843 "data"
dan5a78b812017-12-27 18:54:11 +00005844 };
dan5a78b812017-12-27 18:54:11 +00005845
danfd0245d2017-12-07 15:44:29 +00005846 sqlite3_stmt *pSql = 0;
5847 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00005848 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00005849 char *zWhere = 0;
drhb376b3d2018-01-10 13:11:51 +00005850 int i, j;
dan2ad09492017-12-09 18:28:22 +00005851
dan3f67ddf2017-12-13 20:04:53 +00005852 /* If arguments are specified, check that they actually exist within
5853 ** the archive before proceeding. And formulate a WHERE clause to
5854 ** match them. */
drhb376b3d2018-01-10 13:11:51 +00005855 rc = arCheckEntries(pAr);
dan3f67ddf2017-12-13 20:04:53 +00005856 arWhereClause(&rc, pAr, &zWhere);
5857
5858 if( rc==SQLITE_OK ){
5859 if( pAr->zDir ){
5860 zDir = sqlite3_mprintf("%s/", pAr->zDir);
5861 }else{
5862 zDir = sqlite3_mprintf("");
5863 }
5864 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00005865 }
danfd0245d2017-12-07 15:44:29 +00005866
drhb376b3d2018-01-10 13:11:51 +00005867 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
5868 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
dan5a78b812017-12-27 18:54:11 +00005869 );
5870
dan2ad09492017-12-09 18:28:22 +00005871 if( rc==SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00005872 j = sqlite3_bind_parameter_index(pSql, "$dir");
5873 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
dan25c12182017-12-07 21:03:33 +00005874
danac15e2d2017-12-14 19:15:07 +00005875 /* Run the SELECT statement twice. The first time, writefile() is called
5876 ** for all archive members that should be extracted. The second time,
5877 ** only for the directories. This is because the timestamps for
5878 ** extracted directories must be reset after they are populated (as
5879 ** populating them changes the timestamp). */
5880 for(i=0; i<2; i++){
drhb376b3d2018-01-10 13:11:51 +00005881 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
5882 sqlite3_bind_int(pSql, j, i);
5883 if( pAr->bDryRun ){
5884 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
5885 }else{
5886 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
5887 if( i==0 && pAr->bVerbose ){
5888 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
5889 }
danac15e2d2017-12-14 19:15:07 +00005890 }
5891 }
5892 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005893 }
danac15e2d2017-12-14 19:15:07 +00005894 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00005895 }
dan25c12182017-12-07 21:03:33 +00005896
dan2ad09492017-12-09 18:28:22 +00005897 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00005898 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00005899 return rc;
5900}
5901
drhb376b3d2018-01-10 13:11:51 +00005902/*
5903** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5904*/
5905static int arExecSql(ArCommand *pAr, const char *zSql){
5906 int rc;
5907 if( pAr->bDryRun ){
5908 utf8_printf(pAr->p->out, "%s\n", zSql);
5909 rc = SQLITE_OK;
5910 }else{
drh410cad92018-01-10 17:19:16 +00005911 char *zErr = 0;
5912 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
5913 if( zErr ){
5914 utf8_printf(stdout, "ERROR: %s\n", zErr);
5915 sqlite3_free(zErr);
5916 }
drhb376b3d2018-01-10 13:11:51 +00005917 }
5918 return rc;
5919}
5920
dan1ad3f612017-12-11 20:22:02 +00005921
danfd0245d2017-12-07 15:44:29 +00005922/*
drhb17ea912019-03-25 14:24:19 +00005923** Implementation of .ar "create", "insert", and "update" commands.
5924**
5925** create -> Create a new SQL archive
5926** insert -> Insert or reinsert all files listed
5927** update -> Insert files that have changed or that were not
5928** previously in the archive
danfd0245d2017-12-07 15:44:29 +00005929**
5930** Create the "sqlar" table in the database if it does not already exist.
5931** Then add each file in the azFile[] array to the archive. Directories
5932** are added recursively. If argument bVerbose is non-zero, a message is
5933** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00005934**
5935** The create command is the same as update, except that it drops
drhb17ea912019-03-25 14:24:19 +00005936** any existing "sqlar" table before beginning. The "insert" command
5937** always overwrites every file named on the command-line, where as
5938** "update" only overwrites if the size or mtime or mode has changed.
danfd0245d2017-12-07 15:44:29 +00005939*/
drhb376b3d2018-01-10 13:11:51 +00005940static int arCreateOrUpdateCommand(
dan06741a32017-12-13 20:17:18 +00005941 ArCommand *pAr, /* Command arguments and options */
drhb17ea912019-03-25 14:24:19 +00005942 int bUpdate, /* true for a --create. */
5943 int bOnlyIfChanged /* Only update if file has changed */
danfd0245d2017-12-07 15:44:29 +00005944){
dand4b56e52017-12-12 20:04:59 +00005945 const char *zCreate =
drhafba1802018-01-06 15:49:57 +00005946 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5947 " name TEXT PRIMARY KEY, -- name of the file\n"
5948 " mode INT, -- access permissions\n"
5949 " mtime INT, -- last modification time\n"
5950 " sz INT, -- original file size\n"
5951 " data BLOB -- compressed content\n"
5952 ")";
dand4b56e52017-12-12 20:04:59 +00005953 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
drh1bf208c2018-03-09 21:54:01 +00005954 const char *zInsertFmt[2] = {
5955 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
drh634c70f2018-01-10 16:50:18 +00005956 " SELECT\n"
5957 " %s,\n"
5958 " mode,\n"
5959 " mtime,\n"
drh410cad92018-01-10 17:19:16 +00005960 " CASE substr(lsmode(mode),1,1)\n"
5961 " WHEN '-' THEN length(data)\n"
5962 " WHEN 'd' THEN 0\n"
drh634c70f2018-01-10 16:50:18 +00005963 " ELSE -1 END,\n"
drh69d2d352018-03-09 22:18:53 +00005964 " sqlar_compress(data)\n"
drhb17ea912019-03-25 14:24:19 +00005965 " FROM fsdir(%Q,%Q) AS disk\n"
5966 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
5967 ,
drh1bf208c2018-03-09 21:54:01 +00005968 "REPLACE INTO %s(name,mode,mtime,data)\n"
5969 " SELECT\n"
5970 " %s,\n"
5971 " mode,\n"
5972 " mtime,\n"
5973 " data\n"
drhb17ea912019-03-25 14:24:19 +00005974 " FROM fsdir(%Q,%Q) AS disk\n"
5975 " WHERE lsmode(mode) NOT LIKE '?%%'%s;"
drh1bf208c2018-03-09 21:54:01 +00005976 };
danfd0245d2017-12-07 15:44:29 +00005977 int i; /* For iterating through azFile[] */
5978 int rc; /* Return code */
drh1bf208c2018-03-09 21:54:01 +00005979 const char *zTab = 0; /* SQL table into which to insert */
5980 char *zSql;
5981 char zTemp[50];
drhb17ea912019-03-25 14:24:19 +00005982 char *zExists = 0;
danfd0245d2017-12-07 15:44:29 +00005983
drh1bf208c2018-03-09 21:54:01 +00005984 arExecSql(pAr, "PRAGMA page_size=512");
drhb376b3d2018-01-10 13:11:51 +00005985 rc = arExecSql(pAr, "SAVEPOINT ar;");
danfd0245d2017-12-07 15:44:29 +00005986 if( rc!=SQLITE_OK ) return rc;
drh1bf208c2018-03-09 21:54:01 +00005987 zTemp[0] = 0;
5988 if( pAr->bZip ){
5989 /* Initialize the zipfile virtual table, if necessary */
5990 if( pAr->zFile ){
5991 sqlite3_uint64 r;
5992 sqlite3_randomness(sizeof(r),&r);
5993 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
5994 zTab = zTemp;
5995 zSql = sqlite3_mprintf(
5996 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5997 zTab, pAr->zFile
5998 );
5999 rc = arExecSql(pAr, zSql);
6000 sqlite3_free(zSql);
6001 }else{
6002 zTab = "zip";
6003 }
6004 }else{
6005 /* Initialize the table for an SQLAR */
6006 zTab = "sqlar";
6007 if( bUpdate==0 ){
6008 rc = arExecSql(pAr, zDrop);
6009 if( rc!=SQLITE_OK ) goto end_ar_transaction;
6010 }
6011 rc = arExecSql(pAr, zCreate);
dan06741a32017-12-13 20:17:18 +00006012 }
drhb17ea912019-03-25 14:24:19 +00006013 if( bOnlyIfChanged ){
6014 zExists = sqlite3_mprintf(
6015 " AND NOT EXISTS("
6016 "SELECT 1 FROM %s AS mem"
6017 " WHERE mem.name=disk.name"
6018 " AND mem.mtime=disk.mtime"
6019 " AND mem.mode=disk.mode)", zTab);
6020 }else{
6021 zExists = sqlite3_mprintf("");
6022 }
6023 if( zExists==0 ) rc = SQLITE_NOMEM;
dan88be0202017-12-09 17:58:02 +00006024 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
mistachkince2052b2018-03-23 00:31:53 +00006025 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
drh634c70f2018-01-10 16:50:18 +00006026 pAr->bVerbose ? "shell_putsnl(name)" : "name",
drhb17ea912019-03-25 14:24:19 +00006027 pAr->azArg[i], pAr->zDir, zExists);
mistachkince2052b2018-03-23 00:31:53 +00006028 rc = arExecSql(pAr, zSql2);
6029 sqlite3_free(zSql2);
danfd0245d2017-12-07 15:44:29 +00006030 }
drh1bf208c2018-03-09 21:54:01 +00006031end_ar_transaction:
danfd0245d2017-12-07 15:44:29 +00006032 if( rc!=SQLITE_OK ){
drh2bd207f2019-01-11 17:19:59 +00006033 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00006034 }else{
drhb376b3d2018-01-10 13:11:51 +00006035 rc = arExecSql(pAr, "RELEASE ar;");
drh1bf208c2018-03-09 21:54:01 +00006036 if( pAr->bZip && pAr->zFile ){
6037 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
6038 arExecSql(pAr, zSql);
6039 sqlite3_free(zSql);
6040 }
danfd0245d2017-12-07 15:44:29 +00006041 }
drhb17ea912019-03-25 14:24:19 +00006042 sqlite3_free(zExists);
danfd0245d2017-12-07 15:44:29 +00006043 return rc;
6044}
6045
6046/*
6047** Implementation of ".ar" dot command.
6048*/
6049static int arDotCommand(
6050 ShellState *pState, /* Current shell tool state */
drhd0f9cdc2018-05-17 14:09:06 +00006051 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
danfd0245d2017-12-07 15:44:29 +00006052 char **azArg, /* Array of arguments passed to dot command */
6053 int nArg /* Number of entries in azArg[] */
6054){
dan88be0202017-12-09 17:58:02 +00006055 ArCommand cmd;
6056 int rc;
drh34660642018-01-10 17:39:54 +00006057 memset(&cmd, 0, sizeof(cmd));
drhd0f9cdc2018-05-17 14:09:06 +00006058 cmd.fromCmdLine = fromCmdLine;
dan88be0202017-12-09 17:58:02 +00006059 rc = arParseCommand(azArg, nArg, &cmd);
6060 if( rc==SQLITE_OK ){
drha5676c42018-01-10 15:17:34 +00006061 int eDbType = SHELL_OPEN_UNSPEC;
drhb376b3d2018-01-10 13:11:51 +00006062 cmd.p = pState;
6063 cmd.db = pState->db;
drha5676c42018-01-10 15:17:34 +00006064 if( cmd.zFile ){
drh1bf208c2018-03-09 21:54:01 +00006065 eDbType = deduceDatabaseType(cmd.zFile, 1);
drha5676c42018-01-10 15:17:34 +00006066 }else{
6067 eDbType = pState->openMode;
6068 }
6069 if( eDbType==SHELL_OPEN_ZIPFILE ){
drh1bf208c2018-03-09 21:54:01 +00006070 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
6071 if( cmd.zFile==0 ){
6072 cmd.zSrcTable = sqlite3_mprintf("zip");
6073 }else{
6074 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
6075 }
dan5a78b812017-12-27 18:54:11 +00006076 }
drha5676c42018-01-10 15:17:34 +00006077 cmd.bZip = 1;
dan5a78b812017-12-27 18:54:11 +00006078 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00006079 int flags;
drha5676c42018-01-10 15:17:34 +00006080 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
drhb17ea912019-03-25 14:24:19 +00006081 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT
6082 || cmd.eCmd==AR_CMD_UPDATE ){
dand4b56e52017-12-12 20:04:59 +00006083 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
6084 }else{
6085 flags = SQLITE_OPEN_READONLY;
6086 }
drha82c95b2018-01-10 14:00:00 +00006087 cmd.db = 0;
drha5676c42018-01-10 15:17:34 +00006088 if( cmd.bDryRun ){
6089 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
6090 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
6091 }
6092 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
6093 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
dand4b56e52017-12-12 20:04:59 +00006094 if( rc!=SQLITE_OK ){
drhb376b3d2018-01-10 13:11:51 +00006095 utf8_printf(stderr, "cannot open file: %s (%s)\n",
6096 cmd.zFile, sqlite3_errmsg(cmd.db)
dand4b56e52017-12-12 20:04:59 +00006097 );
drha5676c42018-01-10 15:17:34 +00006098 goto end_ar_command;
dand4b56e52017-12-12 20:04:59 +00006099 }
drhb376b3d2018-01-10 13:11:51 +00006100 sqlite3_fileio_init(cmd.db, 0, 0);
drhb376b3d2018-01-10 13:11:51 +00006101 sqlite3_sqlar_init(cmd.db, 0, 0);
drh34660642018-01-10 17:39:54 +00006102 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
6103 shellPutsFunc, 0, 0);
6104
dand4b56e52017-12-12 20:04:59 +00006105 }
drhd0f9cdc2018-05-17 14:09:06 +00006106 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
drh634c70f2018-01-10 16:50:18 +00006107 if( cmd.eCmd!=AR_CMD_CREATE
6108 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
6109 ){
drha5676c42018-01-10 15:17:34 +00006110 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
6111 rc = SQLITE_ERROR;
6112 goto end_ar_command;
6113 }
6114 cmd.zSrcTable = sqlite3_mprintf("sqlar");
6115 }
dand4b56e52017-12-12 20:04:59 +00006116
dan88be0202017-12-09 17:58:02 +00006117 switch( cmd.eCmd ){
6118 case AR_CMD_CREATE:
drhb17ea912019-03-25 14:24:19 +00006119 rc = arCreateOrUpdateCommand(&cmd, 0, 0);
dan88be0202017-12-09 17:58:02 +00006120 break;
danfd0245d2017-12-07 15:44:29 +00006121
dan88be0202017-12-09 17:58:02 +00006122 case AR_CMD_EXTRACT:
drhb376b3d2018-01-10 13:11:51 +00006123 rc = arExtractCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00006124 break;
6125
6126 case AR_CMD_LIST:
drhb376b3d2018-01-10 13:11:51 +00006127 rc = arListCommand(&cmd);
dan88be0202017-12-09 17:58:02 +00006128 break;
6129
dan0d0547f2017-12-14 15:40:42 +00006130 case AR_CMD_HELP:
6131 arUsage(pState->out);
6132 break;
6133
drhb17ea912019-03-25 14:24:19 +00006134 case AR_CMD_INSERT:
6135 rc = arCreateOrUpdateCommand(&cmd, 1, 0);
6136 break;
6137
dan88be0202017-12-09 17:58:02 +00006138 default:
6139 assert( cmd.eCmd==AR_CMD_UPDATE );
drhb17ea912019-03-25 14:24:19 +00006140 rc = arCreateOrUpdateCommand(&cmd, 1, 1);
dan88be0202017-12-09 17:58:02 +00006141 break;
danfd0245d2017-12-07 15:44:29 +00006142 }
6143 }
drha5676c42018-01-10 15:17:34 +00006144end_ar_command:
6145 if( cmd.db!=pState->db ){
drh9e804032018-05-18 17:11:50 +00006146 close_db(cmd.db);
drha5676c42018-01-10 15:17:34 +00006147 }
6148 sqlite3_free(cmd.zSrcTable);
danfd0245d2017-12-07 15:44:29 +00006149
dan88be0202017-12-09 17:58:02 +00006150 return rc;
danfd0245d2017-12-07 15:44:29 +00006151}
drhe37c0e12018-01-06 19:19:50 +00006152/* End of the ".archive" or ".ar" command logic
6153**********************************************************************************/
6154#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
danfd0245d2017-12-07 15:44:29 +00006155
dan42ebb012019-04-27 18:47:03 +00006156/*
6157** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op.
6158** Otherwise, the SQL statement or statements in zSql are executed using
6159** database connection db and the error code written to *pRc before
6160** this function returns.
6161*/
dan68cb86e2019-04-20 20:57:28 +00006162static void shellExec(sqlite3 *db, int *pRc, const char *zSql){
6163 int rc = *pRc;
6164 if( rc==SQLITE_OK ){
6165 char *zErr = 0;
6166 rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
6167 if( rc!=SQLITE_OK ){
6168 raw_printf(stderr, "SQL error: %s\n", zErr);
6169 }
6170 *pRc = rc;
6171 }
6172}
6173
dan42ebb012019-04-27 18:47:03 +00006174/*
6175** Like shellExec(), except that zFmt is a printf() style format string.
6176*/
danc0b42432019-04-26 15:14:53 +00006177static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){
6178 char *z = 0;
6179 if( *pRc==SQLITE_OK ){
6180 va_list ap;
6181 va_start(ap, zFmt);
6182 z = sqlite3_vmprintf(zFmt, ap);
6183 va_end(ap);
6184 if( z==0 ){
6185 *pRc = SQLITE_NOMEM;
6186 }else{
6187 shellExec(db, pRc, z);
6188 }
6189 sqlite3_free(z);
6190 }
6191}
6192
dan42ebb012019-04-27 18:47:03 +00006193/*
6194** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6195** Otherwise, an attempt is made to allocate, zero and return a pointer
6196** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set
6197** to SQLITE_NOMEM and NULL returned.
6198*/
dan68cb86e2019-04-20 20:57:28 +00006199static void *shellMalloc(int *pRc, sqlite3_int64 nByte){
6200 void *pRet = 0;
6201 if( *pRc==SQLITE_OK ){
6202 pRet = sqlite3_malloc64(nByte);
6203 if( pRet==0 ){
6204 *pRc = SQLITE_NOMEM;
6205 }else{
6206 memset(pRet, 0, nByte);
6207 }
6208 }
6209 return pRet;
6210}
6211
dan42ebb012019-04-27 18:47:03 +00006212/*
6213** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
6214** Otherwise, zFmt is treated as a printf() style string. The result of
6215** formatting it along with any trailing arguments is written into a
6216** buffer obtained from sqlite3_malloc(), and pointer to which is returned.
6217** It is the responsibility of the caller to eventually free this buffer
6218** using a call to sqlite3_free().
6219**
6220** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL
6221** pointer returned.
6222*/
dan68cb86e2019-04-20 20:57:28 +00006223static char *shellMPrintf(int *pRc, const char *zFmt, ...){
6224 char *z = 0;
6225 if( *pRc==SQLITE_OK ){
6226 va_list ap;
6227 va_start(ap, zFmt);
6228 z = sqlite3_vmprintf(zFmt, ap);
6229 va_end(ap);
6230 if( z==0 ){
6231 *pRc = SQLITE_NOMEM;
6232 }
6233 }
6234 return z;
6235}
6236
dan42ebb012019-04-27 18:47:03 +00006237/*
6238** When running the ".recover" command, each output table, and the special
6239** orphaned row table if it is required, is represented by an instance
6240** of the following struct.
6241*/
dan68cb86e2019-04-20 20:57:28 +00006242typedef struct RecoverTable RecoverTable;
6243struct RecoverTable {
dan42ebb012019-04-27 18:47:03 +00006244 char *zQuoted; /* Quoted version of table name */
dan68cb86e2019-04-20 20:57:28 +00006245 int nCol; /* Number of columns in table */
6246 char **azlCol; /* Array of column lists */
dan42ebb012019-04-27 18:47:03 +00006247 int iPk; /* Index of IPK column */
dan68cb86e2019-04-20 20:57:28 +00006248};
6249
6250/*
dan42ebb012019-04-27 18:47:03 +00006251** Free a RecoverTable object allocated by recoverFindTable() or
6252** recoverOrphanTable().
dan68cb86e2019-04-20 20:57:28 +00006253*/
6254static void recoverFreeTable(RecoverTable *pTab){
6255 if( pTab ){
dan68cb86e2019-04-20 20:57:28 +00006256 sqlite3_free(pTab->zQuoted);
dan68cb86e2019-04-20 20:57:28 +00006257 if( pTab->azlCol ){
6258 int i;
dan98c5ad32019-04-26 21:11:37 +00006259 for(i=0; i<=pTab->nCol; i++){
dan68cb86e2019-04-20 20:57:28 +00006260 sqlite3_free(pTab->azlCol[i]);
6261 }
6262 sqlite3_free(pTab->azlCol);
6263 }
6264 sqlite3_free(pTab);
6265 }
6266}
6267
dan42ebb012019-04-27 18:47:03 +00006268/*
6269** This function is a no-op if (*pRc) is not SQLITE_OK when it is called.
6270** Otherwise, it allocates and returns a RecoverTable object based on the
6271** final four arguments passed to this function. It is the responsibility
6272** of the caller to eventually free the returned object using
6273** recoverFreeTable().
6274*/
6275static RecoverTable *recoverNewTable(
danb40af492019-04-22 20:52:12 +00006276 int *pRc, /* IN/OUT: Error code */
danb40af492019-04-22 20:52:12 +00006277 const char *zName, /* Name of table */
6278 const char *zSql, /* CREATE TABLE statement */
6279 int bIntkey,
6280 int nCol
6281){
6282 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */
6283 int rc = *pRc;
dan98c5ad32019-04-26 21:11:37 +00006284 RecoverTable *pTab = 0;
danb40af492019-04-22 20:52:12 +00006285
dan98c5ad32019-04-26 21:11:37 +00006286 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable));
danb40af492019-04-22 20:52:12 +00006287 if( rc==SQLITE_OK ){
6288 int nSqlCol = 0;
6289 int bSqlIntkey = 0;
6290 sqlite3_stmt *pStmt = 0;
dan98c5ad32019-04-26 21:11:37 +00006291
danb40af492019-04-22 20:52:12 +00006292 rc = sqlite3_open("", &dbtmp);
6293 if( rc==SQLITE_OK ){
dan38f9c712019-04-23 18:03:02 +00006294 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0);
6295 }
6296 if( rc==SQLITE_OK ){
danb40af492019-04-22 20:52:12 +00006297 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0);
6298 if( rc==SQLITE_ERROR ){
6299 rc = SQLITE_OK;
6300 goto finished;
6301 }
6302 }
6303 shellPreparePrintf(dbtmp, &rc, &pStmt,
6304 "SELECT count(*) FROM pragma_table_info(%Q)", zName
6305 );
6306 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6307 nSqlCol = sqlite3_column_int(pStmt, 0);
6308 }
6309 shellFinalize(&rc, pStmt);
6310
6311 if( rc!=SQLITE_OK || nSqlCol<nCol ){
6312 goto finished;
6313 }
6314
6315 shellPreparePrintf(dbtmp, &rc, &pStmt,
6316 "SELECT ("
6317 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
6318 ") FROM sqlite_master WHERE name = %Q", zName
6319 );
6320 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6321 bSqlIntkey = sqlite3_column_int(pStmt, 0);
6322 }
6323 shellFinalize(&rc, pStmt);
6324
6325 if( bIntkey==bSqlIntkey ){
dan98c5ad32019-04-26 21:11:37 +00006326 int i;
danb40af492019-04-22 20:52:12 +00006327 const char *zPk = "_rowid_";
6328 sqlite3_stmt *pPkFinder = 0;
6329
danf57bea32019-04-27 15:35:45 +00006330 /* If this is an intkey table and there is an INTEGER PRIMARY KEY,
6331 ** set zPk to the name of the PK column, and pTab->iPk to the index
6332 ** of the column, where columns are 0-numbered from left to right.
6333 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column,
6334 ** leave zPk as "_rowid_" and pTab->iPk at -2. */
dan98c5ad32019-04-26 21:11:37 +00006335 pTab->iPk = -2;
6336 if( bIntkey ){
6337 shellPreparePrintf(dbtmp, &rc, &pPkFinder,
danb40af492019-04-22 20:52:12 +00006338 "SELECT cid, name FROM pragma_table_info(%Q) "
6339 " WHERE pk=1 AND type='integer' COLLATE nocase"
dan98c5ad32019-04-26 21:11:37 +00006340 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)"
6341 , zName, zName
6342 );
6343 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){
6344 pTab->iPk = sqlite3_column_int(pPkFinder, 0);
6345 zPk = (const char*)sqlite3_column_text(pPkFinder, 1);
6346 }
danb40af492019-04-22 20:52:12 +00006347 }
6348
dan42ebb012019-04-27 18:47:03 +00006349 pTab->zQuoted = shellMPrintf(&rc, "%Q", zName);
dan98c5ad32019-04-26 21:11:37 +00006350 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1));
danb40af492019-04-22 20:52:12 +00006351 pTab->nCol = nSqlCol;
6352
dan98c5ad32019-04-26 21:11:37 +00006353 if( bIntkey ){
danb40af492019-04-22 20:52:12 +00006354 pTab->azlCol[0] = shellMPrintf(&rc, "%Q", zPk);
6355 }else{
dan98c5ad32019-04-26 21:11:37 +00006356 pTab->azlCol[0] = shellMPrintf(&rc, "");
danb40af492019-04-22 20:52:12 +00006357 }
dan98c5ad32019-04-26 21:11:37 +00006358 i = 1;
6359 shellPreparePrintf(dbtmp, &rc, &pStmt,
6360 "SELECT %Q || group_concat(name, ', ') "
danf57bea32019-04-27 15:35:45 +00006361 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) "
dan98c5ad32019-04-26 21:11:37 +00006362 "FROM pragma_table_info(%Q)",
danf57bea32019-04-27 15:35:45 +00006363 bIntkey ? ", " : "", pTab->iPk,
6364 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ",
6365 zName
dan98c5ad32019-04-26 21:11:37 +00006366 );
6367 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6368 const char *zText = (const char*)sqlite3_column_text(pStmt, 0);
6369 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText);
6370 i++;
6371 }
6372 shellFinalize(&rc, pStmt);
6373
danb40af492019-04-22 20:52:12 +00006374 shellFinalize(&rc, pPkFinder);
6375 }
6376 }
6377
6378 finished:
6379 sqlite3_close(dbtmp);
6380 *pRc = rc;
dan98c5ad32019-04-26 21:11:37 +00006381 if( rc!=SQLITE_OK ){
6382 recoverFreeTable(pTab);
6383 pTab = 0;
6384 }
6385 return pTab;
danb40af492019-04-22 20:52:12 +00006386}
6387
dan42ebb012019-04-27 18:47:03 +00006388static RecoverTable *recoverFindTable(
dan68cb86e2019-04-20 20:57:28 +00006389 ShellState *pState,
6390 int *pRc,
6391 int iRoot,
danb40af492019-04-22 20:52:12 +00006392 int bIntkey,
dan98c5ad32019-04-26 21:11:37 +00006393 int nCol,
6394 int *pbNoop
dan68cb86e2019-04-20 20:57:28 +00006395){
danb40af492019-04-22 20:52:12 +00006396 sqlite3_stmt *pStmt = 0;
dan68cb86e2019-04-20 20:57:28 +00006397 RecoverTable *pRet = 0;
danb40af492019-04-22 20:52:12 +00006398 int bNoop = 0;
6399 const char *zSql = 0;
6400 const char *zName = 0;
dan68cb86e2019-04-20 20:57:28 +00006401
danb40af492019-04-22 20:52:12 +00006402 /* Search the recovered schema for an object with root page iRoot. */
6403 shellPreparePrintf(pState->db, pRc, &pStmt,
6404 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot
6405 );
6406 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6407 const char *zType = (const char*)sqlite3_column_text(pStmt, 0);
6408 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){
6409 bNoop = 1;
6410 break;
6411 }
6412 if( sqlite3_stricmp(zType, "table")==0 ){
6413 zName = (const char*)sqlite3_column_text(pStmt, 1);
6414 zSql = (const char*)sqlite3_column_text(pStmt, 2);
dan42ebb012019-04-27 18:47:03 +00006415 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol);
danb40af492019-04-22 20:52:12 +00006416 break;
6417 }
6418 }
dan98c5ad32019-04-26 21:11:37 +00006419
danb40af492019-04-22 20:52:12 +00006420 shellFinalize(pRc, pStmt);
dan98c5ad32019-04-26 21:11:37 +00006421 *pbNoop = bNoop;
6422 return pRet;
6423}
danb40af492019-04-22 20:52:12 +00006424
dan98c5ad32019-04-26 21:11:37 +00006425static RecoverTable *recoverOrphanTable(
6426 ShellState *pState,
6427 int *pRc,
dan42ebb012019-04-27 18:47:03 +00006428 const char *zLostAndFound,
dan98c5ad32019-04-26 21:11:37 +00006429 int nCol
6430){
6431 RecoverTable *pTab = 0;
6432 if( nCol>=0 && *pRc==SQLITE_OK ){
6433 int i;
dan42ebb012019-04-27 18:47:03 +00006434
6435 /* This block determines the name of the orphan table. The prefered
6436 ** name is zLostAndFound. But if that clashes with another name
6437 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1
6438 ** and so on until a non-clashing name is found. */
6439 int iTab = 0;
6440 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound);
6441 sqlite3_stmt *pTest = 0;
6442 shellPrepare(pState->db, pRc,
6443 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest
dan68cb86e2019-04-20 20:57:28 +00006444 );
dan42ebb012019-04-27 18:47:03 +00006445 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
6446 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){
6447 shellReset(pRc, pTest);
6448 sqlite3_free(zTab);
6449 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++);
6450 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT);
dan68cb86e2019-04-20 20:57:28 +00006451 }
dan42ebb012019-04-27 18:47:03 +00006452 shellFinalize(pRc, pTest);
dan68cb86e2019-04-20 20:57:28 +00006453
dan98c5ad32019-04-26 21:11:37 +00006454 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable));
6455 if( pTab ){
dan42ebb012019-04-27 18:47:03 +00006456 pTab->zQuoted = shellMPrintf(pRc, "%Q", zTab);
dan98c5ad32019-04-26 21:11:37 +00006457 pTab->nCol = nCol;
6458 pTab->iPk = -2;
6459 if( nCol>0 ){
6460 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1));
6461 if( pTab->azlCol ){
6462 pTab->azlCol[nCol] = shellMPrintf(pRc, "");
6463 for(i=nCol-1; i>=0; i--){
6464 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]);
6465 }
6466 }
danb40af492019-04-22 20:52:12 +00006467 }
dan68cb86e2019-04-20 20:57:28 +00006468
dan42ebb012019-04-27 18:47:03 +00006469 if( *pRc!=SQLITE_OK ){
6470 recoverFreeTable(pTab);
6471 pTab = 0;
6472 }else{
6473 raw_printf(pState->out,
6474 "CREATE TABLE %s(rootpgno INTEGER, "
6475 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted
6476 );
6477 for(i=0; i<nCol; i++){
6478 raw_printf(pState->out, ", c%d", i);
6479 }
6480 raw_printf(pState->out, ");\n");
6481 }
dan98c5ad32019-04-26 21:11:37 +00006482 }
dan42ebb012019-04-27 18:47:03 +00006483 sqlite3_free(zTab);
dan68cb86e2019-04-20 20:57:28 +00006484 }
dan98c5ad32019-04-26 21:11:37 +00006485 return pTab;
dan68cb86e2019-04-20 20:57:28 +00006486}
6487
6488/*
6489** This function is called to recover data from the database. A script
6490** to construct a new database containing all recovered data is output
6491** on stream pState->out.
6492*/
danb9b71db2019-04-25 16:20:40 +00006493static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
dan68cb86e2019-04-20 20:57:28 +00006494 int rc = SQLITE_OK;
6495 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */
danefa363b2019-04-24 20:48:55 +00006496 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */
6497 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */
danc0b42432019-04-26 15:14:53 +00006498 const char *zRecoveryDb = ""; /* Name of "recovery" database */
dan42ebb012019-04-27 18:47:03 +00006499 const char *zLostAndFound = "lost_and_found";
dan9c014f82019-04-25 19:23:15 +00006500 int i;
dan98c5ad32019-04-26 21:11:37 +00006501 int nOrphan = -1;
6502 RecoverTable *pOrphan = 0;
dan9c014f82019-04-25 19:23:15 +00006503
6504 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */
6505 for(i=1; i<nArg; i++){
6506 char *z = azArg[i];
6507 int n;
6508 if( z[0]=='-' && z[1]=='-' ) z++;
6509 n = strlen(z);
6510 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){
6511 bFreelist = 0;
dan42ebb012019-04-27 18:47:03 +00006512 }else
danc0b42432019-04-26 15:14:53 +00006513 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
6514 i++;
6515 zRecoveryDb = azArg[i];
dan42ebb012019-04-27 18:47:03 +00006516 }else
6517 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
6518 i++;
6519 zLostAndFound = azArg[i];
danc0b42432019-04-26 15:14:53 +00006520 }
dan9c014f82019-04-25 19:23:15 +00006521 else{
danc0b42432019-04-26 15:14:53 +00006522 raw_printf(stderr, "unexpected option: %s\n", azArg[i]);
6523 raw_printf(stderr, "options are:\n");
6524 raw_printf(stderr, " --freelist-corrupt\n");
6525 raw_printf(stderr, " --recovery-db DATABASE\n");
dan42ebb012019-04-27 18:47:03 +00006526 raw_printf(stderr, " --lost-and-found TABLE-NAME\n");
dan9c014f82019-04-25 19:23:15 +00006527 return 1;
6528 }
6529 }
dan68cb86e2019-04-20 20:57:28 +00006530
danc0b42432019-04-26 15:14:53 +00006531 shellExecPrintf(pState->db, &rc,
dan68cb86e2019-04-20 20:57:28 +00006532 /* Attach an in-memory database named 'recovery'. Create an indexed
6533 ** cache of the sqlite_dbptr virtual table. */
danc0b42432019-04-26 15:14:53 +00006534 "ATTACH %Q AS recovery;"
6535 "DROP TABLE IF EXISTS recovery.dbptr;"
6536 "DROP TABLE IF EXISTS recovery.freelist;"
6537 "DROP TABLE IF EXISTS recovery.map;"
6538 "DROP TABLE IF EXISTS recovery.schema;"
danc0b42432019-04-26 15:14:53 +00006539 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb
dan9c014f82019-04-25 19:23:15 +00006540 );
6541
6542 if( bFreelist ){
6543 shellExec(pState->db, &rc,
6544 "WITH trunk(pgno) AS ("
6545 " SELECT shell_int32("
6546 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x "
6547 " WHERE x>0"
6548 " UNION"
6549 " SELECT shell_int32("
6550 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x "
6551 " FROM trunk WHERE x>0"
6552 "),"
6553 "freelist(data, n, freepgno) AS ("
6554 " SELECT data, shell_int32(data, 1)-1, t.pgno "
6555 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno"
6556 " UNION ALL"
6557 " SELECT data, n-1, shell_int32(data, 2+n) "
6558 " FROM freelist WHERE n>=0"
6559 ")"
6560 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;"
6561 );
6562 }
6563
6564 shellExec(pState->db, &rc,
danca424382019-04-26 15:40:27 +00006565 "CREATE TABLE recovery.dbptr("
6566 " pgno, child, PRIMARY KEY(child, pgno)"
6567 ") WITHOUT ROWID;"
6568 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) "
6569 " SELECT * FROM sqlite_dbptr"
6570 " WHERE pgno NOT IN freelist AND child NOT IN freelist;"
6571
6572 /* Delete any pointer to page 1. This ensures that page 1 is considered
6573 ** a root page, regardless of how corrupt the db is. */
6574 "DELETE FROM recovery.dbptr WHERE child = 1;"
6575
6576 /* Delete all pointers to any pages that have more than one pointer
6577 ** to them. Such pages will be treated as root pages when recovering
6578 ** data. */
6579 "DELETE FROM recovery.dbptr WHERE child IN ("
6580 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1"
6581 ");"
6582
dan68cb86e2019-04-20 20:57:28 +00006583 /* Create the "map" table that will (eventually) contain instructions
6584 ** for dealing with each page in the db that contains one or more
6585 ** records. */
danb40af492019-04-22 20:52:12 +00006586 "CREATE TABLE recovery.map("
6587 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT"
6588 ");"
dan68cb86e2019-04-20 20:57:28 +00006589
6590 /* Populate table [map]. If there are circular loops of pages in the
6591 ** database, the following adds all pages in such a loop to the map
6592 ** as individual root pages. This could be handled better. */
6593 "WITH pages(i, maxlen) AS ("
danb9b71db2019-04-25 16:20:40 +00006594 " SELECT page_count, ("
6595 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count"
6596 " ) FROM pragma_page_count"
dan68cb86e2019-04-20 20:57:28 +00006597 " UNION ALL"
danb40af492019-04-22 20:52:12 +00006598 " SELECT i-1, ("
6599 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1"
6600 " ) FROM pages WHERE i>=2"
dan68cb86e2019-04-20 20:57:28 +00006601 ")"
danb40af492019-04-22 20:52:12 +00006602 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) "
6603 " SELECT i, maxlen, NULL, ("
dan68cb86e2019-04-20 20:57:28 +00006604 " WITH p(orig, pgno, parent) AS ("
6605 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)"
6606 " UNION ALL"
6607 " SELECT i, p.parent, "
6608 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p"
6609 " )"
6610 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)"
6611 ") "
dan9c014f82019-04-25 19:23:15 +00006612 "FROM pages WHERE maxlen > 0 AND i NOT IN freelist;"
danb40af492019-04-22 20:52:12 +00006613 "UPDATE recovery.map AS o SET intkey = ("
6614 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno"
6615 ");"
dan68cb86e2019-04-20 20:57:28 +00006616
6617 /* Extract data from page 1 and any linked pages into table
6618 ** recovery.schema. With the same schema as an sqlite_master table. */
6619 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
6620 "INSERT INTO recovery.schema SELECT "
6621 " max(CASE WHEN field=0 THEN value ELSE NULL END),"
6622 " max(CASE WHEN field=1 THEN value ELSE NULL END),"
6623 " max(CASE WHEN field=2 THEN value ELSE NULL END),"
6624 " max(CASE WHEN field=3 THEN value ELSE NULL END),"
6625 " max(CASE WHEN field=4 THEN value ELSE NULL END)"
6626 "FROM sqlite_dbdata WHERE pgno IN ("
6627 " SELECT pgno FROM recovery.map WHERE root=1"
6628 ")"
6629 "GROUP BY pgno, cell;"
dan98c5ad32019-04-26 21:11:37 +00006630 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);"
dan68cb86e2019-04-20 20:57:28 +00006631 );
6632
danb40af492019-04-22 20:52:12 +00006633 /* Open a transaction, then print out all non-virtual, non-"sqlite_%"
6634 ** CREATE TABLE statements that extracted from the existing schema. */
6635 if( rc==SQLITE_OK ){
6636 sqlite3_stmt *pStmt = 0;
6637 raw_printf(pState->out, "BEGIN;\n");
dan38f9c712019-04-23 18:03:02 +00006638 raw_printf(pState->out, "PRAGMA writable_schema = on;\n");
6639 shellPrepare(pState->db, &rc,
danb40af492019-04-22 20:52:12 +00006640 "SELECT sql FROM recovery.schema "
dan38f9c712019-04-23 18:03:02 +00006641 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt
danb40af492019-04-22 20:52:12 +00006642 );
6643 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6644 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0);
dan38f9c712019-04-23 18:03:02 +00006645 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n",
6646 &zCreateTable[12]
6647 );
danb40af492019-04-22 20:52:12 +00006648 }
6649 shellFinalize(&rc, pStmt);
6650 }
6651
dan98c5ad32019-04-26 21:11:37 +00006652 /* Figure out if an orphan table will be required. And if so, how many
6653 ** user columns it should contain */
6654 shellPrepare(pState->db, &rc,
6655 "SELECT coalesce(max(maxlen), -2) FROM recovery.map"
6656 " WHERE root>1 AND root NOT IN (SELECT rootpage FROM recovery.schema)"
6657 , &pLoop
6658 );
6659 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6660 nOrphan = sqlite3_column_int(pLoop, 0);
6661 }
6662 shellFinalize(&rc, pLoop);
6663 pLoop = 0;
dan42ebb012019-04-27 18:47:03 +00006664 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan);
dan98c5ad32019-04-26 21:11:37 +00006665
danefa363b2019-04-24 20:48:55 +00006666 shellPrepare(pState->db, &rc,
6667 "SELECT pgno FROM recovery.map WHERE root=?", &pPages
6668 );
6669 shellPrepare(pState->db, &rc,
6670 "SELECT max(field), group_concat(shell_escape_crnl(quote(value)), ', ')"
6671 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?"
6672 "GROUP BY cell", &pCells
6673 );
6674
dan68cb86e2019-04-20 20:57:28 +00006675 /* Loop through each root page. */
danb40af492019-04-22 20:52:12 +00006676 shellPrepare(pState->db, &rc,
6677 "SELECT root, intkey, max(maxlen) FROM recovery.map"
dan38f9c712019-04-23 18:03:02 +00006678 " WHERE root>1 GROUP BY root, intkey ORDER BY root=("
6679 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'"
6680 ")", &pLoop
danb40af492019-04-22 20:52:12 +00006681 );
dan68cb86e2019-04-20 20:57:28 +00006682 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){
6683 int iRoot = sqlite3_column_int(pLoop, 0);
danb40af492019-04-22 20:52:12 +00006684 int bIntkey = sqlite3_column_int(pLoop, 1);
6685 int nCol = sqlite3_column_int(pLoop, 2);
dan98c5ad32019-04-26 21:11:37 +00006686 int bNoop = 0;
dan68cb86e2019-04-20 20:57:28 +00006687 RecoverTable *pTab;
6688
dan42ebb012019-04-27 18:47:03 +00006689 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop);
dan98c5ad32019-04-26 21:11:37 +00006690 if( bNoop || rc ) continue;
6691 if( pTab==0 ) pTab = pOrphan;
6692
dan42ebb012019-04-27 18:47:03 +00006693 if( 0==sqlite3_stricmp(pTab->zQuoted, "'sqlite_sequence'") ){
dan98c5ad32019-04-26 21:11:37 +00006694 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n");
6695 }
6696 sqlite3_bind_int(pPages, 1, iRoot);
6697 sqlite3_bind_int(pCells, 2, pTab->iPk);
6698
6699 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){
6700 int iPgno = sqlite3_column_int(pPages, 0);
6701 sqlite3_bind_int(pCells, 1, iPgno);
6702 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){
6703 int nField = sqlite3_column_int(pCells, 0);
6704 const char *zVal = (const char*)sqlite3_column_text(pCells, 1);
6705
6706 nField = nField+1;
6707 if( pTab==pOrphan ){
6708 raw_printf(pState->out,
6709 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n",
6710 pTab->zQuoted, iRoot, iPgno, nField,
6711 bIntkey ? "" : "NULL, ", zVal, pTab->azlCol[nField]
6712 );
6713 }else{
danefa363b2019-04-24 20:48:55 +00006714 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n",
dan98c5ad32019-04-26 21:11:37 +00006715 pTab->zQuoted, pTab->azlCol[nField], zVal
danefa363b2019-04-24 20:48:55 +00006716 );
6717 }
dan68cb86e2019-04-20 20:57:28 +00006718 }
dan98c5ad32019-04-26 21:11:37 +00006719 shellReset(&rc, pCells);
dan68cb86e2019-04-20 20:57:28 +00006720 }
dan98c5ad32019-04-26 21:11:37 +00006721 shellReset(&rc, pPages);
6722 if( pTab!=pOrphan ) recoverFreeTable(pTab);
dan68cb86e2019-04-20 20:57:28 +00006723 }
6724 shellFinalize(&rc, pLoop);
danefa363b2019-04-24 20:48:55 +00006725 shellFinalize(&rc, pPages);
6726 shellFinalize(&rc, pCells);
dan98c5ad32019-04-26 21:11:37 +00006727 recoverFreeTable(pOrphan);
dan68cb86e2019-04-20 20:57:28 +00006728
dan38f9c712019-04-23 18:03:02 +00006729 /* The rest of the schema */
danb40af492019-04-22 20:52:12 +00006730 if( rc==SQLITE_OK ){
dan38f9c712019-04-23 18:03:02 +00006731 sqlite3_stmt *pStmt = 0;
6732 shellPrepare(pState->db, &rc,
6733 "SELECT sql, name FROM recovery.schema "
danb1825882019-04-23 20:48:32 +00006734 "WHERE sql NOT LIKE 'create table%'", &pStmt
dan38f9c712019-04-23 18:03:02 +00006735 );
6736 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
6737 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
6738 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
6739 const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
6740 char *zPrint = shellMPrintf(&rc,
6741 "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)",
6742 zName, zName, zSql
6743 );
6744 raw_printf(pState->out, "%s;\n", zPrint);
6745 sqlite3_free(zPrint);
6746 }else{
6747 raw_printf(pState->out, "%s;\n", zSql);
6748 }
6749 }
6750 shellFinalize(&rc, pStmt);
6751 }
6752
6753 if( rc==SQLITE_OK ){
6754 raw_printf(pState->out, "PRAGMA writable_schema = off;\n");
danb40af492019-04-22 20:52:12 +00006755 raw_printf(pState->out, "COMMIT;\n");
6756 }
dan68cb86e2019-04-20 20:57:28 +00006757 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0);
6758 return rc;
6759}
6760
drh2ce15c32017-07-11 13:34:40 +00006761
6762/*
6763** If an input line begins with "." then invoke this routine to
6764** process that line.
6765**
6766** Return 1 on error, 2 to exit, and 0 otherwise.
6767*/
6768static int do_meta_command(char *zLine, ShellState *p){
6769 int h = 1;
6770 int nArg = 0;
6771 int n, c;
6772 int rc = 0;
6773 char *azArg[50];
6774
dan6b046be2018-01-09 15:25:55 +00006775#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00006776 if( p->expert.pExpert ){
6777 expertFinish(p, 1, 0);
6778 }
dan6b046be2018-01-09 15:25:55 +00006779#endif
dan43efc182017-12-19 17:42:13 +00006780
drh2ce15c32017-07-11 13:34:40 +00006781 /* Parse the input line into tokens.
6782 */
6783 while( zLine[h] && nArg<ArraySize(azArg) ){
6784 while( IsSpace(zLine[h]) ){ h++; }
6785 if( zLine[h]==0 ) break;
6786 if( zLine[h]=='\'' || zLine[h]=='"' ){
6787 int delim = zLine[h++];
6788 azArg[nArg++] = &zLine[h];
6789 while( zLine[h] && zLine[h]!=delim ){
6790 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
6791 h++;
6792 }
6793 if( zLine[h]==delim ){
6794 zLine[h++] = 0;
6795 }
6796 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
6797 }else{
6798 azArg[nArg++] = &zLine[h];
6799 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
6800 if( zLine[h] ) zLine[h++] = 0;
6801 resolve_backslashes(azArg[nArg-1]);
6802 }
6803 }
6804
6805 /* Process the input line.
6806 */
6807 if( nArg==0 ) return 0; /* no tokens, no error */
6808 n = strlen30(azArg[0]);
6809 c = azArg[0][0];
drh13c20932018-01-10 21:41:55 +00006810 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00006811
6812#ifndef SQLITE_OMIT_AUTHORIZATION
6813 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
6814 if( nArg!=2 ){
6815 raw_printf(stderr, "Usage: .auth ON|OFF\n");
6816 rc = 1;
6817 goto meta_command_exit;
6818 }
6819 open_db(p, 0);
6820 if( booleanValue(azArg[1]) ){
6821 sqlite3_set_authorizer(p->db, shellAuth, p);
6822 }else{
6823 sqlite3_set_authorizer(p->db, 0, 0);
6824 }
6825 }else
6826#endif
6827
drhe37c0e12018-01-06 19:19:50 +00006828#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
6829 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
danfd0245d2017-12-07 15:44:29 +00006830 open_db(p, 0);
drhd0f9cdc2018-05-17 14:09:06 +00006831 rc = arDotCommand(p, 0, azArg, nArg);
danfd0245d2017-12-07 15:44:29 +00006832 }else
6833#endif
6834
drh2ce15c32017-07-11 13:34:40 +00006835 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
6836 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
6837 ){
6838 const char *zDestFile = 0;
6839 const char *zDb = 0;
6840 sqlite3 *pDest;
6841 sqlite3_backup *pBackup;
6842 int j;
drha50bffb2018-12-08 01:09:14 +00006843 int bAsync = 0;
drh69ed38a2018-05-14 00:23:08 +00006844 const char *zVfs = 0;
drh2ce15c32017-07-11 13:34:40 +00006845 for(j=1; j<nArg; j++){
6846 const char *z = azArg[j];
6847 if( z[0]=='-' ){
drh69ed38a2018-05-14 00:23:08 +00006848 if( z[1]=='-' ) z++;
6849 if( strcmp(z, "-append")==0 ){
6850 zVfs = "apndvfs";
6851 }else
drha50bffb2018-12-08 01:09:14 +00006852 if( strcmp(z, "-async")==0 ){
6853 bAsync = 1;
6854 }else
drh2ce15c32017-07-11 13:34:40 +00006855 {
6856 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
6857 return 1;
6858 }
6859 }else if( zDestFile==0 ){
6860 zDestFile = azArg[j];
6861 }else if( zDb==0 ){
6862 zDb = zDestFile;
6863 zDestFile = azArg[j];
6864 }else{
drha50bffb2018-12-08 01:09:14 +00006865 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n");
drh2ce15c32017-07-11 13:34:40 +00006866 return 1;
6867 }
6868 }
6869 if( zDestFile==0 ){
6870 raw_printf(stderr, "missing FILENAME argument on .backup\n");
6871 return 1;
6872 }
6873 if( zDb==0 ) zDb = "main";
drh69ed38a2018-05-14 00:23:08 +00006874 rc = sqlite3_open_v2(zDestFile, &pDest,
6875 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
drh2ce15c32017-07-11 13:34:40 +00006876 if( rc!=SQLITE_OK ){
6877 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9e804032018-05-18 17:11:50 +00006878 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006879 return 1;
6880 }
drha50bffb2018-12-08 01:09:14 +00006881 if( bAsync ){
6882 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;",
6883 0, 0, 0);
6884 }
drh2ce15c32017-07-11 13:34:40 +00006885 open_db(p, 0);
6886 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
6887 if( pBackup==0 ){
6888 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9e804032018-05-18 17:11:50 +00006889 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006890 return 1;
6891 }
6892 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
6893 sqlite3_backup_finish(pBackup);
6894 if( rc==SQLITE_DONE ){
6895 rc = 0;
6896 }else{
6897 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
6898 rc = 1;
6899 }
drh9e804032018-05-18 17:11:50 +00006900 close_db(pDest);
drh2ce15c32017-07-11 13:34:40 +00006901 }else
6902
6903 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
6904 if( nArg==2 ){
6905 bail_on_error = booleanValue(azArg[1]);
6906 }else{
6907 raw_printf(stderr, "Usage: .bail on|off\n");
6908 rc = 1;
6909 }
6910 }else
6911
6912 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
6913 if( nArg==2 ){
6914 if( booleanValue(azArg[1]) ){
6915 setBinaryMode(p->out, 1);
6916 }else{
6917 setTextMode(p->out, 1);
6918 }
6919 }else{
6920 raw_printf(stderr, "Usage: .binary on|off\n");
6921 rc = 1;
6922 }
6923 }else
6924
6925 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
6926 if( nArg==2 ){
6927#if defined(_WIN32) || defined(WIN32)
6928 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
6929 rc = !SetCurrentDirectoryW(z);
6930 sqlite3_free(z);
6931#else
6932 rc = chdir(azArg[1]);
6933#endif
6934 if( rc ){
6935 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
6936 rc = 1;
6937 }
6938 }else{
6939 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
6940 rc = 1;
6941 }
6942 }else
6943
6944 /* The undocumented ".breakpoint" command causes a call to the no-op
6945 ** routine named test_breakpoint().
6946 */
6947 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
6948 test_breakpoint();
6949 }else
6950
6951 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
6952 if( nArg==2 ){
6953 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
6954 }else{
6955 raw_printf(stderr, "Usage: .changes on|off\n");
6956 rc = 1;
6957 }
6958 }else
6959
6960 /* Cancel output redirection, if it is currently set (by .testcase)
6961 ** Then read the content of the testcase-out.txt file and compare against
6962 ** azArg[1]. If there are differences, report an error and exit.
6963 */
6964 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
6965 char *zRes = 0;
6966 output_reset(p);
6967 if( nArg!=2 ){
6968 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
6969 rc = 2;
6970 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
6971 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
6972 rc = 2;
6973 }else if( testcase_glob(azArg[1],zRes)==0 ){
6974 utf8_printf(stderr,
6975 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
6976 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00006977 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00006978 }else{
6979 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
6980 p->nCheck++;
6981 }
6982 sqlite3_free(zRes);
6983 }else
6984
6985 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
6986 if( nArg==2 ){
6987 tryToClone(p, azArg[1]);
6988 }else{
6989 raw_printf(stderr, "Usage: .clone FILENAME\n");
6990 rc = 1;
6991 }
6992 }else
6993
6994 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
6995 ShellState data;
6996 char *zErrMsg = 0;
6997 open_db(p, 0);
6998 memcpy(&data, p, sizeof(data));
6999 data.showHeader = 0;
7000 data.cMode = data.mode = MODE_List;
7001 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
7002 data.cnt = 0;
7003 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
7004 callback, &data, &zErrMsg);
7005 if( zErrMsg ){
7006 utf8_printf(stderr,"Error: %s\n", zErrMsg);
7007 sqlite3_free(zErrMsg);
7008 rc = 1;
7009 }
7010 }else
7011
drh7df01192018-04-28 12:43:16 +00007012 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
drheb7f2a02018-09-26 18:02:32 +00007013 static const struct DbConfigChoices {
7014 const char *zName;
7015 int op;
7016 } aDbConfig[] = {
drh7df01192018-04-28 12:43:16 +00007017 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
7018 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
7019 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
7020 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
7021 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
7022 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
7023 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
7024 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
drha296cda2018-11-03 16:09:59 +00007025 { "defensive", SQLITE_DBCONFIG_DEFENSIVE },
drh7df01192018-04-28 12:43:16 +00007026 };
7027 int ii, v;
7028 open_db(p, 0);
7029 for(ii=0; ii<ArraySize(aDbConfig); ii++){
7030 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
7031 if( nArg>=3 ){
7032 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
7033 }
7034 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
7035 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
7036 if( nArg>1 ) break;
7037 }
7038 if( nArg>1 && ii==ArraySize(aDbConfig) ){
7039 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
7040 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
7041 }
7042 }else
7043
7044 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007045 rc = shell_dbinfo_command(p, nArg, azArg);
7046 }else
7047
dan68cb86e2019-04-20 20:57:28 +00007048 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){
7049 open_db(p, 0);
danb9b71db2019-04-25 16:20:40 +00007050 rc = recoverDatabaseCmd(p, nArg, azArg);
dan68cb86e2019-04-20 20:57:28 +00007051 }else
7052
drh2ce15c32017-07-11 13:34:40 +00007053 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
7054 const char *zLike = 0;
7055 int i;
7056 int savedShowHeader = p->showHeader;
drhf213b332018-07-05 17:35:46 +00007057 int savedShellFlags = p->shellFlgs;
7058 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
drh2ce15c32017-07-11 13:34:40 +00007059 for(i=1; i<nArg; i++){
7060 if( azArg[i][0]=='-' ){
7061 const char *z = azArg[i]+1;
7062 if( z[0]=='-' ) z++;
7063 if( strcmp(z,"preserve-rowids")==0 ){
7064#ifdef SQLITE_OMIT_VIRTUALTABLE
7065 raw_printf(stderr, "The --preserve-rowids option is not compatible"
7066 " with SQLITE_OMIT_VIRTUALTABLE\n");
7067 rc = 1;
7068 goto meta_command_exit;
7069#else
7070 ShellSetFlag(p, SHFLG_PreserveRowid);
7071#endif
7072 }else
7073 if( strcmp(z,"newlines")==0 ){
7074 ShellSetFlag(p, SHFLG_Newlines);
7075 }else
7076 {
7077 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
7078 rc = 1;
7079 goto meta_command_exit;
7080 }
7081 }else if( zLike ){
7082 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
7083 "?--newlines? ?LIKE-PATTERN?\n");
7084 rc = 1;
7085 goto meta_command_exit;
7086 }else{
7087 zLike = azArg[i];
7088 }
7089 }
dan68cb86e2019-04-20 20:57:28 +00007090
drh2ce15c32017-07-11 13:34:40 +00007091 open_db(p, 0);
dan68cb86e2019-04-20 20:57:28 +00007092
drh2ce15c32017-07-11 13:34:40 +00007093 /* When playing back a "dump", the content might appear in an order
7094 ** which causes immediate foreign key constraints to be violated.
7095 ** So disable foreign-key constraint enforcement to prevent problems. */
7096 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
7097 raw_printf(p->out, "BEGIN TRANSACTION;\n");
7098 p->writableSchema = 0;
7099 p->showHeader = 0;
7100 /* Set writable_schema=ON since doing so forces SQLite to initialize
7101 ** as much of the schema as it can even if the sqlite_master table is
7102 ** corrupt. */
7103 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
7104 p->nErr = 0;
7105 if( zLike==0 ){
7106 run_schema_dump_query(p,
dan42ebb012019-04-27 18:47:03 +00007107 "SELECT name, type, sql FROM sqlite_master "
7108 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
7109 );
drh2ce15c32017-07-11 13:34:40 +00007110 run_schema_dump_query(p,
dan42ebb012019-04-27 18:47:03 +00007111 "SELECT name, type, sql FROM sqlite_master "
7112 "WHERE name=='sqlite_sequence'"
7113 );
drh2ce15c32017-07-11 13:34:40 +00007114 run_table_dump_query(p,
dan42ebb012019-04-27 18:47:03 +00007115 "SELECT sql FROM sqlite_master "
7116 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
7117 );
drh2ce15c32017-07-11 13:34:40 +00007118 }else{
7119 char *zSql;
7120 zSql = sqlite3_mprintf(
dan42ebb012019-04-27 18:47:03 +00007121 "SELECT name, type, sql FROM sqlite_master "
7122 "WHERE tbl_name LIKE %Q AND type=='table'"
7123 " AND sql NOT NULL", zLike);
drh2ce15c32017-07-11 13:34:40 +00007124 run_schema_dump_query(p,zSql);
7125 sqlite3_free(zSql);
7126 zSql = sqlite3_mprintf(
dan42ebb012019-04-27 18:47:03 +00007127 "SELECT sql FROM sqlite_master "
7128 "WHERE sql NOT NULL"
7129 " AND type IN ('index','trigger','view')"
7130 " AND tbl_name LIKE %Q", zLike);
drh2ce15c32017-07-11 13:34:40 +00007131 run_table_dump_query(p, zSql, 0);
7132 sqlite3_free(zSql);
7133 }
7134 if( p->writableSchema ){
7135 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
7136 p->writableSchema = 0;
7137 }
7138 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
7139 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
dan68cb86e2019-04-20 20:57:28 +00007140 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
drh2ce15c32017-07-11 13:34:40 +00007141 p->showHeader = savedShowHeader;
drhf213b332018-07-05 17:35:46 +00007142 p->shellFlgs = savedShellFlags;
drh2ce15c32017-07-11 13:34:40 +00007143 }else
7144
7145 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
7146 if( nArg==2 ){
7147 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
7148 }else{
7149 raw_printf(stderr, "Usage: .echo on|off\n");
7150 rc = 1;
7151 }
7152 }else
7153
7154 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
7155 if( nArg==2 ){
drhe2ca99c2018-05-02 00:33:43 +00007156 p->autoEQPtest = 0;
drhb4e50392019-01-26 15:40:04 +00007157 if( p->autoEQPtrace ){
7158 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0);
7159 p->autoEQPtrace = 0;
7160 }
drh2ce15c32017-07-11 13:34:40 +00007161 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00007162 p->autoEQP = AUTOEQP_full;
7163 }else if( strcmp(azArg[1],"trigger")==0 ){
7164 p->autoEQP = AUTOEQP_trigger;
drhb4e50392019-01-26 15:40:04 +00007165#ifdef SQLITE_DEBUG
drhe2ca99c2018-05-02 00:33:43 +00007166 }else if( strcmp(azArg[1],"test")==0 ){
7167 p->autoEQP = AUTOEQP_on;
7168 p->autoEQPtest = 1;
drhb4e50392019-01-26 15:40:04 +00007169 }else if( strcmp(azArg[1],"trace")==0 ){
7170 p->autoEQP = AUTOEQP_full;
7171 p->autoEQPtrace = 1;
7172 open_db(p, 0);
drhc07eee72019-01-27 19:50:56 +00007173 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
drhb4e50392019-01-26 15:40:04 +00007174 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
7175#endif
drh2ce15c32017-07-11 13:34:40 +00007176 }else{
mistachkinb71aa092018-01-23 00:05:18 +00007177 p->autoEQP = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00007178 }
7179 }else{
drhb4e50392019-01-26 15:40:04 +00007180 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00007181 rc = 1;
7182 }
7183 }else
7184
7185 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
7186 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
7187 rc = 2;
7188 }else
7189
7190 /* The ".explain" command is automatic now. It is largely pointless. It
7191 ** retained purely for backwards compatibility */
7192 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
7193 int val = 1;
7194 if( nArg>=2 ){
7195 if( strcmp(azArg[1],"auto")==0 ){
7196 val = 99;
7197 }else{
7198 val = booleanValue(azArg[1]);
7199 }
7200 }
7201 if( val==1 && p->mode!=MODE_Explain ){
7202 p->normalMode = p->mode;
7203 p->mode = MODE_Explain;
7204 p->autoExplain = 0;
7205 }else if( val==0 ){
7206 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7207 p->autoExplain = 0;
7208 }else if( val==99 ){
7209 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
7210 p->autoExplain = 1;
7211 }
7212 }else
7213
dan6b046be2018-01-09 15:25:55 +00007214#ifndef SQLITE_OMIT_VIRTUALTABLE
dan43efc182017-12-19 17:42:13 +00007215 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
7216 open_db(p, 0);
7217 expertDotCommand(p, azArg, nArg);
7218 }else
dan6b046be2018-01-09 15:25:55 +00007219#endif
dan43efc182017-12-19 17:42:13 +00007220
drh2ce15c32017-07-11 13:34:40 +00007221 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
7222 ShellState data;
7223 char *zErrMsg = 0;
7224 int doStats = 0;
7225 memcpy(&data, p, sizeof(data));
7226 data.showHeader = 0;
7227 data.cMode = data.mode = MODE_Semi;
7228 if( nArg==2 && optionMatch(azArg[1], "indent") ){
7229 data.cMode = data.mode = MODE_Pretty;
7230 nArg = 1;
7231 }
7232 if( nArg!=1 ){
7233 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
7234 rc = 1;
7235 goto meta_command_exit;
7236 }
7237 open_db(p, 0);
7238 rc = sqlite3_exec(p->db,
7239 "SELECT sql FROM"
7240 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
7241 " FROM sqlite_master UNION ALL"
7242 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
7243 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
7244 "ORDER BY rowid",
7245 callback, &data, &zErrMsg
7246 );
7247 if( rc==SQLITE_OK ){
7248 sqlite3_stmt *pStmt;
7249 rc = sqlite3_prepare_v2(p->db,
7250 "SELECT rowid FROM sqlite_master"
7251 " WHERE name GLOB 'sqlite_stat[134]'",
7252 -1, &pStmt, 0);
7253 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
7254 sqlite3_finalize(pStmt);
7255 }
7256 if( doStats==0 ){
7257 raw_printf(p->out, "/* No STAT tables available */\n");
7258 }else{
7259 raw_printf(p->out, "ANALYZE sqlite_master;\n");
7260 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
7261 callback, &data, &zErrMsg);
7262 data.cMode = data.mode = MODE_Insert;
7263 data.zDestTable = "sqlite_stat1";
drh4c540452018-05-08 23:17:36 +00007264 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007265 data.zDestTable = "sqlite_stat3";
drh4c540452018-05-08 23:17:36 +00007266 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007267 data.zDestTable = "sqlite_stat4";
drh4c540452018-05-08 23:17:36 +00007268 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00007269 raw_printf(p->out, "ANALYZE sqlite_master;\n");
7270 }
7271 }else
7272
7273 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
7274 if( nArg==2 ){
7275 p->showHeader = booleanValue(azArg[1]);
7276 }else{
7277 raw_printf(stderr, "Usage: .headers on|off\n");
7278 rc = 1;
7279 }
7280 }else
7281
7282 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
drh98aa2ab2018-09-26 16:53:51 +00007283 if( nArg>=2 ){
drhe93f8262018-10-11 16:53:37 +00007284 n = showHelp(p->out, azArg[1]);
drh98aa2ab2018-09-26 16:53:51 +00007285 if( n==0 ){
7286 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]);
7287 }
7288 }else{
7289 showHelp(p->out, 0);
7290 }
drh2ce15c32017-07-11 13:34:40 +00007291 }else
7292
7293 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
7294 char *zTable; /* Insert data into this table */
7295 char *zFile; /* Name of file to extra content from */
7296 sqlite3_stmt *pStmt = NULL; /* A statement */
7297 int nCol; /* Number of columns in the table */
7298 int nByte; /* Number of bytes in an SQL string */
7299 int i, j; /* Loop counters */
7300 int needCommit; /* True to COMMIT or ROLLBACK at end */
7301 int nSep; /* Number of bytes in p->colSeparator[] */
7302 char *zSql; /* An SQL statement */
7303 ImportCtx sCtx; /* Reader context */
7304 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
7305 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
7306
7307 if( nArg!=3 ){
7308 raw_printf(stderr, "Usage: .import FILE TABLE\n");
7309 goto meta_command_exit;
7310 }
7311 zFile = azArg[1];
7312 zTable = azArg[2];
7313 seenInterrupt = 0;
7314 memset(&sCtx, 0, sizeof(sCtx));
7315 open_db(p, 0);
7316 nSep = strlen30(p->colSeparator);
7317 if( nSep==0 ){
7318 raw_printf(stderr,
7319 "Error: non-null column separator required for import\n");
7320 return 1;
7321 }
7322 if( nSep>1 ){
7323 raw_printf(stderr, "Error: multi-character column separators not allowed"
7324 " for import\n");
7325 return 1;
7326 }
7327 nSep = strlen30(p->rowSeparator);
7328 if( nSep==0 ){
7329 raw_printf(stderr, "Error: non-null row separator required for import\n");
7330 return 1;
7331 }
7332 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
7333 /* When importing CSV (only), if the row separator is set to the
7334 ** default output row separator, change it to the default input
7335 ** row separator. This avoids having to maintain different input
7336 ** and output row separators. */
7337 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7338 nSep = strlen30(p->rowSeparator);
7339 }
7340 if( nSep>1 ){
7341 raw_printf(stderr, "Error: multi-character row separators not allowed"
7342 " for import\n");
7343 return 1;
7344 }
7345 sCtx.zFile = zFile;
7346 sCtx.nLine = 1;
7347 if( sCtx.zFile[0]=='|' ){
7348#ifdef SQLITE_OMIT_POPEN
7349 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7350 return 1;
7351#else
7352 sCtx.in = popen(sCtx.zFile+1, "r");
7353 sCtx.zFile = "<pipe>";
7354 xCloser = pclose;
7355#endif
7356 }else{
7357 sCtx.in = fopen(sCtx.zFile, "rb");
7358 xCloser = fclose;
7359 }
7360 if( p->mode==MODE_Ascii ){
7361 xRead = ascii_read_one_field;
7362 }else{
7363 xRead = csv_read_one_field;
7364 }
7365 if( sCtx.in==0 ){
7366 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
7367 return 1;
7368 }
7369 sCtx.cColSep = p->colSeparator[0];
7370 sCtx.cRowSep = p->rowSeparator[0];
7371 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
7372 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00007373 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00007374 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007375 }
7376 nByte = strlen30(zSql);
7377 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7378 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
7379 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
7380 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
7381 char cSep = '(';
7382 while( xRead(&sCtx) ){
7383 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
7384 cSep = ',';
7385 if( sCtx.cTerm!=sCtx.cColSep ) break;
7386 }
7387 if( cSep=='(' ){
7388 sqlite3_free(zCreate);
7389 sqlite3_free(sCtx.z);
7390 xCloser(sCtx.in);
7391 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
7392 return 1;
7393 }
7394 zCreate = sqlite3_mprintf("%z\n)", zCreate);
7395 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
7396 sqlite3_free(zCreate);
7397 if( rc ){
7398 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
7399 sqlite3_errmsg(p->db));
7400 sqlite3_free(sCtx.z);
7401 xCloser(sCtx.in);
7402 return 1;
7403 }
7404 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7405 }
7406 sqlite3_free(zSql);
7407 if( rc ){
7408 if (pStmt) sqlite3_finalize(pStmt);
7409 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
7410 xCloser(sCtx.in);
7411 return 1;
7412 }
7413 nCol = sqlite3_column_count(pStmt);
7414 sqlite3_finalize(pStmt);
7415 pStmt = 0;
7416 if( nCol==0 ) return 0; /* no columns, no error */
7417 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
7418 if( zSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00007419 xCloser(sCtx.in);
drh4b5345c2018-04-24 13:07:40 +00007420 shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00007421 }
7422 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
7423 j = strlen30(zSql);
7424 for(i=1; i<nCol; i++){
7425 zSql[j++] = ',';
7426 zSql[j++] = '?';
7427 }
7428 zSql[j++] = ')';
7429 zSql[j] = 0;
7430 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7431 sqlite3_free(zSql);
7432 if( rc ){
7433 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
7434 if (pStmt) sqlite3_finalize(pStmt);
7435 xCloser(sCtx.in);
7436 return 1;
7437 }
7438 needCommit = sqlite3_get_autocommit(p->db);
7439 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
7440 do{
7441 int startLine = sCtx.nLine;
7442 for(i=0; i<nCol; i++){
7443 char *z = xRead(&sCtx);
7444 /*
7445 ** Did we reach end-of-file before finding any columns?
7446 ** If so, stop instead of NULL filling the remaining columns.
7447 */
7448 if( z==0 && i==0 ) break;
7449 /*
7450 ** Did we reach end-of-file OR end-of-line before finding any
7451 ** columns in ASCII mode? If so, stop instead of NULL filling
7452 ** the remaining columns.
7453 */
7454 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
7455 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
7456 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
7457 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7458 "filling the rest with NULL\n",
7459 sCtx.zFile, startLine, nCol, i+1);
7460 i += 2;
7461 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
7462 }
7463 }
7464 if( sCtx.cTerm==sCtx.cColSep ){
7465 do{
7466 xRead(&sCtx);
7467 i++;
7468 }while( sCtx.cTerm==sCtx.cColSep );
7469 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
7470 "extras ignored\n",
7471 sCtx.zFile, startLine, nCol, i);
7472 }
7473 if( i>=nCol ){
7474 sqlite3_step(pStmt);
7475 rc = sqlite3_reset(pStmt);
7476 if( rc!=SQLITE_OK ){
7477 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
7478 startLine, sqlite3_errmsg(p->db));
7479 }
7480 }
7481 }while( sCtx.cTerm!=EOF );
7482
7483 xCloser(sCtx.in);
7484 sqlite3_free(sCtx.z);
7485 sqlite3_finalize(pStmt);
7486 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
7487 }else
7488
7489#ifndef SQLITE_UNTESTABLE
7490 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
7491 char *zSql;
7492 char *zCollist = 0;
7493 sqlite3_stmt *pStmt;
7494 int tnum = 0;
7495 int i;
drh48d219a2018-04-23 18:38:48 +00007496 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
7497 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
7498 " .imposter off\n");
drh2ce15c32017-07-11 13:34:40 +00007499 rc = 1;
7500 goto meta_command_exit;
7501 }
7502 open_db(p, 0);
drh48d219a2018-04-23 18:38:48 +00007503 if( nArg==2 ){
7504 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
7505 goto meta_command_exit;
7506 }
drh2ce15c32017-07-11 13:34:40 +00007507 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
7508 " WHERE name='%q' AND type='index'", azArg[1]);
7509 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7510 sqlite3_free(zSql);
7511 if( sqlite3_step(pStmt)==SQLITE_ROW ){
7512 tnum = sqlite3_column_int(pStmt, 0);
7513 }
7514 sqlite3_finalize(pStmt);
7515 if( tnum==0 ){
7516 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
7517 rc = 1;
7518 goto meta_command_exit;
7519 }
7520 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
7521 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7522 sqlite3_free(zSql);
7523 i = 0;
7524 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7525 char zLabel[20];
7526 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
7527 i++;
7528 if( zCol==0 ){
7529 if( sqlite3_column_int(pStmt,1)==-1 ){
7530 zCol = "_ROWID_";
7531 }else{
7532 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
7533 zCol = zLabel;
7534 }
7535 }
7536 if( zCollist==0 ){
7537 zCollist = sqlite3_mprintf("\"%w\"", zCol);
7538 }else{
7539 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
7540 }
7541 }
7542 sqlite3_finalize(pStmt);
7543 zSql = sqlite3_mprintf(
7544 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
7545 azArg[2], zCollist, zCollist);
7546 sqlite3_free(zCollist);
7547 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
7548 if( rc==SQLITE_OK ){
7549 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
7550 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
7551 if( rc ){
7552 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
7553 }else{
7554 utf8_printf(stdout, "%s;\n", zSql);
7555 raw_printf(stdout,
7556 "WARNING: writing to an imposter table will corrupt the index!\n"
7557 );
7558 }
7559 }else{
7560 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
7561 rc = 1;
7562 }
7563 sqlite3_free(zSql);
7564 }else
7565#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
7566
7567#ifdef SQLITE_ENABLE_IOTRACE
7568 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
7569 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
7570 if( iotrace && iotrace!=stdout ) fclose(iotrace);
7571 iotrace = 0;
7572 if( nArg<2 ){
7573 sqlite3IoTrace = 0;
7574 }else if( strcmp(azArg[1], "-")==0 ){
7575 sqlite3IoTrace = iotracePrintf;
7576 iotrace = stdout;
7577 }else{
7578 iotrace = fopen(azArg[1], "w");
7579 if( iotrace==0 ){
7580 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
7581 sqlite3IoTrace = 0;
7582 rc = 1;
7583 }else{
7584 sqlite3IoTrace = iotracePrintf;
7585 }
7586 }
7587 }else
7588#endif
7589
7590 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
7591 static const struct {
7592 const char *zLimitName; /* Name of a limit */
7593 int limitCode; /* Integer code for that limit */
7594 } aLimit[] = {
7595 { "length", SQLITE_LIMIT_LENGTH },
7596 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
7597 { "column", SQLITE_LIMIT_COLUMN },
7598 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
7599 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
7600 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
7601 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
7602 { "attached", SQLITE_LIMIT_ATTACHED },
7603 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
7604 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
7605 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
7606 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
7607 };
7608 int i, n2;
7609 open_db(p, 0);
7610 if( nArg==1 ){
7611 for(i=0; i<ArraySize(aLimit); i++){
7612 printf("%20s %d\n", aLimit[i].zLimitName,
7613 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
7614 }
7615 }else if( nArg>3 ){
7616 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
7617 rc = 1;
7618 goto meta_command_exit;
7619 }else{
7620 int iLimit = -1;
7621 n2 = strlen30(azArg[1]);
7622 for(i=0; i<ArraySize(aLimit); i++){
7623 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
7624 if( iLimit<0 ){
7625 iLimit = i;
7626 }else{
7627 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
7628 rc = 1;
7629 goto meta_command_exit;
7630 }
7631 }
7632 }
7633 if( iLimit<0 ){
7634 utf8_printf(stderr, "unknown limit: \"%s\"\n"
7635 "enter \".limits\" with no arguments for a list.\n",
7636 azArg[1]);
7637 rc = 1;
7638 goto meta_command_exit;
7639 }
7640 if( nArg==3 ){
7641 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
7642 (int)integerValue(azArg[2]));
7643 }
7644 printf("%20s %d\n", aLimit[iLimit].zLimitName,
7645 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
7646 }
7647 }else
7648
7649 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
7650 open_db(p, 0);
7651 lintDotCommand(p, azArg, nArg);
7652 }else
7653
7654#ifndef SQLITE_OMIT_LOAD_EXTENSION
7655 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
7656 const char *zFile, *zProc;
7657 char *zErrMsg = 0;
7658 if( nArg<2 ){
7659 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
7660 rc = 1;
7661 goto meta_command_exit;
7662 }
7663 zFile = azArg[1];
7664 zProc = nArg>=3 ? azArg[2] : 0;
7665 open_db(p, 0);
7666 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
7667 if( rc!=SQLITE_OK ){
7668 utf8_printf(stderr, "Error: %s\n", zErrMsg);
7669 sqlite3_free(zErrMsg);
7670 rc = 1;
7671 }
7672 }else
7673#endif
7674
7675 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
7676 if( nArg!=2 ){
7677 raw_printf(stderr, "Usage: .log FILENAME\n");
7678 rc = 1;
7679 }else{
7680 const char *zFile = azArg[1];
7681 output_file_close(p->pLog);
drha92a01a2018-01-10 22:15:37 +00007682 p->pLog = output_file_open(zFile, 0);
drh2ce15c32017-07-11 13:34:40 +00007683 }
7684 }else
7685
7686 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
7687 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00007688 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00007689 int c2 = zMode[0];
7690 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
7691 p->mode = MODE_Line;
7692 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7693 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
7694 p->mode = MODE_Column;
7695 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7696 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
7697 p->mode = MODE_List;
7698 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
7699 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7700 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
7701 p->mode = MODE_Html;
7702 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
7703 p->mode = MODE_Tcl;
7704 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
7705 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
7706 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
7707 p->mode = MODE_Csv;
7708 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
7709 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
7710 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
7711 p->mode = MODE_List;
7712 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
7713 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
7714 p->mode = MODE_Insert;
7715 set_table_name(p, nArg>=3 ? azArg[2] : "table");
7716 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
7717 p->mode = MODE_Quote;
7718 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
7719 p->mode = MODE_Ascii;
7720 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
7721 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
7722 }else if( nArg==1 ){
7723 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
7724 }else{
7725 raw_printf(stderr, "Error: mode should be one of: "
7726 "ascii column csv html insert line list quote tabs tcl\n");
7727 rc = 1;
7728 }
7729 p->cMode = p->mode;
7730 }else
7731
7732 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
7733 if( nArg==2 ){
7734 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
7735 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
7736 }else{
7737 raw_printf(stderr, "Usage: .nullvalue STRING\n");
7738 rc = 1;
7739 }
7740 }else
7741
7742 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
7743 char *zNewFilename; /* Name of the database file to open */
7744 int iName = 1; /* Index in azArg[] of the filename */
7745 int newFlag = 0; /* True to delete file before opening */
7746 /* Close the existing database */
7747 session_close_all(p);
drh9e804032018-05-18 17:11:50 +00007748 close_db(p->db);
drh2ce15c32017-07-11 13:34:40 +00007749 p->db = 0;
7750 p->zDbFilename = 0;
7751 sqlite3_free(p->zFreeOnClose);
7752 p->zFreeOnClose = 0;
drh1fa6d9f2018-01-06 21:46:01 +00007753 p->openMode = SHELL_OPEN_UNSPEC;
drh6ca64482019-01-22 16:06:20 +00007754 p->szMax = 0;
drh2ce15c32017-07-11 13:34:40 +00007755 /* Check for command-line arguments */
7756 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
7757 const char *z = azArg[iName];
7758 if( optionMatch(z,"new") ){
7759 newFlag = 1;
drh3baed312018-03-08 18:14:41 +00007760#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +00007761 }else if( optionMatch(z, "zip") ){
7762 p->openMode = SHELL_OPEN_ZIPFILE;
7763#endif
7764 }else if( optionMatch(z, "append") ){
7765 p->openMode = SHELL_OPEN_APPENDVFS;
drhee269a62018-02-14 23:27:43 +00007766 }else if( optionMatch(z, "readonly") ){
7767 p->openMode = SHELL_OPEN_READONLY;
drha751f392018-10-30 15:31:22 +00007768#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00007769 }else if( optionMatch(z, "deserialize") ){
7770 p->openMode = SHELL_OPEN_DESERIALIZE;
drh33746482018-12-13 15:06:26 +00007771 }else if( optionMatch(z, "hexdb") ){
7772 p->openMode = SHELL_OPEN_HEXDB;
drh6ca64482019-01-22 16:06:20 +00007773 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){
7774 p->szMax = integerValue(azArg[++iName]);
drh33746482018-12-13 15:06:26 +00007775#endif /* SQLITE_ENABLE_DESERIALIZE */
drh2ce15c32017-07-11 13:34:40 +00007776 }else if( z[0]=='-' ){
7777 utf8_printf(stderr, "unknown option: %s\n", z);
7778 rc = 1;
7779 goto meta_command_exit;
7780 }
7781 }
7782 /* If a filename is specified, try to open it first */
7783 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
drh33746482018-12-13 15:06:26 +00007784 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
drh2ce15c32017-07-11 13:34:40 +00007785 if( newFlag ) shellDeleteFile(zNewFilename);
7786 p->zDbFilename = zNewFilename;
drhbe4ccb22018-05-17 20:04:24 +00007787 open_db(p, OPEN_DB_KEEPALIVE);
drh2ce15c32017-07-11 13:34:40 +00007788 if( p->db==0 ){
7789 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
7790 sqlite3_free(zNewFilename);
7791 }else{
7792 p->zFreeOnClose = zNewFilename;
7793 }
7794 }
7795 if( p->db==0 ){
7796 /* As a fall-back open a TEMP database */
7797 p->zDbFilename = 0;
7798 open_db(p, 0);
7799 }
7800 }else
7801
drh13c20932018-01-10 21:41:55 +00007802 if( (c=='o'
7803 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
7804 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
drh2ce15c32017-07-11 13:34:40 +00007805 ){
7806 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
drha92a01a2018-01-10 22:15:37 +00007807 int bTxtMode = 0;
drh13c20932018-01-10 21:41:55 +00007808 if( azArg[0][0]=='e' ){
7809 /* Transform the ".excel" command into ".once -x" */
7810 nArg = 2;
7811 azArg[0] = "once";
7812 zFile = azArg[1] = "-x";
7813 n = 4;
7814 }
drh2ce15c32017-07-11 13:34:40 +00007815 if( nArg>2 ){
drh13c20932018-01-10 21:41:55 +00007816 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
drh2ce15c32017-07-11 13:34:40 +00007817 rc = 1;
7818 goto meta_command_exit;
7819 }
7820 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
7821 if( nArg<2 ){
drh13c20932018-01-10 21:41:55 +00007822 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
drh2ce15c32017-07-11 13:34:40 +00007823 rc = 1;
7824 goto meta_command_exit;
7825 }
7826 p->outCount = 2;
7827 }else{
7828 p->outCount = 0;
7829 }
7830 output_reset(p);
drh13c20932018-01-10 21:41:55 +00007831 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
drh04a28c32018-01-31 01:38:44 +00007832#ifndef SQLITE_NOHAVE_SYSTEM
drh13c20932018-01-10 21:41:55 +00007833 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
drh3c484e82018-01-10 22:27:21 +00007834 p->doXdgOpen = 1;
7835 outputModePush(p);
drh13c20932018-01-10 21:41:55 +00007836 if( zFile[1]=='x' ){
7837 newTempFile(p, "csv");
7838 p->mode = MODE_Csv;
7839 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
7840 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
7841 }else{
7842 newTempFile(p, "txt");
drha92a01a2018-01-10 22:15:37 +00007843 bTxtMode = 1;
drh13c20932018-01-10 21:41:55 +00007844 }
7845 zFile = p->zTempFile;
7846 }
drh04a28c32018-01-31 01:38:44 +00007847#endif /* SQLITE_NOHAVE_SYSTEM */
drh2ce15c32017-07-11 13:34:40 +00007848 if( zFile[0]=='|' ){
7849#ifdef SQLITE_OMIT_POPEN
7850 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
7851 rc = 1;
7852 p->out = stdout;
7853#else
7854 p->out = popen(zFile + 1, "w");
7855 if( p->out==0 ){
7856 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
7857 p->out = stdout;
7858 rc = 1;
7859 }else{
7860 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7861 }
7862#endif
7863 }else{
drha92a01a2018-01-10 22:15:37 +00007864 p->out = output_file_open(zFile, bTxtMode);
drh2ce15c32017-07-11 13:34:40 +00007865 if( p->out==0 ){
7866 if( strcmp(zFile,"off")!=0 ){
7867 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
7868 }
7869 p->out = stdout;
7870 rc = 1;
7871 } else {
7872 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
7873 }
7874 }
7875 }else
7876
drh9cb02642019-02-28 20:10:52 +00007877 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){
7878 open_db(p,0);
7879 if( nArg<=1 ) goto parameter_syntax_error;
7880
7881 /* .parameter clear
7882 ** Clear all bind parameters by dropping the TEMP table that holds them.
7883 */
7884 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){
drh346f4e22019-03-25 21:35:41 +00007885 int wrSchema = 0;
7886 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
7887 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
drh65c29fd2019-03-25 21:56:26 +00007888 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;",
drh9cb02642019-02-28 20:10:52 +00007889 0, 0, 0);
drh346f4e22019-03-25 21:35:41 +00007890 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
drh9cb02642019-02-28 20:10:52 +00007891 }else
7892
7893 /* .parameter list
7894 ** List all bind parameters.
7895 */
7896 if( nArg==2 && strcmp(azArg[1],"list")==0 ){
7897 sqlite3_stmt *pStmt = 0;
7898 int rx;
7899 int len = 0;
7900 rx = sqlite3_prepare_v2(p->db,
7901 "SELECT max(length(key)) "
drh65c29fd2019-03-25 21:56:26 +00007902 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
drh9cb02642019-02-28 20:10:52 +00007903 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){
7904 len = sqlite3_column_int(pStmt, 0);
7905 if( len>40 ) len = 40;
7906 }
7907 sqlite3_finalize(pStmt);
7908 pStmt = 0;
7909 if( len ){
7910 rx = sqlite3_prepare_v2(p->db,
7911 "SELECT key, quote(value) "
drh65c29fd2019-03-25 21:56:26 +00007912 "FROM temp.sqlite_parameters;", -1, &pStmt, 0);
drh9cb02642019-02-28 20:10:52 +00007913 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7914 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0),
7915 sqlite3_column_text(pStmt,1));
7916 }
7917 sqlite3_finalize(pStmt);
7918 }
7919 }else
7920
7921 /* .parameter init
7922 ** Make sure the TEMP table used to hold bind parameters exists.
7923 ** Create it if necessary.
7924 */
7925 if( nArg==2 && strcmp(azArg[1],"init")==0 ){
7926 bind_table_init(p);
7927 }else
7928
7929 /* .parameter set NAME VALUE
7930 ** Set or reset a bind parameter. NAME should be the full parameter
7931 ** name exactly as it appears in the query. (ex: $abc, @def). The
7932 ** VALUE can be in either SQL literal notation, or if not it will be
7933 ** understood to be a text string.
7934 */
7935 if( nArg==4 && strcmp(azArg[1],"set")==0 ){
7936 int rx;
7937 char *zSql;
7938 sqlite3_stmt *pStmt;
7939 const char *zKey = azArg[2];
7940 const char *zValue = azArg[3];
7941 bind_table_init(p);
7942 zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007943 "REPLACE INTO temp.sqlite_parameters(key,value)"
drh9cb02642019-02-28 20:10:52 +00007944 "VALUES(%Q,%s);", zKey, zValue);
7945 if( zSql==0 ) shell_out_of_memory();
7946 pStmt = 0;
7947 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7948 sqlite3_free(zSql);
7949 if( rx!=SQLITE_OK ){
7950 sqlite3_finalize(pStmt);
7951 pStmt = 0;
7952 zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007953 "REPLACE INTO temp.sqlite_parameters(key,value)"
drh9cb02642019-02-28 20:10:52 +00007954 "VALUES(%Q,%Q);", zKey, zValue);
7955 if( zSql==0 ) shell_out_of_memory();
7956 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7957 sqlite3_free(zSql);
7958 if( rx!=SQLITE_OK ){
7959 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db));
7960 sqlite3_finalize(pStmt);
7961 pStmt = 0;
7962 rc = 1;
7963 }
7964 }
7965 sqlite3_step(pStmt);
7966 sqlite3_finalize(pStmt);
7967 }else
7968
7969 /* .parameter unset NAME
7970 ** Remove the NAME binding from the parameter binding table, if it
7971 ** exists.
7972 */
7973 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){
7974 char *zSql = sqlite3_mprintf(
drh65c29fd2019-03-25 21:56:26 +00007975 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]);
drh9cb02642019-02-28 20:10:52 +00007976 if( zSql==0 ) shell_out_of_memory();
7977 sqlite3_exec(p->db, zSql, 0, 0, 0);
7978 sqlite3_free(zSql);
7979 }else
7980 /* If no command name matches, show a syntax error */
7981 parameter_syntax_error:
7982 showHelp(p->out, "parameter");
7983 }else
7984
drh2ce15c32017-07-11 13:34:40 +00007985 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
7986 int i;
7987 for(i=1; i<nArg; i++){
7988 if( i>1 ) raw_printf(p->out, " ");
7989 utf8_printf(p->out, "%s", azArg[i]);
7990 }
7991 raw_printf(p->out, "\n");
7992 }else
7993
drh569b1d92019-02-05 20:51:41 +00007994#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
drh3f83f592019-02-04 14:53:18 +00007995 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){
7996 int i;
drhfc4eeef2019-02-05 19:48:46 +00007997 int nn = 0;
drh3f83f592019-02-04 14:53:18 +00007998 p->flgProgress = 0;
7999 p->mxProgress = 0;
8000 p->nProgress = 0;
8001 for(i=1; i<nArg; i++){
8002 const char *z = azArg[i];
8003 if( z[0]=='-' ){
8004 z++;
8005 if( z[0]=='-' ) z++;
8006 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00008007 p->flgProgress |= SHELL_PROGRESS_QUIET;
drh3f83f592019-02-04 14:53:18 +00008008 continue;
8009 }
8010 if( strcmp(z,"reset")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00008011 p->flgProgress |= SHELL_PROGRESS_RESET;
drh3f83f592019-02-04 14:53:18 +00008012 continue;
8013 }
8014 if( strcmp(z,"once")==0 ){
drhfc4eeef2019-02-05 19:48:46 +00008015 p->flgProgress |= SHELL_PROGRESS_ONCE;
drh3f83f592019-02-04 14:53:18 +00008016 continue;
8017 }
8018 if( strcmp(z,"limit")==0 ){
8019 if( i+1>=nArg ){
8020 utf8_printf(stderr, "Error: missing argument on --limit\n");
8021 rc = 1;
8022 goto meta_command_exit;
8023 }else{
8024 p->mxProgress = (int)integerValue(azArg[++i]);
8025 }
8026 continue;
8027 }
8028 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]);
8029 rc = 1;
8030 goto meta_command_exit;
8031 }else{
drhfc4eeef2019-02-05 19:48:46 +00008032 nn = (int)integerValue(z);
drh3f83f592019-02-04 14:53:18 +00008033 }
8034 }
8035 open_db(p, 0);
drhfc4eeef2019-02-05 19:48:46 +00008036 sqlite3_progress_handler(p->db, nn, progress_handler, p);
drh3f83f592019-02-04 14:53:18 +00008037 }else
drh569b1d92019-02-05 20:51:41 +00008038#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
drh3f83f592019-02-04 14:53:18 +00008039
drh2ce15c32017-07-11 13:34:40 +00008040 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
8041 if( nArg >= 2) {
8042 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
8043 }
8044 if( nArg >= 3) {
8045 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
8046 }
8047 }else
8048
8049 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
8050 rc = 2;
8051 }else
8052
8053 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
drh60379d42018-12-13 18:30:01 +00008054 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00008055 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00008056 if( nArg!=2 ){
8057 raw_printf(stderr, "Usage: .read FILE\n");
8058 rc = 1;
8059 goto meta_command_exit;
8060 }
drh60379d42018-12-13 18:30:01 +00008061 p->in = fopen(azArg[1], "rb");
8062 if( p->in==0 ){
drh2ce15c32017-07-11 13:34:40 +00008063 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
8064 rc = 1;
8065 }else{
drh60379d42018-12-13 18:30:01 +00008066 rc = process_input(p);
8067 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00008068 }
drh60379d42018-12-13 18:30:01 +00008069 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00008070 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00008071 }else
8072
8073 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
8074 const char *zSrcFile;
8075 const char *zDb;
8076 sqlite3 *pSrc;
8077 sqlite3_backup *pBackup;
8078 int nTimeout = 0;
8079
8080 if( nArg==2 ){
8081 zSrcFile = azArg[1];
8082 zDb = "main";
8083 }else if( nArg==3 ){
8084 zSrcFile = azArg[2];
8085 zDb = azArg[1];
8086 }else{
8087 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
8088 rc = 1;
8089 goto meta_command_exit;
8090 }
8091 rc = sqlite3_open(zSrcFile, &pSrc);
8092 if( rc!=SQLITE_OK ){
8093 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9e804032018-05-18 17:11:50 +00008094 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00008095 return 1;
8096 }
8097 open_db(p, 0);
8098 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
8099 if( pBackup==0 ){
8100 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9e804032018-05-18 17:11:50 +00008101 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00008102 return 1;
8103 }
8104 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
8105 || rc==SQLITE_BUSY ){
8106 if( rc==SQLITE_BUSY ){
8107 if( nTimeout++ >= 3 ) break;
8108 sqlite3_sleep(100);
8109 }
8110 }
8111 sqlite3_backup_finish(pBackup);
8112 if( rc==SQLITE_DONE ){
8113 rc = 0;
8114 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
8115 raw_printf(stderr, "Error: source database is busy\n");
8116 rc = 1;
8117 }else{
8118 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8119 rc = 1;
8120 }
drh9e804032018-05-18 17:11:50 +00008121 close_db(pSrc);
drh2ce15c32017-07-11 13:34:40 +00008122 }else
8123
drh2ce15c32017-07-11 13:34:40 +00008124 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
8125 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00008126 p->scanstatsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00008127#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
8128 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
8129#endif
8130 }else{
8131 raw_printf(stderr, "Usage: .scanstats on|off\n");
8132 rc = 1;
8133 }
8134 }else
8135
8136 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
8137 ShellText sSelect;
8138 ShellState data;
8139 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00008140 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00008141 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00008142 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00008143 int bDebug = 0;
8144 int ii;
drh2ce15c32017-07-11 13:34:40 +00008145
8146 open_db(p, 0);
8147 memcpy(&data, p, sizeof(data));
8148 data.showHeader = 0;
8149 data.cMode = data.mode = MODE_Semi;
8150 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00008151 for(ii=1; ii<nArg; ii++){
8152 if( optionMatch(azArg[ii],"indent") ){
8153 data.cMode = data.mode = MODE_Pretty;
8154 }else if( optionMatch(azArg[ii],"debug") ){
8155 bDebug = 1;
8156 }else if( zName==0 ){
8157 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00008158 }else{
drhceba7922018-01-01 21:28:25 +00008159 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
8160 rc = 1;
8161 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00008162 }
drh2ce15c32017-07-11 13:34:40 +00008163 }
drhceba7922018-01-01 21:28:25 +00008164 if( zName!=0 ){
mistachkin9d107262018-03-23 14:24:34 +00008165 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
8166 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
drh2ce15c32017-07-11 13:34:40 +00008167 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00008168 new_argv[0] = sqlite3_mprintf(
8169 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00008170 " type text,\n"
8171 " name text,\n"
8172 " tbl_name text,\n"
8173 " rootpage integer,\n"
8174 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00008175 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00008176 new_argv[1] = 0;
8177 new_colv[0] = "sql";
8178 new_colv[1] = 0;
8179 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00008180 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00008181 }
drh2ce15c32017-07-11 13:34:40 +00008182 }
8183 if( zDiv ){
8184 sqlite3_stmt *pStmt = 0;
8185 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
8186 -1, &pStmt, 0);
8187 if( rc ){
8188 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
8189 sqlite3_finalize(pStmt);
8190 rc = 1;
8191 goto meta_command_exit;
8192 }
8193 appendText(&sSelect, "SELECT sql FROM", 0);
8194 iSchema = 0;
8195 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8196 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
8197 char zScNum[30];
8198 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
8199 appendText(&sSelect, zDiv, 0);
8200 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00008201 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
8202 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00008203 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00008204 }else{
drhceba7922018-01-01 21:28:25 +00008205 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00008206 }
drhceba7922018-01-01 21:28:25 +00008207 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
8208 appendText(&sSelect, zScNum, 0);
8209 appendText(&sSelect, " AS snum, ", 0);
8210 appendText(&sSelect, zDb, '\'');
8211 appendText(&sSelect, " AS sname FROM ", 0);
8212 appendText(&sSelect, zDb, '"');
8213 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00008214 }
8215 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00008216#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00008217 if( zName ){
8218 appendText(&sSelect,
8219 " UNION ALL SELECT shell_module_schema(name),"
8220 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
8221 }
drhcde7b772018-01-02 12:50:40 +00008222#endif
drh2ce15c32017-07-11 13:34:40 +00008223 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00008224 if( zName ){
8225 char *zQarg = sqlite3_mprintf("%Q", zName);
mistachkin9d107262018-03-23 14:24:34 +00008226 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
8227 strchr(zName, '[') != 0;
drhceba7922018-01-01 21:28:25 +00008228 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00008229 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
8230 }else{
8231 appendText(&sSelect, "lower(tbl_name)", 0);
8232 }
mistachkin9d107262018-03-23 14:24:34 +00008233 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00008234 appendText(&sSelect, zQarg, 0);
mistachkin9d107262018-03-23 14:24:34 +00008235 if( !bGlob ){
8236 appendText(&sSelect, " ESCAPE '\\' ", 0);
8237 }
drh2ce15c32017-07-11 13:34:40 +00008238 appendText(&sSelect, " AND ", 0);
8239 sqlite3_free(zQarg);
8240 }
8241 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
8242 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00008243 if( bDebug ){
8244 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
8245 }else{
8246 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
8247 }
drh2ce15c32017-07-11 13:34:40 +00008248 freeText(&sSelect);
8249 }
8250 if( zErrMsg ){
8251 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8252 sqlite3_free(zErrMsg);
8253 rc = 1;
8254 }else if( rc != SQLITE_OK ){
8255 raw_printf(stderr,"Error: querying schema information\n");
8256 rc = 1;
8257 }else{
8258 rc = 0;
8259 }
8260 }else
8261
8262#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
8263 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
8264 sqlite3SelectTrace = (int)integerValue(azArg[1]);
8265 }else
8266#endif
8267
8268#if defined(SQLITE_ENABLE_SESSION)
8269 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
8270 OpenSession *pSession = &p->aSession[0];
8271 char **azCmd = &azArg[1];
8272 int iSes = 0;
8273 int nCmd = nArg - 1;
8274 int i;
8275 if( nArg<=1 ) goto session_syntax_error;
8276 open_db(p, 0);
8277 if( nArg>=3 ){
8278 for(iSes=0; iSes<p->nSession; iSes++){
8279 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
8280 }
8281 if( iSes<p->nSession ){
8282 pSession = &p->aSession[iSes];
8283 azCmd++;
8284 nCmd--;
8285 }else{
8286 pSession = &p->aSession[0];
8287 iSes = 0;
8288 }
8289 }
8290
8291 /* .session attach TABLE
8292 ** Invoke the sqlite3session_attach() interface to attach a particular
8293 ** table so that it is never filtered.
8294 */
8295 if( strcmp(azCmd[0],"attach")==0 ){
8296 if( nCmd!=2 ) goto session_syntax_error;
8297 if( pSession->p==0 ){
8298 session_not_open:
8299 raw_printf(stderr, "ERROR: No sessions are open\n");
8300 }else{
8301 rc = sqlite3session_attach(pSession->p, azCmd[1]);
8302 if( rc ){
8303 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
8304 rc = 0;
8305 }
8306 }
8307 }else
8308
8309 /* .session changeset FILE
8310 ** .session patchset FILE
8311 ** Write a changeset or patchset into a file. The file is overwritten.
8312 */
8313 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
8314 FILE *out = 0;
8315 if( nCmd!=2 ) goto session_syntax_error;
8316 if( pSession->p==0 ) goto session_not_open;
8317 out = fopen(azCmd[1], "wb");
8318 if( out==0 ){
8319 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
8320 }else{
8321 int szChng;
8322 void *pChng;
8323 if( azCmd[0][0]=='c' ){
8324 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
8325 }else{
8326 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
8327 }
8328 if( rc ){
8329 printf("Error: error code %d\n", rc);
8330 rc = 0;
8331 }
8332 if( pChng
8333 && fwrite(pChng, szChng, 1, out)!=1 ){
8334 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
8335 szChng);
8336 }
8337 sqlite3_free(pChng);
8338 fclose(out);
8339 }
8340 }else
8341
8342 /* .session close
8343 ** Close the identified session
8344 */
8345 if( strcmp(azCmd[0], "close")==0 ){
8346 if( nCmd!=1 ) goto session_syntax_error;
8347 if( p->nSession ){
8348 session_close(pSession);
8349 p->aSession[iSes] = p->aSession[--p->nSession];
8350 }
8351 }else
8352
8353 /* .session enable ?BOOLEAN?
8354 ** Query or set the enable flag
8355 */
8356 if( strcmp(azCmd[0], "enable")==0 ){
8357 int ii;
8358 if( nCmd>2 ) goto session_syntax_error;
8359 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8360 if( p->nSession ){
8361 ii = sqlite3session_enable(pSession->p, ii);
8362 utf8_printf(p->out, "session %s enable flag = %d\n",
8363 pSession->zName, ii);
8364 }
8365 }else
8366
8367 /* .session filter GLOB ....
8368 ** Set a list of GLOB patterns of table names to be excluded.
8369 */
8370 if( strcmp(azCmd[0], "filter")==0 ){
8371 int ii, nByte;
8372 if( nCmd<2 ) goto session_syntax_error;
8373 if( p->nSession ){
8374 for(ii=0; ii<pSession->nFilter; ii++){
8375 sqlite3_free(pSession->azFilter[ii]);
8376 }
8377 sqlite3_free(pSession->azFilter);
8378 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
8379 pSession->azFilter = sqlite3_malloc( nByte );
8380 if( pSession->azFilter==0 ){
8381 raw_printf(stderr, "Error: out or memory\n");
8382 exit(1);
8383 }
8384 for(ii=1; ii<nCmd; ii++){
8385 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
8386 }
8387 pSession->nFilter = ii-1;
8388 }
8389 }else
8390
8391 /* .session indirect ?BOOLEAN?
8392 ** Query or set the indirect flag
8393 */
8394 if( strcmp(azCmd[0], "indirect")==0 ){
8395 int ii;
8396 if( nCmd>2 ) goto session_syntax_error;
8397 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
8398 if( p->nSession ){
8399 ii = sqlite3session_indirect(pSession->p, ii);
8400 utf8_printf(p->out, "session %s indirect flag = %d\n",
8401 pSession->zName, ii);
8402 }
8403 }else
8404
8405 /* .session isempty
8406 ** Determine if the session is empty
8407 */
8408 if( strcmp(azCmd[0], "isempty")==0 ){
8409 int ii;
8410 if( nCmd!=1 ) goto session_syntax_error;
8411 if( p->nSession ){
8412 ii = sqlite3session_isempty(pSession->p);
8413 utf8_printf(p->out, "session %s isempty flag = %d\n",
8414 pSession->zName, ii);
8415 }
8416 }else
8417
8418 /* .session list
8419 ** List all currently open sessions
8420 */
8421 if( strcmp(azCmd[0],"list")==0 ){
8422 for(i=0; i<p->nSession; i++){
8423 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
8424 }
8425 }else
8426
8427 /* .session open DB NAME
8428 ** Open a new session called NAME on the attached database DB.
8429 ** DB is normally "main".
8430 */
8431 if( strcmp(azCmd[0],"open")==0 ){
8432 char *zName;
8433 if( nCmd!=3 ) goto session_syntax_error;
8434 zName = azCmd[2];
8435 if( zName[0]==0 ) goto session_syntax_error;
8436 for(i=0; i<p->nSession; i++){
8437 if( strcmp(p->aSession[i].zName,zName)==0 ){
8438 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
8439 goto meta_command_exit;
8440 }
8441 }
8442 if( p->nSession>=ArraySize(p->aSession) ){
8443 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
8444 goto meta_command_exit;
8445 }
8446 pSession = &p->aSession[p->nSession];
8447 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
8448 if( rc ){
8449 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
8450 rc = 0;
8451 goto meta_command_exit;
8452 }
8453 pSession->nFilter = 0;
8454 sqlite3session_table_filter(pSession->p, session_filter, pSession);
8455 p->nSession++;
8456 pSession->zName = sqlite3_mprintf("%s", zName);
8457 }else
8458 /* If no command name matches, show a syntax error */
8459 session_syntax_error:
drheb7f2a02018-09-26 18:02:32 +00008460 showHelp(p->out, "session");
drh2ce15c32017-07-11 13:34:40 +00008461 }else
8462#endif
8463
8464#ifdef SQLITE_DEBUG
8465 /* Undocumented commands for internal testing. Subject to change
8466 ** without notice. */
8467 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
8468 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
8469 int i, v;
8470 for(i=1; i<nArg; i++){
8471 v = booleanValue(azArg[i]);
8472 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
8473 }
8474 }
8475 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
8476 int i; sqlite3_int64 v;
8477 for(i=1; i<nArg; i++){
8478 char zBuf[200];
8479 v = integerValue(azArg[i]);
8480 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
8481 utf8_printf(p->out, "%s", zBuf);
8482 }
8483 }
8484 }else
8485#endif
8486
8487 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
8488 int bIsInit = 0; /* True to initialize the SELFTEST table */
8489 int bVerbose = 0; /* Verbose output */
8490 int bSelftestExists; /* True if SELFTEST already exists */
8491 int i, k; /* Loop counters */
8492 int nTest = 0; /* Number of tests runs */
8493 int nErr = 0; /* Number of errors seen */
8494 ShellText str; /* Answer for a query */
8495 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
8496
8497 open_db(p,0);
8498 for(i=1; i<nArg; i++){
8499 const char *z = azArg[i];
8500 if( z[0]=='-' && z[1]=='-' ) z++;
8501 if( strcmp(z,"-init")==0 ){
8502 bIsInit = 1;
8503 }else
8504 if( strcmp(z,"-v")==0 ){
8505 bVerbose++;
8506 }else
8507 {
8508 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8509 azArg[i], azArg[0]);
8510 raw_printf(stderr, "Should be one of: --init -v\n");
8511 rc = 1;
8512 goto meta_command_exit;
8513 }
8514 }
8515 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
8516 != SQLITE_OK ){
8517 bSelftestExists = 0;
8518 }else{
8519 bSelftestExists = 1;
8520 }
8521 if( bIsInit ){
8522 createSelftestTable(p);
8523 bSelftestExists = 1;
8524 }
8525 initText(&str);
8526 appendText(&str, "x", 0);
8527 for(k=bSelftestExists; k>=0; k--){
8528 if( k==1 ){
8529 rc = sqlite3_prepare_v2(p->db,
8530 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
8531 -1, &pStmt, 0);
8532 }else{
8533 rc = sqlite3_prepare_v2(p->db,
8534 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
8535 " (1,'run','PRAGMA integrity_check','ok')",
8536 -1, &pStmt, 0);
8537 }
8538 if( rc ){
8539 raw_printf(stderr, "Error querying the selftest table\n");
8540 rc = 1;
8541 sqlite3_finalize(pStmt);
8542 goto meta_command_exit;
8543 }
8544 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
8545 int tno = sqlite3_column_int(pStmt, 0);
8546 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
8547 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
8548 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
8549
8550 k = 0;
8551 if( bVerbose>0 ){
8552 char *zQuote = sqlite3_mprintf("%q", zSql);
8553 printf("%d: %s %s\n", tno, zOp, zSql);
8554 sqlite3_free(zQuote);
8555 }
8556 if( strcmp(zOp,"memo")==0 ){
8557 utf8_printf(p->out, "%s\n", zSql);
8558 }else
8559 if( strcmp(zOp,"run")==0 ){
8560 char *zErrMsg = 0;
8561 str.n = 0;
8562 str.z[0] = 0;
8563 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
8564 nTest++;
8565 if( bVerbose ){
8566 utf8_printf(p->out, "Result: %s\n", str.z);
8567 }
8568 if( rc || zErrMsg ){
8569 nErr++;
8570 rc = 1;
8571 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
8572 sqlite3_free(zErrMsg);
8573 }else if( strcmp(zAns,str.z)!=0 ){
8574 nErr++;
8575 rc = 1;
8576 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
8577 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
8578 }
8579 }else
8580 {
8581 utf8_printf(stderr,
8582 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
8583 rc = 1;
8584 break;
8585 }
8586 } /* End loop over rows of content from SELFTEST */
8587 sqlite3_finalize(pStmt);
8588 } /* End loop over k */
8589 freeText(&str);
8590 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
8591 }else
8592
8593 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
8594 if( nArg<2 || nArg>3 ){
8595 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
8596 rc = 1;
8597 }
8598 if( nArg>=2 ){
8599 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
8600 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
8601 }
8602 if( nArg>=3 ){
8603 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
8604 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
8605 }
8606 }else
8607
8608 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
8609 const char *zLike = 0; /* Which table to checksum. 0 means everything */
8610 int i; /* Loop counter */
8611 int bSchema = 0; /* Also hash the schema */
8612 int bSeparate = 0; /* Hash each table separately */
8613 int iSize = 224; /* Hash algorithm to use */
8614 int bDebug = 0; /* Only show the query that would have run */
8615 sqlite3_stmt *pStmt; /* For querying tables names */
8616 char *zSql; /* SQL to be run */
8617 char *zSep; /* Separator */
8618 ShellText sSql; /* Complete SQL for the query to run the hash */
8619 ShellText sQuery; /* Set of queries used to read all content */
8620 open_db(p, 0);
8621 for(i=1; i<nArg; i++){
8622 const char *z = azArg[i];
8623 if( z[0]=='-' ){
8624 z++;
8625 if( z[0]=='-' ) z++;
8626 if( strcmp(z,"schema")==0 ){
8627 bSchema = 1;
8628 }else
8629 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
8630 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
8631 ){
8632 iSize = atoi(&z[5]);
8633 }else
8634 if( strcmp(z,"debug")==0 ){
8635 bDebug = 1;
8636 }else
8637 {
8638 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
8639 azArg[i], azArg[0]);
8640 raw_printf(stderr, "Should be one of: --schema"
drh003edba2018-05-11 15:10:43 +00008641 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
drh2ce15c32017-07-11 13:34:40 +00008642 rc = 1;
8643 goto meta_command_exit;
8644 }
8645 }else if( zLike ){
8646 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
8647 rc = 1;
8648 goto meta_command_exit;
8649 }else{
8650 zLike = z;
8651 bSeparate = 1;
drhcedfecf2018-03-23 12:59:10 +00008652 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
drh2ce15c32017-07-11 13:34:40 +00008653 }
8654 }
8655 if( bSchema ){
8656 zSql = "SELECT lower(name) FROM sqlite_master"
8657 " WHERE type='table' AND coalesce(rootpage,0)>1"
8658 " UNION ALL SELECT 'sqlite_master'"
8659 " ORDER BY 1 collate nocase";
8660 }else{
8661 zSql = "SELECT lower(name) FROM sqlite_master"
8662 " WHERE type='table' AND coalesce(rootpage,0)>1"
8663 " AND name NOT LIKE 'sqlite_%'"
8664 " ORDER BY 1 collate nocase";
8665 }
8666 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
8667 initText(&sQuery);
8668 initText(&sSql);
8669 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
8670 zSep = "VALUES(";
8671 while( SQLITE_ROW==sqlite3_step(pStmt) ){
8672 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
8673 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
8674 if( strncmp(zTab, "sqlite_",7)!=0 ){
8675 appendText(&sQuery,"SELECT * FROM ", 0);
8676 appendText(&sQuery,zTab,'"');
8677 appendText(&sQuery," NOT INDEXED;", 0);
8678 }else if( strcmp(zTab, "sqlite_master")==0 ){
8679 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
8680 " ORDER BY name;", 0);
8681 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
8682 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
8683 " ORDER BY name;", 0);
8684 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
8685 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
8686 " ORDER BY tbl,idx;", 0);
8687 }else if( strcmp(zTab, "sqlite_stat3")==0
8688 || strcmp(zTab, "sqlite_stat4")==0 ){
8689 appendText(&sQuery, "SELECT * FROM ", 0);
8690 appendText(&sQuery, zTab, 0);
8691 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
8692 }
8693 appendText(&sSql, zSep, 0);
8694 appendText(&sSql, sQuery.z, '\'');
8695 sQuery.n = 0;
8696 appendText(&sSql, ",", 0);
8697 appendText(&sSql, zTab, '\'');
8698 zSep = "),(";
8699 }
8700 sqlite3_finalize(pStmt);
8701 if( bSeparate ){
8702 zSql = sqlite3_mprintf(
8703 "%s))"
8704 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
8705 " FROM [sha3sum$query]",
8706 sSql.z, iSize);
8707 }else{
8708 zSql = sqlite3_mprintf(
8709 "%s))"
8710 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
8711 " FROM [sha3sum$query]",
8712 sSql.z, iSize);
8713 }
8714 freeText(&sQuery);
8715 freeText(&sSql);
8716 if( bDebug ){
8717 utf8_printf(p->out, "%s\n", zSql);
8718 }else{
drha10b9992018-03-09 15:24:33 +00008719 shell_exec(p, zSql, 0);
drh2ce15c32017-07-11 13:34:40 +00008720 }
8721 sqlite3_free(zSql);
8722 }else
8723
drh04a28c32018-01-31 01:38:44 +00008724#ifndef SQLITE_NOHAVE_SYSTEM
drh2ce15c32017-07-11 13:34:40 +00008725 if( c=='s'
8726 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
8727 ){
8728 char *zCmd;
8729 int i, x;
8730 if( nArg<2 ){
8731 raw_printf(stderr, "Usage: .system COMMAND\n");
8732 rc = 1;
8733 goto meta_command_exit;
8734 }
8735 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
8736 for(i=2; i<nArg; i++){
8737 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
8738 zCmd, azArg[i]);
8739 }
8740 x = system(zCmd);
8741 sqlite3_free(zCmd);
8742 if( x ) raw_printf(stderr, "System command returns %d\n", x);
8743 }else
drh04a28c32018-01-31 01:38:44 +00008744#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
drh2ce15c32017-07-11 13:34:40 +00008745
8746 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00008747 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00008748 int i;
8749 if( nArg!=1 ){
8750 raw_printf(stderr, "Usage: .show\n");
8751 rc = 1;
8752 goto meta_command_exit;
8753 }
8754 utf8_printf(p->out, "%12.12s: %s\n","echo",
8755 azBool[ShellHasFlag(p, SHFLG_Echo)]);
8756 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
8757 utf8_printf(p->out, "%12.12s: %s\n","explain",
8758 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
8759 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
8760 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
8761 utf8_printf(p->out, "%12.12s: ", "nullvalue");
8762 output_c_string(p->out, p->nullValue);
8763 raw_printf(p->out, "\n");
8764 utf8_printf(p->out,"%12.12s: %s\n","output",
8765 strlen30(p->outfile) ? p->outfile : "stdout");
8766 utf8_printf(p->out,"%12.12s: ", "colseparator");
8767 output_c_string(p->out, p->colSeparator);
8768 raw_printf(p->out, "\n");
8769 utf8_printf(p->out,"%12.12s: ", "rowseparator");
8770 output_c_string(p->out, p->rowSeparator);
8771 raw_printf(p->out, "\n");
8772 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
8773 utf8_printf(p->out, "%12.12s: ", "width");
8774 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
8775 raw_printf(p->out, "%d ", p->colWidth[i]);
8776 }
8777 raw_printf(p->out, "\n");
8778 utf8_printf(p->out, "%12.12s: %s\n", "filename",
8779 p->zDbFilename ? p->zDbFilename : "");
8780 }else
8781
8782 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
8783 if( nArg==2 ){
mistachkinb71aa092018-01-23 00:05:18 +00008784 p->statsOn = (u8)booleanValue(azArg[1]);
drh2ce15c32017-07-11 13:34:40 +00008785 }else if( nArg==1 ){
8786 display_stats(p->db, p, 0);
8787 }else{
8788 raw_printf(stderr, "Usage: .stats ?on|off?\n");
8789 rc = 1;
8790 }
8791 }else
8792
8793 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
8794 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
8795 || strncmp(azArg[0], "indexes", n)==0) )
8796 ){
8797 sqlite3_stmt *pStmt;
8798 char **azResult;
8799 int nRow, nAlloc;
8800 int ii;
8801 ShellText s;
8802 initText(&s);
8803 open_db(p, 0);
8804 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
drh9e804032018-05-18 17:11:50 +00008805 if( rc ){
8806 sqlite3_finalize(pStmt);
8807 return shellDatabaseError(p->db);
8808 }
drh2ce15c32017-07-11 13:34:40 +00008809
8810 if( nArg>2 && c=='i' ){
8811 /* It is an historical accident that the .indexes command shows an error
8812 ** when called with the wrong number of arguments whereas the .tables
8813 ** command does not. */
8814 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
8815 rc = 1;
drh9e804032018-05-18 17:11:50 +00008816 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00008817 goto meta_command_exit;
8818 }
8819 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
8820 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
8821 if( zDbName==0 ) continue;
8822 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
8823 if( sqlite3_stricmp(zDbName, "main")==0 ){
8824 appendText(&s, "SELECT name FROM ", 0);
8825 }else{
8826 appendText(&s, "SELECT ", 0);
8827 appendText(&s, zDbName, '\'');
8828 appendText(&s, "||'.'||name FROM ", 0);
8829 }
8830 appendText(&s, zDbName, '"');
8831 appendText(&s, ".sqlite_master ", 0);
8832 if( c=='t' ){
8833 appendText(&s," WHERE type IN ('table','view')"
8834 " AND name NOT LIKE 'sqlite_%'"
8835 " AND name LIKE ?1", 0);
8836 }else{
8837 appendText(&s," WHERE type='index'"
8838 " AND tbl_name LIKE ?1", 0);
8839 }
8840 }
8841 rc = sqlite3_finalize(pStmt);
8842 appendText(&s, " ORDER BY 1", 0);
8843 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
8844 freeText(&s);
8845 if( rc ) return shellDatabaseError(p->db);
8846
8847 /* Run the SQL statement prepared by the above block. Store the results
8848 ** as an array of nul-terminated strings in azResult[]. */
8849 nRow = nAlloc = 0;
8850 azResult = 0;
8851 if( nArg>1 ){
8852 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
8853 }else{
8854 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
8855 }
8856 while( sqlite3_step(pStmt)==SQLITE_ROW ){
8857 if( nRow>=nAlloc ){
8858 char **azNew;
8859 int n2 = nAlloc*2 + 10;
8860 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh4b5345c2018-04-24 13:07:40 +00008861 if( azNew==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008862 nAlloc = n2;
8863 azResult = azNew;
8864 }
8865 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
drh4b5345c2018-04-24 13:07:40 +00008866 if( 0==azResult[nRow] ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00008867 nRow++;
8868 }
8869 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
8870 rc = shellDatabaseError(p->db);
8871 }
8872
8873 /* Pretty-print the contents of array azResult[] to the output */
8874 if( rc==0 && nRow>0 ){
8875 int len, maxlen = 0;
8876 int i, j;
8877 int nPrintCol, nPrintRow;
8878 for(i=0; i<nRow; i++){
8879 len = strlen30(azResult[i]);
8880 if( len>maxlen ) maxlen = len;
8881 }
8882 nPrintCol = 80/(maxlen+2);
8883 if( nPrintCol<1 ) nPrintCol = 1;
8884 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
8885 for(i=0; i<nPrintRow; i++){
8886 for(j=i; j<nRow; j+=nPrintRow){
8887 char *zSp = j<nPrintRow ? "" : " ";
8888 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
8889 azResult[j] ? azResult[j]:"");
8890 }
8891 raw_printf(p->out, "\n");
8892 }
8893 }
8894
8895 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
8896 sqlite3_free(azResult);
8897 }else
8898
8899 /* Begin redirecting output to the file "testcase-out.txt" */
8900 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
8901 output_reset(p);
drha92a01a2018-01-10 22:15:37 +00008902 p->out = output_file_open("testcase-out.txt", 0);
drh2ce15c32017-07-11 13:34:40 +00008903 if( p->out==0 ){
8904 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
8905 }
8906 if( nArg>=2 ){
8907 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
8908 }else{
8909 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
8910 }
8911 }else
8912
8913#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00008914 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00008915 static const struct {
8916 const char *zCtrlName; /* Name of a test-control option */
8917 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00008918 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00008919 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00008920 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
8921 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
8922 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
8923 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
8924 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
8925 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
8926 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
drheea8eb62018-11-26 18:09:15 +00008927 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" },
drhef302e82017-11-15 19:14:08 +00008928 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
8929 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
8930 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00008931#ifdef YYCOVERAGE
8932 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
8933#endif
drhef302e82017-11-15 19:14:08 +00008934 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
8935 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
8936 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
8937 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
8938 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00008939 };
8940 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00008941 int iCtrl = -1;
8942 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
8943 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00008944 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00008945 const char *zCmd = 0;
8946
drh2ce15c32017-07-11 13:34:40 +00008947 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00008948 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00008949
8950 /* The argument can optionally begin with "-" or "--" */
8951 if( zCmd[0]=='-' && zCmd[1] ){
8952 zCmd++;
8953 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
8954 }
8955
8956 /* --help lists all test-controls */
8957 if( strcmp(zCmd,"help")==0 ){
8958 utf8_printf(p->out, "Available test-controls:\n");
8959 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00008960 utf8_printf(p->out, " .testctrl %s %s\n",
8961 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00008962 }
8963 rc = 1;
8964 goto meta_command_exit;
8965 }
drh2ce15c32017-07-11 13:34:40 +00008966
8967 /* convert testctrl text option to value. allow any unique prefix
8968 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00008969 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00008970 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00008971 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00008972 if( testctrl<0 ){
8973 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00008974 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00008975 }else{
drh35f51a42017-11-15 17:07:22 +00008976 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
8977 "Use \".testctrl --help\" for help\n", zCmd);
8978 rc = 1;
8979 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00008980 }
8981 }
8982 }
drhef302e82017-11-15 19:14:08 +00008983 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00008984 utf8_printf(stderr,"Error: unknown test-control: %s\n"
8985 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00008986 }else{
8987 switch(testctrl){
8988
8989 /* sqlite3_test_control(int, db, int) */
8990 case SQLITE_TESTCTRL_OPTIMIZATIONS:
8991 case SQLITE_TESTCTRL_RESERVE:
8992 if( nArg==3 ){
8993 int opt = (int)strtol(azArg[2], 0, 0);
8994 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00008995 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00008996 }
8997 break;
8998
8999 /* sqlite3_test_control(int) */
9000 case SQLITE_TESTCTRL_PRNG_SAVE:
9001 case SQLITE_TESTCTRL_PRNG_RESTORE:
9002 case SQLITE_TESTCTRL_PRNG_RESET:
9003 case SQLITE_TESTCTRL_BYTEORDER:
9004 if( nArg==2 ){
9005 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00009006 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00009007 }
9008 break;
9009
9010 /* sqlite3_test_control(int, uint) */
9011 case SQLITE_TESTCTRL_PENDING_BYTE:
9012 if( nArg==3 ){
9013 unsigned int opt = (unsigned int)integerValue(azArg[2]);
9014 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00009015 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00009016 }
9017 break;
9018
9019 /* sqlite3_test_control(int, int) */
9020 case SQLITE_TESTCTRL_ASSERT:
9021 case SQLITE_TESTCTRL_ALWAYS:
drheea8eb62018-11-26 18:09:15 +00009022 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
drhef302e82017-11-15 19:14:08 +00009023 if( nArg==3 ){
9024 int opt = booleanValue(azArg[2]);
9025 rc2 = sqlite3_test_control(testctrl, opt);
9026 isOk = 1;
9027 }
9028 break;
9029
9030 /* sqlite3_test_control(int, int) */
9031 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00009032 case SQLITE_TESTCTRL_NEVER_CORRUPT:
9033 if( nArg==3 ){
9034 int opt = booleanValue(azArg[2]);
9035 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00009036 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00009037 }
9038 break;
9039
drh2ce15c32017-07-11 13:34:40 +00009040 case SQLITE_TESTCTRL_IMPOSTER:
9041 if( nArg==5 ){
9042 rc2 = sqlite3_test_control(testctrl, p->db,
9043 azArg[2],
9044 integerValue(azArg[3]),
9045 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00009046 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00009047 }
9048 break;
drh0d9de992017-12-26 18:04:23 +00009049
9050#ifdef YYCOVERAGE
9051 case SQLITE_TESTCTRL_PARSER_COVERAGE:
9052 if( nArg==2 ){
9053 sqlite3_test_control(testctrl, p->out);
9054 isOk = 3;
9055 }
9056#endif
drh2ce15c32017-07-11 13:34:40 +00009057 }
9058 }
drhef302e82017-11-15 19:14:08 +00009059 if( isOk==0 && iCtrl>=0 ){
9060 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
9061 rc = 1;
9062 }else if( isOk==1 ){
9063 raw_printf(p->out, "%d\n", rc2);
9064 }else if( isOk==2 ){
9065 raw_printf(p->out, "0x%08x\n", rc2);
9066 }
drh2ce15c32017-07-11 13:34:40 +00009067 }else
9068#endif /* !defined(SQLITE_UNTESTABLE) */
9069
9070 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
9071 open_db(p, 0);
9072 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
9073 }else
9074
9075 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
9076 if( nArg==2 ){
9077 enableTimer = booleanValue(azArg[1]);
9078 if( enableTimer && !HAS_TIMER ){
9079 raw_printf(stderr, "Error: timer not available on this system.\n");
9080 enableTimer = 0;
9081 }
9082 }else{
9083 raw_printf(stderr, "Usage: .timer on|off\n");
9084 rc = 1;
9085 }
9086 }else
9087
drh707821f2018-12-05 13:39:06 +00009088#ifndef SQLITE_OMIT_TRACE
drh2ce15c32017-07-11 13:34:40 +00009089 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh707821f2018-12-05 13:39:06 +00009090 int mType = 0;
9091 int jj;
drh2ce15c32017-07-11 13:34:40 +00009092 open_db(p, 0);
drh707821f2018-12-05 13:39:06 +00009093 for(jj=1; jj<nArg; jj++){
9094 const char *z = azArg[jj];
9095 if( z[0]=='-' ){
9096 if( optionMatch(z, "expanded") ){
9097 p->eTraceType = SHELL_TRACE_EXPANDED;
9098 }
9099#ifdef SQLITE_ENABLE_NORMALIZE
9100 else if( optionMatch(z, "normalized") ){
9101 p->eTraceType = SHELL_TRACE_NORMALIZED;
9102 }
9103#endif
9104 else if( optionMatch(z, "plain") ){
9105 p->eTraceType = SHELL_TRACE_PLAIN;
9106 }
9107 else if( optionMatch(z, "profile") ){
9108 mType |= SQLITE_TRACE_PROFILE;
9109 }
9110 else if( optionMatch(z, "row") ){
9111 mType |= SQLITE_TRACE_ROW;
9112 }
9113 else if( optionMatch(z, "stmt") ){
9114 mType |= SQLITE_TRACE_STMT;
9115 }
9116 else if( optionMatch(z, "close") ){
9117 mType |= SQLITE_TRACE_CLOSE;
9118 }
9119 else {
9120 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z);
9121 rc = 1;
9122 goto meta_command_exit;
9123 }
9124 }else{
9125 output_file_close(p->traceOut);
9126 p->traceOut = output_file_open(azArg[1], 0);
9127 }
drh2ce15c32017-07-11 13:34:40 +00009128 }
drh2ce15c32017-07-11 13:34:40 +00009129 if( p->traceOut==0 ){
9130 sqlite3_trace_v2(p->db, 0, 0, 0);
9131 }else{
drh707821f2018-12-05 13:39:06 +00009132 if( mType==0 ) mType = SQLITE_TRACE_STMT;
9133 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p);
drh2ce15c32017-07-11 13:34:40 +00009134 }
drh2ce15c32017-07-11 13:34:40 +00009135 }else
drh707821f2018-12-05 13:39:06 +00009136#endif /* !defined(SQLITE_OMIT_TRACE) */
drh2ce15c32017-07-11 13:34:40 +00009137
9138#if SQLITE_USER_AUTHENTICATION
9139 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
9140 if( nArg<2 ){
9141 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
9142 rc = 1;
9143 goto meta_command_exit;
9144 }
9145 open_db(p, 0);
9146 if( strcmp(azArg[1],"login")==0 ){
9147 if( nArg!=4 ){
9148 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
9149 rc = 1;
9150 goto meta_command_exit;
9151 }
drhaf2770f2018-01-05 14:55:43 +00009152 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00009153 if( rc ){
9154 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
9155 rc = 1;
9156 }
9157 }else if( strcmp(azArg[1],"add")==0 ){
9158 if( nArg!=5 ){
9159 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
9160 rc = 1;
9161 goto meta_command_exit;
9162 }
drhaf2770f2018-01-05 14:55:43 +00009163 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00009164 booleanValue(azArg[4]));
9165 if( rc ){
9166 raw_printf(stderr, "User-Add failed: %d\n", rc);
9167 rc = 1;
9168 }
9169 }else if( strcmp(azArg[1],"edit")==0 ){
9170 if( nArg!=5 ){
9171 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
9172 rc = 1;
9173 goto meta_command_exit;
9174 }
drhaf2770f2018-01-05 14:55:43 +00009175 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00009176 booleanValue(azArg[4]));
9177 if( rc ){
9178 raw_printf(stderr, "User-Edit failed: %d\n", rc);
9179 rc = 1;
9180 }
9181 }else if( strcmp(azArg[1],"delete")==0 ){
9182 if( nArg!=3 ){
9183 raw_printf(stderr, "Usage: .user delete USER\n");
9184 rc = 1;
9185 goto meta_command_exit;
9186 }
9187 rc = sqlite3_user_delete(p->db, azArg[2]);
9188 if( rc ){
9189 raw_printf(stderr, "User-Delete failed: %d\n", rc);
9190 rc = 1;
9191 }
9192 }else{
9193 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
9194 rc = 1;
9195 goto meta_command_exit;
9196 }
9197 }else
9198#endif /* SQLITE_USER_AUTHENTICATION */
9199
9200 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
9201 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
9202 sqlite3_libversion(), sqlite3_sourceid());
drh0ed2fd82018-01-16 20:05:27 +00009203#if SQLITE_HAVE_ZLIB
9204 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
9205#endif
9206#define CTIMEOPT_VAL_(opt) #opt
9207#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
9208#if defined(__clang__) && defined(__clang_major__)
9209 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
9210 CTIMEOPT_VAL(__clang_minor__) "."
9211 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
9212#elif defined(_MSC_VER)
9213 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
9214#elif defined(__GNUC__) && defined(__VERSION__)
9215 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
9216#endif
drh2ce15c32017-07-11 13:34:40 +00009217 }else
9218
9219 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
9220 const char *zDbName = nArg==2 ? azArg[1] : "main";
9221 sqlite3_vfs *pVfs = 0;
9222 if( p->db ){
9223 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
9224 if( pVfs ){
9225 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
9226 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
9227 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
9228 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9229 }
9230 }
9231 }else
9232
9233 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
9234 sqlite3_vfs *pVfs;
9235 sqlite3_vfs *pCurrent = 0;
9236 if( p->db ){
9237 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
9238 }
9239 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
9240 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
9241 pVfs==pCurrent ? " <--- CURRENT" : "");
9242 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
9243 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
9244 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
9245 if( pVfs->pNext ){
9246 raw_printf(p->out, "-----------------------------------\n");
9247 }
9248 }
9249 }else
9250
9251 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
9252 const char *zDbName = nArg==2 ? azArg[1] : "main";
9253 char *zVfsName = 0;
9254 if( p->db ){
9255 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
9256 if( zVfsName ){
9257 utf8_printf(p->out, "%s\n", zVfsName);
9258 sqlite3_free(zVfsName);
9259 }
9260 }
9261 }else
9262
9263#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
9264 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
9265 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
9266 }else
9267#endif
9268
9269 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
9270 int j;
9271 assert( nArg<=ArraySize(azArg) );
9272 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
9273 p->colWidth[j-1] = (int)integerValue(azArg[j]);
9274 }
9275 }else
9276
9277 {
9278 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
9279 " \"%s\". Enter \".help\" for help\n", azArg[0]);
9280 rc = 1;
9281 }
9282
9283meta_command_exit:
9284 if( p->outCount ){
9285 p->outCount--;
9286 if( p->outCount==0 ) output_reset(p);
9287 }
9288 return rc;
9289}
9290
9291/*
9292** Return TRUE if a semicolon occurs anywhere in the first N characters
9293** of string z[].
9294*/
9295static int line_contains_semicolon(const char *z, int N){
9296 int i;
9297 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
9298 return 0;
9299}
9300
9301/*
9302** Test to see if a line consists entirely of whitespace.
9303*/
9304static int _all_whitespace(const char *z){
9305 for(; *z; z++){
9306 if( IsSpace(z[0]) ) continue;
9307 if( *z=='/' && z[1]=='*' ){
9308 z += 2;
9309 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
9310 if( *z==0 ) return 0;
9311 z++;
9312 continue;
9313 }
9314 if( *z=='-' && z[1]=='-' ){
9315 z += 2;
9316 while( *z && *z!='\n' ){ z++; }
9317 if( *z==0 ) return 1;
9318 continue;
9319 }
9320 return 0;
9321 }
9322 return 1;
9323}
9324
9325/*
9326** Return TRUE if the line typed in is an SQL command terminator other
9327** than a semi-colon. The SQL Server style "go" command is understood
9328** as is the Oracle "/".
9329*/
9330static int line_is_command_terminator(const char *zLine){
9331 while( IsSpace(zLine[0]) ){ zLine++; };
9332 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
9333 return 1; /* Oracle */
9334 }
9335 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
9336 && _all_whitespace(&zLine[2]) ){
9337 return 1; /* SQL Server */
9338 }
9339 return 0;
9340}
9341
9342/*
drh56f17742018-01-24 01:58:49 +00009343** We need a default sqlite3_complete() implementation to use in case
9344** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
9345** any arbitrary text is a complete SQL statement. This is not very
9346** user-friendly, but it does seem to work.
9347*/
9348#ifdef SQLITE_OMIT_COMPLETE
danc86b23b2018-11-16 14:36:42 +00009349#define sqlite3_complete(x) 1
drh56f17742018-01-24 01:58:49 +00009350#endif
9351
9352/*
drh2ce15c32017-07-11 13:34:40 +00009353** Return true if zSql is a complete SQL statement. Return false if it
9354** ends in the middle of a string literal or C-style comment.
9355*/
9356static int line_is_complete(char *zSql, int nSql){
9357 int rc;
9358 if( zSql==0 ) return 1;
9359 zSql[nSql] = ';';
9360 zSql[nSql+1] = 0;
9361 rc = sqlite3_complete(zSql);
9362 zSql[nSql] = 0;
9363 return rc;
9364}
9365
9366/*
drhfc29a862018-05-11 19:11:18 +00009367** Run a single line of SQL. Return the number of errors.
drh2ce15c32017-07-11 13:34:40 +00009368*/
9369static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
9370 int rc;
9371 char *zErrMsg = 0;
9372
9373 open_db(p, 0);
9374 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drhfc4eeef2019-02-05 19:48:46 +00009375 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0;
drh2ce15c32017-07-11 13:34:40 +00009376 BEGIN_TIMER;
drha10b9992018-03-09 15:24:33 +00009377 rc = shell_exec(p, zSql, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +00009378 END_TIMER;
9379 if( rc || zErrMsg ){
9380 char zPrefix[100];
9381 if( in!=0 || !stdin_is_interactive ){
9382 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
9383 "Error: near line %d:", startline);
9384 }else{
9385 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
9386 }
9387 if( zErrMsg!=0 ){
9388 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
9389 sqlite3_free(zErrMsg);
9390 zErrMsg = 0;
9391 }else{
9392 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
9393 }
9394 return 1;
9395 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
9396 raw_printf(p->out, "changes: %3d total_changes: %d\n",
9397 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
9398 }
9399 return 0;
9400}
9401
9402
9403/*
9404** Read input from *in and process it. If *in==0 then input
9405** is interactive - the user is typing it it. Otherwise, input
9406** is coming from a file or device. A prompt is issued and history
9407** is saved only if input is interactive. An interrupt signal will
9408** cause this routine to exit immediately, unless input is interactive.
9409**
9410** Return the number of errors.
9411*/
drh60379d42018-12-13 18:30:01 +00009412static int process_input(ShellState *p){
drh2ce15c32017-07-11 13:34:40 +00009413 char *zLine = 0; /* A single input line */
9414 char *zSql = 0; /* Accumulated SQL text */
9415 int nLine; /* Length of current line */
9416 int nSql = 0; /* Bytes of zSql[] used */
9417 int nAlloc = 0; /* Allocated zSql[] space */
9418 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
9419 int rc; /* Error code */
9420 int errCnt = 0; /* Number of errors seen */
drh2ce15c32017-07-11 13:34:40 +00009421 int startline = 0; /* Line number for start of current input */
9422
drh2c8ee022018-12-13 18:59:30 +00009423 p->lineno = 0;
drh60379d42018-12-13 18:30:01 +00009424 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){
drh2ce15c32017-07-11 13:34:40 +00009425 fflush(p->out);
drh60379d42018-12-13 18:30:01 +00009426 zLine = one_input_line(p->in, zLine, nSql>0);
drh2ce15c32017-07-11 13:34:40 +00009427 if( zLine==0 ){
9428 /* End of input */
drh60379d42018-12-13 18:30:01 +00009429 if( p->in==0 && stdin_is_interactive ) printf("\n");
drh2ce15c32017-07-11 13:34:40 +00009430 break;
9431 }
9432 if( seenInterrupt ){
drh60379d42018-12-13 18:30:01 +00009433 if( p->in!=0 ) break;
drh2ce15c32017-07-11 13:34:40 +00009434 seenInterrupt = 0;
9435 }
drh2c8ee022018-12-13 18:59:30 +00009436 p->lineno++;
drh2ce15c32017-07-11 13:34:40 +00009437 if( nSql==0 && _all_whitespace(zLine) ){
9438 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
9439 continue;
9440 }
drh1615c372018-05-12 23:56:22 +00009441 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
drh2ce15c32017-07-11 13:34:40 +00009442 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh1615c372018-05-12 23:56:22 +00009443 if( zLine[0]=='.' ){
9444 rc = do_meta_command(zLine, p);
9445 if( rc==2 ){ /* exit requested */
9446 break;
9447 }else if( rc ){
9448 errCnt++;
9449 }
drh2ce15c32017-07-11 13:34:40 +00009450 }
9451 continue;
9452 }
9453 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
9454 memcpy(zLine,";",2);
9455 }
9456 nLine = strlen30(zLine);
9457 if( nSql+nLine+2>=nAlloc ){
9458 nAlloc = nSql+nLine+100;
9459 zSql = realloc(zSql, nAlloc);
drh4b5345c2018-04-24 13:07:40 +00009460 if( zSql==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009461 }
9462 nSqlPrior = nSql;
9463 if( nSql==0 ){
9464 int i;
9465 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
9466 assert( nAlloc>0 && zSql!=0 );
9467 memcpy(zSql, zLine+i, nLine+1-i);
drh2c8ee022018-12-13 18:59:30 +00009468 startline = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00009469 nSql = nLine-i;
9470 }else{
9471 zSql[nSql++] = '\n';
9472 memcpy(zSql+nSql, zLine, nLine+1);
9473 nSql += nLine;
9474 }
9475 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
9476 && sqlite3_complete(zSql) ){
drh60379d42018-12-13 18:30:01 +00009477 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00009478 nSql = 0;
9479 if( p->outCount ){
9480 output_reset(p);
9481 p->outCount = 0;
drh13c20932018-01-10 21:41:55 +00009482 }else{
9483 clearTempFile(p);
drh2ce15c32017-07-11 13:34:40 +00009484 }
9485 }else if( nSql && _all_whitespace(zSql) ){
9486 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
9487 nSql = 0;
9488 }
9489 }
9490 if( nSql && !_all_whitespace(zSql) ){
drh60379d42018-12-13 18:30:01 +00009491 errCnt += runOneSqlLine(p, zSql, p->in, startline);
drh2ce15c32017-07-11 13:34:40 +00009492 }
9493 free(zSql);
9494 free(zLine);
9495 return errCnt>0;
9496}
9497
9498/*
9499** Return a pathname which is the user's home directory. A
9500** 0 return indicates an error of some kind.
9501*/
9502static char *find_home_dir(int clearFlag){
9503 static char *home_dir = NULL;
9504 if( clearFlag ){
9505 free(home_dir);
9506 home_dir = 0;
9507 return 0;
9508 }
9509 if( home_dir ) return home_dir;
9510
9511#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
9512 && !defined(__RTP__) && !defined(_WRS_KERNEL)
9513 {
9514 struct passwd *pwent;
9515 uid_t uid = getuid();
9516 if( (pwent=getpwuid(uid)) != NULL) {
9517 home_dir = pwent->pw_dir;
9518 }
9519 }
9520#endif
9521
9522#if defined(_WIN32_WCE)
9523 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
9524 */
9525 home_dir = "/";
9526#else
9527
9528#if defined(_WIN32) || defined(WIN32)
9529 if (!home_dir) {
9530 home_dir = getenv("USERPROFILE");
9531 }
9532#endif
9533
9534 if (!home_dir) {
9535 home_dir = getenv("HOME");
9536 }
9537
9538#if defined(_WIN32) || defined(WIN32)
9539 if (!home_dir) {
9540 char *zDrive, *zPath;
9541 int n;
9542 zDrive = getenv("HOMEDRIVE");
9543 zPath = getenv("HOMEPATH");
9544 if( zDrive && zPath ){
9545 n = strlen30(zDrive) + strlen30(zPath) + 1;
9546 home_dir = malloc( n );
9547 if( home_dir==0 ) return 0;
9548 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
9549 return home_dir;
9550 }
9551 home_dir = "c:\\";
9552 }
9553#endif
9554
9555#endif /* !_WIN32_WCE */
9556
9557 if( home_dir ){
9558 int n = strlen30(home_dir) + 1;
9559 char *z = malloc( n );
9560 if( z ) memcpy(z, home_dir, n);
9561 home_dir = z;
9562 }
9563
9564 return home_dir;
9565}
9566
9567/*
9568** Read input from the file given by sqliterc_override. Or if that
9569** parameter is NULL, take input from ~/.sqliterc
9570**
9571** Returns the number of errors.
9572*/
9573static void process_sqliterc(
9574 ShellState *p, /* Configuration data */
9575 const char *sqliterc_override /* Name of config file. NULL to use default */
9576){
9577 char *home_dir = NULL;
9578 const char *sqliterc = sqliterc_override;
9579 char *zBuf = 0;
drh60379d42018-12-13 18:30:01 +00009580 FILE *inSaved = p->in;
drh2c8ee022018-12-13 18:59:30 +00009581 int savedLineno = p->lineno;
drh2ce15c32017-07-11 13:34:40 +00009582
9583 if (sqliterc == NULL) {
9584 home_dir = find_home_dir(0);
9585 if( home_dir==0 ){
9586 raw_printf(stderr, "-- warning: cannot find home directory;"
9587 " cannot read ~/.sqliterc\n");
9588 return;
9589 }
drh2ce15c32017-07-11 13:34:40 +00009590 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
9591 sqliterc = zBuf;
9592 }
drh60379d42018-12-13 18:30:01 +00009593 p->in = fopen(sqliterc,"rb");
9594 if( p->in ){
drh2ce15c32017-07-11 13:34:40 +00009595 if( stdin_is_interactive ){
9596 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
9597 }
drh60379d42018-12-13 18:30:01 +00009598 process_input(p);
9599 fclose(p->in);
drh2ce15c32017-07-11 13:34:40 +00009600 }
drh60379d42018-12-13 18:30:01 +00009601 p->in = inSaved;
drh2c8ee022018-12-13 18:59:30 +00009602 p->lineno = savedLineno;
drh2ce15c32017-07-11 13:34:40 +00009603 sqlite3_free(zBuf);
9604}
9605
9606/*
9607** Show available command line options
9608*/
9609static const char zOptions[] =
drhda57d962018-03-05 19:34:05 +00009610#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
drhad7fd5d2018-03-05 20:21:50 +00009611 " -A ARGS... run \".archive ARGS\" and exit\n"
drhda57d962018-03-05 19:34:05 +00009612#endif
drh3baed312018-03-08 18:14:41 +00009613 " -append append the database to the end of the file\n"
drh2ce15c32017-07-11 13:34:40 +00009614 " -ascii set output mode to 'ascii'\n"
9615 " -bail stop after hitting an error\n"
9616 " -batch force batch I/O\n"
9617 " -column set output mode to 'column'\n"
9618 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
9619 " -csv set output mode to 'csv'\n"
drh6ca64482019-01-22 16:06:20 +00009620#if defined(SQLITE_ENABLE_DESERIALIZE)
9621 " -deserialize open the database using sqlite3_deserialize()\n"
9622#endif
drh2ce15c32017-07-11 13:34:40 +00009623 " -echo print commands before execution\n"
9624 " -init FILENAME read/process named file\n"
9625 " -[no]header turn headers on or off\n"
9626#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
9627 " -heap SIZE Size of heap for memsys3 or memsys5\n"
9628#endif
9629 " -help show this message\n"
9630 " -html set output mode to HTML\n"
9631 " -interactive force interactive I/O\n"
9632 " -line set output mode to 'line'\n"
9633 " -list set output mode to 'list'\n"
9634 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh6ca64482019-01-22 16:06:20 +00009635#if defined(SQLITE_ENABLE_DESERIALIZE)
9636 " -maxsize N maximum size for a --deserialize database\n"
9637#endif
drhaf482572019-02-04 19:52:39 +00009638 " -memtrace trace all memory allocations and deallocations\n"
drh2ce15c32017-07-11 13:34:40 +00009639 " -mmap N default mmap size set to N\n"
9640#ifdef SQLITE_ENABLE_MULTIPLEX
9641 " -multiplex enable the multiplexor VFS\n"
9642#endif
9643 " -newline SEP set output row separator. Default: '\\n'\n"
9644 " -nullvalue TEXT set text string for NULL values. Default ''\n"
9645 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
9646 " -quote set output mode to 'quote'\n"
drhee269a62018-02-14 23:27:43 +00009647 " -readonly open the database read-only\n"
drh2ce15c32017-07-11 13:34:40 +00009648 " -separator SEP set output column separator. Default: '|'\n"
drha90d84f2018-04-18 15:21:13 +00009649#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9650 " -sorterref SIZE sorter references threshold size\n"
9651#endif
drh2ce15c32017-07-11 13:34:40 +00009652 " -stats print memory stats before each finalize\n"
9653 " -version show SQLite version\n"
9654 " -vfs NAME use NAME as the default VFS\n"
9655#ifdef SQLITE_ENABLE_VFSTRACE
9656 " -vfstrace enable tracing of all VFS calls\n"
9657#endif
drh3baed312018-03-08 18:14:41 +00009658#ifdef SQLITE_HAVE_ZLIB
9659 " -zip open the file as a ZIP Archive\n"
9660#endif
drh2ce15c32017-07-11 13:34:40 +00009661;
9662static void usage(int showDetail){
9663 utf8_printf(stderr,
9664 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
9665 "FILENAME is the name of an SQLite database. A new database is created\n"
9666 "if the file does not previously exist.\n", Argv0);
9667 if( showDetail ){
9668 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
9669 }else{
9670 raw_printf(stderr, "Use the -help option for additional information\n");
9671 }
9672 exit(1);
9673}
9674
9675/*
drhe7df8922018-04-18 10:44:58 +00009676** Internal check: Verify that the SQLite is uninitialized. Print a
9677** error message if it is initialized.
9678*/
9679static void verify_uninitialized(void){
9680 if( sqlite3_config(-1)==SQLITE_MISUSE ){
drh8e02a182018-05-30 07:24:41 +00009681 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
drhe7df8922018-04-18 10:44:58 +00009682 " initialization.\n");
9683 }
9684}
9685
9686/*
drh2ce15c32017-07-11 13:34:40 +00009687** Initialize the state information in data
9688*/
9689static void main_init(ShellState *data) {
9690 memset(data, 0, sizeof(*data));
9691 data->normalMode = data->cMode = data->mode = MODE_List;
9692 data->autoExplain = 1;
9693 memcpy(data->colSeparator,SEP_Column, 2);
9694 memcpy(data->rowSeparator,SEP_Row, 2);
9695 data->showHeader = 0;
9696 data->shellFlgs = SHFLG_Lookaside;
drhe7df8922018-04-18 10:44:58 +00009697 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00009698 sqlite3_config(SQLITE_CONFIG_URI, 1);
9699 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
9700 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
9701 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
9702 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
9703}
9704
9705/*
9706** Output text to the console in a font that attracts extra attention.
9707*/
9708#ifdef _WIN32
9709static void printBold(const char *zText){
9710 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
9711 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
9712 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
9713 SetConsoleTextAttribute(out,
9714 FOREGROUND_RED|FOREGROUND_INTENSITY
9715 );
9716 printf("%s", zText);
9717 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
9718}
9719#else
9720static void printBold(const char *zText){
9721 printf("\033[1m%s\033[0m", zText);
9722}
9723#endif
9724
9725/*
9726** Get the argument to an --option. Throw an error and die if no argument
9727** is available.
9728*/
9729static char *cmdline_option_value(int argc, char **argv, int i){
9730 if( i==argc ){
9731 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
9732 argv[0], argv[argc-1]);
9733 exit(1);
9734 }
9735 return argv[i];
9736}
9737
9738#ifndef SQLITE_SHELL_IS_UTF8
9739# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
9740# define SQLITE_SHELL_IS_UTF8 (0)
9741# else
9742# define SQLITE_SHELL_IS_UTF8 (1)
9743# endif
9744#endif
9745
9746#if SQLITE_SHELL_IS_UTF8
9747int SQLITE_CDECL main(int argc, char **argv){
9748#else
9749int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
9750 char **argv;
9751#endif
9752 char *zErrMsg = 0;
9753 ShellState data;
9754 const char *zInitFile = 0;
9755 int i;
9756 int rc = 0;
9757 int warnInmemoryDb = 0;
9758 int readStdin = 1;
9759 int nCmd = 0;
9760 char **azCmd = 0;
dan16a47422018-04-18 09:16:11 +00009761 const char *zVfs = 0; /* Value of -vfs command-line option */
drh1f22f622018-05-17 13:29:14 +00009762#if !SQLITE_SHELL_IS_UTF8
9763 char **argvToFree = 0;
9764 int argcToFree = 0;
9765#endif
drh2ce15c32017-07-11 13:34:40 +00009766
9767 setBinaryMode(stdin, 0);
9768 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
9769 stdin_is_interactive = isatty(0);
9770 stdout_is_console = isatty(1);
9771
mistachkin1e8487d2018-07-22 06:25:35 +00009772#if !defined(_WIN32_WCE)
9773 if( getenv("SQLITE_DEBUG_BREAK") ){
9774 if( isatty(0) && isatty(2) ){
9775 fprintf(stderr,
9776 "attach debugger to process %d and press any key to continue.\n",
9777 GETPID());
9778 fgetc(stdin);
9779 }else{
9780#if defined(_WIN32) || defined(WIN32)
9781 DebugBreak();
9782#elif defined(SIGTRAP)
9783 raise(SIGTRAP);
9784#endif
9785 }
9786 }
9787#endif
9788
drh2ce15c32017-07-11 13:34:40 +00009789#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00009790 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00009791 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
9792 sqlite3_sourceid(), SQLITE_SOURCE_ID);
9793 exit(1);
9794 }
9795#endif
9796 main_init(&data);
drh501ea052018-02-15 01:03:37 +00009797
9798 /* On Windows, we must translate command-line arguments into UTF-8.
9799 ** The SQLite memory allocator subsystem has to be enabled in order to
9800 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
9801 ** subsequent sqlite3_config() calls will work. So copy all results into
9802 ** memory that does not come from the SQLite memory allocator.
9803 */
drh4b18c1d2018-02-04 20:33:13 +00009804#if !SQLITE_SHELL_IS_UTF8
drh501ea052018-02-15 01:03:37 +00009805 sqlite3_initialize();
drh1f22f622018-05-17 13:29:14 +00009806 argvToFree = malloc(sizeof(argv[0])*argc*2);
9807 argcToFree = argc;
9808 argv = argvToFree + argc;
drh4b5345c2018-04-24 13:07:40 +00009809 if( argv==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009810 for(i=0; i<argc; i++){
drh501ea052018-02-15 01:03:37 +00009811 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
9812 int n;
drh4b5345c2018-04-24 13:07:40 +00009813 if( z==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00009814 n = (int)strlen(z);
9815 argv[i] = malloc( n+1 );
drh4b5345c2018-04-24 13:07:40 +00009816 if( argv[i]==0 ) shell_out_of_memory();
drh501ea052018-02-15 01:03:37 +00009817 memcpy(argv[i], z, n+1);
drh1f22f622018-05-17 13:29:14 +00009818 argvToFree[i] = argv[i];
drh501ea052018-02-15 01:03:37 +00009819 sqlite3_free(z);
drh2ce15c32017-07-11 13:34:40 +00009820 }
drh501ea052018-02-15 01:03:37 +00009821 sqlite3_shutdown();
drh2ce15c32017-07-11 13:34:40 +00009822#endif
drh501ea052018-02-15 01:03:37 +00009823
drh2ce15c32017-07-11 13:34:40 +00009824 assert( argc>=1 && argv && argv[0] );
9825 Argv0 = argv[0];
9826
9827 /* Make sure we have a valid signal handler early, before anything
9828 ** else is done.
9829 */
9830#ifdef SIGINT
9831 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00009832#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
9833 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00009834#endif
9835
9836#ifdef SQLITE_SHELL_DBNAME_PROC
9837 {
9838 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
9839 ** of a C-function that will provide the name of the database file. Use
9840 ** this compile-time option to embed this shell program in larger
9841 ** applications. */
9842 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
9843 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
9844 warnInmemoryDb = 0;
9845 }
9846#endif
9847
9848 /* Do an initial pass through the command-line argument to locate
9849 ** the name of the database file, the name of the initialization file,
9850 ** the size of the alternative malloc heap,
9851 ** and the first command to execute.
9852 */
drhe7df8922018-04-18 10:44:58 +00009853 verify_uninitialized();
drh2ce15c32017-07-11 13:34:40 +00009854 for(i=1; i<argc; i++){
9855 char *z;
9856 z = argv[i];
9857 if( z[0]!='-' ){
9858 if( data.zDbFilename==0 ){
9859 data.zDbFilename = z;
9860 }else{
9861 /* Excesss arguments are interpreted as SQL (or dot-commands) and
9862 ** mean that nothing is read from stdin */
9863 readStdin = 0;
9864 nCmd++;
9865 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
drh4b5345c2018-04-24 13:07:40 +00009866 if( azCmd==0 ) shell_out_of_memory();
drh2ce15c32017-07-11 13:34:40 +00009867 azCmd[nCmd-1] = z;
9868 }
9869 }
9870 if( z[1]=='-' ) z++;
9871 if( strcmp(z,"-separator")==0
9872 || strcmp(z,"-nullvalue")==0
9873 || strcmp(z,"-newline")==0
9874 || strcmp(z,"-cmd")==0
9875 ){
9876 (void)cmdline_option_value(argc, argv, ++i);
9877 }else if( strcmp(z,"-init")==0 ){
9878 zInitFile = cmdline_option_value(argc, argv, ++i);
9879 }else if( strcmp(z,"-batch")==0 ){
9880 /* Need to check for batch mode here to so we can avoid printing
9881 ** informational messages (like from process_sqliterc) before
9882 ** we do the actual processing of arguments later in a second pass.
9883 */
9884 stdin_is_interactive = 0;
9885 }else if( strcmp(z,"-heap")==0 ){
9886#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
9887 const char *zSize;
9888 sqlite3_int64 szHeap;
9889
9890 zSize = cmdline_option_value(argc, argv, ++i);
9891 szHeap = integerValue(zSize);
9892 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
9893 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
9894#else
9895 (void)cmdline_option_value(argc, argv, ++i);
9896#endif
drh2ce15c32017-07-11 13:34:40 +00009897 }else if( strcmp(z,"-pagecache")==0 ){
9898 int n, sz;
9899 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
9900 if( sz>70000 ) sz = 70000;
9901 if( sz<0 ) sz = 0;
9902 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
9903 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
9904 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
9905 data.shellFlgs |= SHFLG_Pagecache;
9906 }else if( strcmp(z,"-lookaside")==0 ){
9907 int n, sz;
9908 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
9909 if( sz<0 ) sz = 0;
9910 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
9911 if( n<0 ) n = 0;
9912 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
9913 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
9914#ifdef SQLITE_ENABLE_VFSTRACE
9915 }else if( strcmp(z,"-vfstrace")==0 ){
9916 extern int vfstrace_register(
9917 const char *zTraceName,
9918 const char *zOldVfsName,
9919 int (*xOut)(const char*,void*),
9920 void *pOutArg,
9921 int makeDefault
9922 );
9923 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
9924#endif
9925#ifdef SQLITE_ENABLE_MULTIPLEX
9926 }else if( strcmp(z,"-multiplex")==0 ){
9927 extern int sqlite3_multiple_initialize(const char*,int);
9928 sqlite3_multiplex_initialize(0, 1);
9929#endif
9930 }else if( strcmp(z,"-mmap")==0 ){
9931 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
9932 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drha90d84f2018-04-18 15:21:13 +00009933#ifdef SQLITE_ENABLE_SORTER_REFERENCES
9934 }else if( strcmp(z,"-sorterref")==0 ){
9935 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
9936 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
9937#endif
drh2ce15c32017-07-11 13:34:40 +00009938 }else if( strcmp(z,"-vfs")==0 ){
dan16a47422018-04-18 09:16:11 +00009939 zVfs = cmdline_option_value(argc, argv, ++i);
drh3baed312018-03-08 18:14:41 +00009940#ifdef SQLITE_HAVE_ZLIB
drh8682e122018-01-07 20:38:10 +00009941 }else if( strcmp(z,"-zip")==0 ){
9942 data.openMode = SHELL_OPEN_ZIPFILE;
9943#endif
9944 }else if( strcmp(z,"-append")==0 ){
9945 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +00009946#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +00009947 }else if( strcmp(z,"-deserialize")==0 ){
9948 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +00009949 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
9950 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +00009951#endif
drhee269a62018-02-14 23:27:43 +00009952 }else if( strcmp(z,"-readonly")==0 ){
9953 data.openMode = SHELL_OPEN_READONLY;
drhda57d962018-03-05 19:34:05 +00009954#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +00009955 }else if( strncmp(z, "-A",2)==0 ){
drhda57d962018-03-05 19:34:05 +00009956 /* All remaining command-line arguments are passed to the ".archive"
9957 ** command, so ignore them */
9958 break;
9959#endif
drh50b910a2019-01-21 14:55:03 +00009960 }else if( strcmp(z, "-memtrace")==0 ){
9961 sqlite3MemTraceActivate(stderr);
drh2ce15c32017-07-11 13:34:40 +00009962 }
9963 }
drhe7df8922018-04-18 10:44:58 +00009964 verify_uninitialized();
9965
dan16a47422018-04-18 09:16:11 +00009966
drhd11b8f62018-04-25 13:27:07 +00009967#ifdef SQLITE_SHELL_INIT_PROC
9968 {
9969 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
9970 ** of a C-function that will perform initialization actions on SQLite that
9971 ** occur just before or after sqlite3_initialize(). Use this compile-time
9972 ** option to embed this shell program in larger applications. */
9973 extern void SQLITE_SHELL_INIT_PROC(void);
9974 SQLITE_SHELL_INIT_PROC();
9975 }
9976#else
dan16a47422018-04-18 09:16:11 +00009977 /* All the sqlite3_config() calls have now been made. So it is safe
9978 ** to call sqlite3_initialize() and process any command line -vfs option. */
9979 sqlite3_initialize();
drhd11b8f62018-04-25 13:27:07 +00009980#endif
9981
dan16a47422018-04-18 09:16:11 +00009982 if( zVfs ){
9983 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
9984 if( pVfs ){
9985 sqlite3_vfs_register(pVfs, 1);
9986 }else{
9987 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
9988 exit(1);
9989 }
9990 }
9991
drh2ce15c32017-07-11 13:34:40 +00009992 if( data.zDbFilename==0 ){
9993#ifndef SQLITE_OMIT_MEMORYDB
9994 data.zDbFilename = ":memory:";
9995 warnInmemoryDb = argc==1;
9996#else
9997 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
9998 return 1;
9999#endif
10000 }
10001 data.out = stdout;
drh8682e122018-01-07 20:38:10 +000010002 sqlite3_appendvfs_init(0,0,0);
drh2ce15c32017-07-11 13:34:40 +000010003
10004 /* Go ahead and open the database file if it already exists. If the
10005 ** file does not exist, delay opening it. This prevents empty database
10006 ** files from being created if a user mistypes the database name argument
10007 ** to the sqlite command-line tool.
10008 */
10009 if( access(data.zDbFilename, 0)==0 ){
10010 open_db(&data, 0);
10011 }
10012
10013 /* Process the initialization file if there is one. If no -init option
10014 ** is given on the command line, look for a file named ~/.sqliterc and
10015 ** try to process it.
10016 */
10017 process_sqliterc(&data,zInitFile);
10018
10019 /* Make a second pass through the command-line argument and set
10020 ** options. This second pass is delayed until after the initialization
10021 ** file is processed so that the command-line arguments will override
10022 ** settings in the initialization file.
10023 */
10024 for(i=1; i<argc; i++){
10025 char *z = argv[i];
10026 if( z[0]!='-' ) continue;
10027 if( z[1]=='-' ){ z++; }
10028 if( strcmp(z,"-init")==0 ){
10029 i++;
10030 }else if( strcmp(z,"-html")==0 ){
10031 data.mode = MODE_Html;
10032 }else if( strcmp(z,"-list")==0 ){
10033 data.mode = MODE_List;
10034 }else if( strcmp(z,"-quote")==0 ){
10035 data.mode = MODE_Quote;
10036 }else if( strcmp(z,"-line")==0 ){
10037 data.mode = MODE_Line;
10038 }else if( strcmp(z,"-column")==0 ){
10039 data.mode = MODE_Column;
10040 }else if( strcmp(z,"-csv")==0 ){
10041 data.mode = MODE_Csv;
10042 memcpy(data.colSeparator,",",2);
drh3baed312018-03-08 18:14:41 +000010043#ifdef SQLITE_HAVE_ZLIB
drh1fa6d9f2018-01-06 21:46:01 +000010044 }else if( strcmp(z,"-zip")==0 ){
10045 data.openMode = SHELL_OPEN_ZIPFILE;
10046#endif
10047 }else if( strcmp(z,"-append")==0 ){
10048 data.openMode = SHELL_OPEN_APPENDVFS;
drha751f392018-10-30 15:31:22 +000010049#ifdef SQLITE_ENABLE_DESERIALIZE
drh60f34ae2018-10-30 13:19:49 +000010050 }else if( strcmp(z,"-deserialize")==0 ){
10051 data.openMode = SHELL_OPEN_DESERIALIZE;
drh6ca64482019-01-22 16:06:20 +000010052 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){
10053 data.szMax = integerValue(argv[++i]);
drha751f392018-10-30 15:31:22 +000010054#endif
drh4aafe592018-03-23 16:08:30 +000010055 }else if( strcmp(z,"-readonly")==0 ){
10056 data.openMode = SHELL_OPEN_READONLY;
drh2ce15c32017-07-11 13:34:40 +000010057 }else if( strcmp(z,"-ascii")==0 ){
10058 data.mode = MODE_Ascii;
10059 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
10060 SEP_Unit);
10061 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
10062 SEP_Record);
10063 }else if( strcmp(z,"-separator")==0 ){
10064 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
10065 "%s",cmdline_option_value(argc,argv,++i));
10066 }else if( strcmp(z,"-newline")==0 ){
10067 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
10068 "%s",cmdline_option_value(argc,argv,++i));
10069 }else if( strcmp(z,"-nullvalue")==0 ){
10070 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
10071 "%s",cmdline_option_value(argc,argv,++i));
10072 }else if( strcmp(z,"-header")==0 ){
10073 data.showHeader = 1;
10074 }else if( strcmp(z,"-noheader")==0 ){
10075 data.showHeader = 0;
10076 }else if( strcmp(z,"-echo")==0 ){
10077 ShellSetFlag(&data, SHFLG_Echo);
10078 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +000010079 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +000010080 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +000010081 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +000010082 }else if( strcmp(z,"-stats")==0 ){
10083 data.statsOn = 1;
10084 }else if( strcmp(z,"-scanstats")==0 ){
10085 data.scanstatsOn = 1;
10086 }else if( strcmp(z,"-backslash")==0 ){
10087 /* Undocumented command-line option: -backslash
10088 ** Causes C-style backslash escapes to be evaluated in SQL statements
10089 ** prior to sending the SQL into SQLite. Useful for injecting
10090 ** crazy bytes in the middle of SQL statements for testing and debugging.
10091 */
10092 ShellSetFlag(&data, SHFLG_Backslash);
10093 }else if( strcmp(z,"-bail")==0 ){
10094 bail_on_error = 1;
10095 }else if( strcmp(z,"-version")==0 ){
10096 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
10097 return 0;
10098 }else if( strcmp(z,"-interactive")==0 ){
10099 stdin_is_interactive = 1;
10100 }else if( strcmp(z,"-batch")==0 ){
10101 stdin_is_interactive = 0;
10102 }else if( strcmp(z,"-heap")==0 ){
10103 i++;
drh2ce15c32017-07-11 13:34:40 +000010104 }else if( strcmp(z,"-pagecache")==0 ){
10105 i+=2;
10106 }else if( strcmp(z,"-lookaside")==0 ){
10107 i+=2;
10108 }else if( strcmp(z,"-mmap")==0 ){
10109 i++;
drh50b910a2019-01-21 14:55:03 +000010110 }else if( strcmp(z,"-memtrace")==0 ){
10111 i++;
drha90d84f2018-04-18 15:21:13 +000010112#ifdef SQLITE_ENABLE_SORTER_REFERENCES
10113 }else if( strcmp(z,"-sorterref")==0 ){
10114 i++;
10115#endif
drh2ce15c32017-07-11 13:34:40 +000010116 }else if( strcmp(z,"-vfs")==0 ){
10117 i++;
10118#ifdef SQLITE_ENABLE_VFSTRACE
10119 }else if( strcmp(z,"-vfstrace")==0 ){
10120 i++;
10121#endif
10122#ifdef SQLITE_ENABLE_MULTIPLEX
10123 }else if( strcmp(z,"-multiplex")==0 ){
10124 i++;
10125#endif
10126 }else if( strcmp(z,"-help")==0 ){
10127 usage(1);
10128 }else if( strcmp(z,"-cmd")==0 ){
10129 /* Run commands that follow -cmd first and separately from commands
10130 ** that simply appear on the command-line. This seems goofy. It would
10131 ** be better if all commands ran in the order that they appear. But
10132 ** we retain the goofy behavior for historical compatibility. */
10133 if( i==argc-1 ) break;
10134 z = cmdline_option_value(argc,argv,++i);
10135 if( z[0]=='.' ){
10136 rc = do_meta_command(z, &data);
10137 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
10138 }else{
10139 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +000010140 rc = shell_exec(&data, z, &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +000010141 if( zErrMsg!=0 ){
10142 utf8_printf(stderr,"Error: %s\n", zErrMsg);
10143 if( bail_on_error ) return rc!=0 ? rc : 1;
10144 }else if( rc!=0 ){
10145 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
10146 if( bail_on_error ) return rc;
10147 }
10148 }
drhda57d962018-03-05 19:34:05 +000010149#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
drh93b77312018-03-05 20:20:22 +000010150 }else if( strncmp(z, "-A", 2)==0 ){
drhda57d962018-03-05 19:34:05 +000010151 if( nCmd>0 ){
10152 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
10153 " with \"%s\"\n", z);
10154 return 1;
10155 }
drhbe4ccb22018-05-17 20:04:24 +000010156 open_db(&data, OPEN_DB_ZIPFILE);
drh93b77312018-03-05 20:20:22 +000010157 if( z[2] ){
10158 argv[i] = &z[2];
drhd0f9cdc2018-05-17 14:09:06 +000010159 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
drh93b77312018-03-05 20:20:22 +000010160 }else{
drhd0f9cdc2018-05-17 14:09:06 +000010161 arDotCommand(&data, 1, argv+i, argc-i);
drh93b77312018-03-05 20:20:22 +000010162 }
drhda57d962018-03-05 19:34:05 +000010163 readStdin = 0;
10164 break;
10165#endif
drh2ce15c32017-07-11 13:34:40 +000010166 }else{
10167 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
10168 raw_printf(stderr,"Use -help for a list of options.\n");
10169 return 1;
10170 }
10171 data.cMode = data.mode;
10172 }
10173
10174 if( !readStdin ){
10175 /* Run all arguments that do not begin with '-' as if they were separate
10176 ** command-line inputs, except for the argToSkip argument which contains
10177 ** the database filename.
10178 */
10179 for(i=0; i<nCmd; i++){
10180 if( azCmd[i][0]=='.' ){
10181 rc = do_meta_command(azCmd[i], &data);
10182 if( rc ) return rc==2 ? 0 : rc;
10183 }else{
10184 open_db(&data, 0);
drha10b9992018-03-09 15:24:33 +000010185 rc = shell_exec(&data, azCmd[i], &zErrMsg);
drh2ce15c32017-07-11 13:34:40 +000010186 if( zErrMsg!=0 ){
10187 utf8_printf(stderr,"Error: %s\n", zErrMsg);
10188 return rc!=0 ? rc : 1;
10189 }else if( rc!=0 ){
10190 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
10191 return rc;
10192 }
10193 }
10194 }
10195 free(azCmd);
10196 }else{
10197 /* Run commands received from standard input
10198 */
10199 if( stdin_is_interactive ){
10200 char *zHome;
drha9e4be32018-10-10 18:56:40 +000010201 char *zHistory;
drh2ce15c32017-07-11 13:34:40 +000010202 int nHistory;
10203 printf(
10204 "SQLite version %s %.19s\n" /*extra-version-info*/
10205 "Enter \".help\" for usage hints.\n",
10206 sqlite3_libversion(), sqlite3_sourceid()
10207 );
10208 if( warnInmemoryDb ){
10209 printf("Connected to a ");
10210 printBold("transient in-memory database");
10211 printf(".\nUse \".open FILENAME\" to reopen on a "
10212 "persistent database.\n");
10213 }
drha9e4be32018-10-10 18:56:40 +000010214 zHistory = getenv("SQLITE_HISTORY");
10215 if( zHistory ){
10216 zHistory = strdup(zHistory);
10217 }else if( (zHome = find_home_dir(0))!=0 ){
drh2ce15c32017-07-11 13:34:40 +000010218 nHistory = strlen30(zHome) + 20;
10219 if( (zHistory = malloc(nHistory))!=0 ){
10220 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
10221 }
10222 }
10223 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +000010224#if HAVE_READLINE || HAVE_EDITLINE
10225 rl_attempted_completion_function = readline_completion;
10226#elif HAVE_LINENOISE
10227 linenoiseSetCompletionCallback(linenoise_completion);
10228#endif
drh60379d42018-12-13 18:30:01 +000010229 data.in = 0;
10230 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +000010231 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +000010232 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +000010233 shell_write_history(zHistory);
10234 free(zHistory);
10235 }
10236 }else{
drh60379d42018-12-13 18:30:01 +000010237 data.in = stdin;
10238 rc = process_input(&data);
drh2ce15c32017-07-11 13:34:40 +000010239 }
10240 }
10241 set_table_name(&data, 0);
10242 if( data.db ){
10243 session_close_all(&data);
drh9e804032018-05-18 17:11:50 +000010244 close_db(data.db);
drh2ce15c32017-07-11 13:34:40 +000010245 }
10246 sqlite3_free(data.zFreeOnClose);
10247 find_home_dir(1);
drh536c3452018-01-11 00:38:39 +000010248 output_reset(&data);
10249 data.doXdgOpen = 0;
drh13c20932018-01-10 21:41:55 +000010250 clearTempFile(&data);
drh2ce15c32017-07-11 13:34:40 +000010251#if !SQLITE_SHELL_IS_UTF8
drh1f22f622018-05-17 13:29:14 +000010252 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
10253 free(argvToFree);
drh2ce15c32017-07-11 13:34:40 +000010254#endif
drh9e804032018-05-18 17:11:50 +000010255 /* Clear the global data structure so that valgrind will detect memory
10256 ** leaks */
10257 memset(&data, 0, sizeof(data));
drh2ce15c32017-07-11 13:34:40 +000010258 return rc;
10259}