blob: c113bdb934a52c0b7dfa99152d97dc966fe456da [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;
drh2ce15c32017-07-11 13:34:40 +000066#if SQLITE_USER_AUTHENTICATION
67# include "sqlite3userauth.h"
68#endif
69#include <ctype.h>
70#include <stdarg.h>
71
72#if !defined(_WIN32) && !defined(WIN32)
73# include <signal.h>
74# if !defined(__RTP__) && !defined(_WRS_KERNEL)
75# include <pwd.h>
76# endif
mistachkinacae8c32018-01-05 20:08:46 +000077#endif
78#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW_H)
drh2ce15c32017-07-11 13:34:40 +000079# include <unistd.h>
mistachkinacae8c32018-01-05 20:08:46 +000080# include <dirent.h>
81# if defined(__MINGW_H)
82# define DIRENT dirent
mistachkin2f74b3c2018-01-05 20:26:06 +000083# ifndef S_ISLNK
84# define S_ISLNK(mode) (0)
85# endif
mistachkinacae8c32018-01-05 20:08:46 +000086# endif
drh2ce15c32017-07-11 13:34:40 +000087#endif
mistachkindfdfd8c2018-01-04 22:46:08 +000088#include <sys/types.h>
89#include <sys/stat.h>
drh2ce15c32017-07-11 13:34:40 +000090
91#if HAVE_READLINE
92# include <readline/readline.h>
93# include <readline/history.h>
94#endif
95
96#if HAVE_EDITLINE
97# include <editline/readline.h>
98#endif
99
100#if HAVE_EDITLINE || HAVE_READLINE
101
102# define shell_add_history(X) add_history(X)
103# define shell_read_history(X) read_history(X)
104# define shell_write_history(X) write_history(X)
105# define shell_stifle_history(X) stifle_history(X)
106# define shell_readline(X) readline(X)
107
108#elif HAVE_LINENOISE
109
110# include "linenoise.h"
111# define shell_add_history(X) linenoiseHistoryAdd(X)
112# define shell_read_history(X) linenoiseHistoryLoad(X)
113# define shell_write_history(X) linenoiseHistorySave(X)
114# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
115# define shell_readline(X) linenoise(X)
116
117#else
118
119# define shell_read_history(X)
120# define shell_write_history(X)
121# define shell_stifle_history(X)
122
123# define SHELL_USE_LOCAL_GETLINE 1
124#endif
125
126
127#if defined(_WIN32) || defined(WIN32)
128# include <io.h>
129# include <fcntl.h>
130# define isatty(h) _isatty(h)
131# ifndef access
132# define access(f,m) _access((f),(m))
133# endif
134# undef popen
135# define popen _popen
136# undef pclose
137# define pclose _pclose
138#else
139 /* Make sure isatty() has a prototype. */
140 extern int isatty(int);
141
142# if !defined(__RTP__) && !defined(_WRS_KERNEL)
143 /* popen and pclose are not C89 functions and so are
144 ** sometimes omitted from the <stdio.h> header */
145 extern FILE *popen(const char*,const char*);
146 extern int pclose(FILE*);
147# else
148# define SQLITE_OMIT_POPEN 1
149# endif
150#endif
151
152#if defined(_WIN32_WCE)
153/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
154 * thus we always assume that we have a console. That can be
155 * overridden with the -batch command line option.
156 */
157#define isatty(x) 1
158#endif
159
160/* ctype macros that work with signed characters */
161#define IsSpace(X) isspace((unsigned char)X)
162#define IsDigit(X) isdigit((unsigned char)X)
163#define ToLower(X) (char)tolower((unsigned char)X)
164
165#if defined(_WIN32) || defined(WIN32)
166#include <windows.h>
167
168/* string conversion routines only needed on Win32 */
169extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
170extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
171extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
172extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
173#endif
174
175/* On Windows, we normally run with output mode of TEXT so that \n characters
176** are automatically translated into \r\n. However, this behavior needs
177** to be disabled in some cases (ex: when generating CSV output and when
178** rendering quoted strings that contain \n characters). The following
179** routines take care of that.
180*/
181#if defined(_WIN32) || defined(WIN32)
182static void setBinaryMode(FILE *file, int isOutput){
183 if( isOutput ) fflush(file);
184 _setmode(_fileno(file), _O_BINARY);
185}
186static void setTextMode(FILE *file, int isOutput){
187 if( isOutput ) fflush(file);
188 _setmode(_fileno(file), _O_TEXT);
189}
190#else
191# define setBinaryMode(X,Y)
192# define setTextMode(X,Y)
193#endif
194
195
196/* True if the timer is enabled */
197static int enableTimer = 0;
198
199/* Return the current wall-clock time */
200static sqlite3_int64 timeOfDay(void){
201 static sqlite3_vfs *clockVfs = 0;
202 sqlite3_int64 t;
203 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
204 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
205 clockVfs->xCurrentTimeInt64(clockVfs, &t);
206 }else{
207 double r;
208 clockVfs->xCurrentTime(clockVfs, &r);
209 t = (sqlite3_int64)(r*86400000.0);
210 }
211 return t;
212}
213
214#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
215#include <sys/time.h>
216#include <sys/resource.h>
217
218/* VxWorks does not support getrusage() as far as we can determine */
219#if defined(_WRS_KERNEL) || defined(__RTP__)
220struct rusage {
221 struct timeval ru_utime; /* user CPU time used */
222 struct timeval ru_stime; /* system CPU time used */
223};
224#define getrusage(A,B) memset(B,0,sizeof(*B))
225#endif
226
227/* Saved resource information for the beginning of an operation */
228static struct rusage sBegin; /* CPU time at start */
229static sqlite3_int64 iBegin; /* Wall-clock time at start */
230
231/*
232** Begin timing an operation
233*/
234static void beginTimer(void){
235 if( enableTimer ){
236 getrusage(RUSAGE_SELF, &sBegin);
237 iBegin = timeOfDay();
238 }
239}
240
241/* Return the difference of two time_structs in seconds */
242static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
243 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
244 (double)(pEnd->tv_sec - pStart->tv_sec);
245}
246
247/*
248** Print the timing results.
249*/
250static void endTimer(void){
251 if( enableTimer ){
252 sqlite3_int64 iEnd = timeOfDay();
253 struct rusage sEnd;
254 getrusage(RUSAGE_SELF, &sEnd);
255 printf("Run Time: real %.3f user %f sys %f\n",
256 (iEnd - iBegin)*0.001,
257 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
258 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
259 }
260}
261
262#define BEGIN_TIMER beginTimer()
263#define END_TIMER endTimer()
264#define HAS_TIMER 1
265
266#elif (defined(_WIN32) || defined(WIN32))
267
268/* Saved resource information for the beginning of an operation */
269static HANDLE hProcess;
270static FILETIME ftKernelBegin;
271static FILETIME ftUserBegin;
272static sqlite3_int64 ftWallBegin;
273typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
274 LPFILETIME, LPFILETIME);
275static GETPROCTIMES getProcessTimesAddr = NULL;
276
277/*
278** Check to see if we have timer support. Return 1 if necessary
279** support found (or found previously).
280*/
281static int hasTimer(void){
282 if( getProcessTimesAddr ){
283 return 1;
284 } else {
285 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
286 ** versions. See if the version we are running on has it, and if it
287 ** does, save off a pointer to it and the current process handle.
288 */
289 hProcess = GetCurrentProcess();
290 if( hProcess ){
291 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
292 if( NULL != hinstLib ){
293 getProcessTimesAddr =
294 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
295 if( NULL != getProcessTimesAddr ){
296 return 1;
297 }
298 FreeLibrary(hinstLib);
299 }
300 }
301 }
302 return 0;
303}
304
305/*
306** Begin timing an operation
307*/
308static void beginTimer(void){
309 if( enableTimer && getProcessTimesAddr ){
310 FILETIME ftCreation, ftExit;
311 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
312 &ftKernelBegin,&ftUserBegin);
313 ftWallBegin = timeOfDay();
314 }
315}
316
317/* Return the difference of two FILETIME structs in seconds */
318static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
319 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
320 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
321 return (double) ((i64End - i64Start) / 10000000.0);
322}
323
324/*
325** Print the timing results.
326*/
327static void endTimer(void){
328 if( enableTimer && getProcessTimesAddr){
329 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
330 sqlite3_int64 ftWallEnd = timeOfDay();
331 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
332 printf("Run Time: real %.3f user %f sys %f\n",
333 (ftWallEnd - ftWallBegin)*0.001,
334 timeDiff(&ftUserBegin, &ftUserEnd),
335 timeDiff(&ftKernelBegin, &ftKernelEnd));
336 }
337}
338
339#define BEGIN_TIMER beginTimer()
340#define END_TIMER endTimer()
341#define HAS_TIMER hasTimer()
342
343#else
344#define BEGIN_TIMER
345#define END_TIMER
346#define HAS_TIMER 0
347#endif
348
349/*
350** Used to prevent warnings about unused parameters
351*/
352#define UNUSED_PARAMETER(x) (void)(x)
353
354/*
355** If the following flag is set, then command execution stops
356** at an error if we are not interactive.
357*/
358static int bail_on_error = 0;
359
360/*
361** Threat stdin as an interactive input if the following variable
362** is true. Otherwise, assume stdin is connected to a file or pipe.
363*/
364static int stdin_is_interactive = 1;
365
366/*
367** On Windows systems we have to know if standard output is a console
368** in order to translate UTF-8 into MBCS. The following variable is
369** true if translation is required.
370*/
371static int stdout_is_console = 1;
372
373/*
374** The following is the open SQLite database. We make a pointer
375** to this database a static variable so that it can be accessed
376** by the SIGINT handler to interrupt database processing.
377*/
378static sqlite3 *globalDb = 0;
379
380/*
381** True if an interrupt (Control-C) has been received.
382*/
383static volatile int seenInterrupt = 0;
384
385/*
386** This is the name of our program. It is set in main(), used
387** in a number of other places, mostly for error messages.
388*/
389static char *Argv0;
390
391/*
392** Prompt strings. Initialized in main. Settable with
393** .prompt main continue
394*/
395static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
396static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
397
398/*
399** Render output like fprintf(). Except, if the output is going to the
400** console and if this is running on a Windows machine, translate the
401** output from UTF-8 into MBCS.
402*/
403#if defined(_WIN32) || defined(WIN32)
404void utf8_printf(FILE *out, const char *zFormat, ...){
405 va_list ap;
406 va_start(ap, zFormat);
407 if( stdout_is_console && (out==stdout || out==stderr) ){
408 char *z1 = sqlite3_vmprintf(zFormat, ap);
409 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
410 sqlite3_free(z1);
411 fputs(z2, out);
412 sqlite3_free(z2);
413 }else{
414 vfprintf(out, zFormat, ap);
415 }
416 va_end(ap);
417}
418#elif !defined(utf8_printf)
419# define utf8_printf fprintf
420#endif
421
422/*
423** Render output like fprintf(). This should not be used on anything that
424** includes string formatting (e.g. "%s").
425*/
426#if !defined(raw_printf)
427# define raw_printf fprintf
428#endif
429
430/*
431** Write I/O traces to the following stream.
432*/
433#ifdef SQLITE_ENABLE_IOTRACE
434static FILE *iotrace = 0;
435#endif
436
437/*
438** This routine works like printf in that its first argument is a
439** format string and subsequent arguments are values to be substituted
440** in place of % fields. The result of formatting this string
441** is written to iotrace.
442*/
443#ifdef SQLITE_ENABLE_IOTRACE
444static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
445 va_list ap;
446 char *z;
447 if( iotrace==0 ) return;
448 va_start(ap, zFormat);
449 z = sqlite3_vmprintf(zFormat, ap);
450 va_end(ap);
451 utf8_printf(iotrace, "%s", z);
452 sqlite3_free(z);
453}
454#endif
455
456/*
457** Output string zUtf to stream pOut as w characters. If w is negative,
458** then right-justify the text. W is the width in UTF-8 characters, not
459** in bytes. This is different from the %*.*s specification in printf
460** since with %*.*s the width is measured in bytes, not characters.
461*/
462static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
463 int i;
464 int n;
465 int aw = w<0 ? -w : w;
466 char zBuf[1000];
467 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
468 for(i=n=0; zUtf[i]; i++){
469 if( (zUtf[i]&0xc0)!=0x80 ){
470 n++;
471 if( n==aw ){
472 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
473 break;
474 }
475 }
476 }
477 if( n>=aw ){
478 utf8_printf(pOut, "%.*s", i, zUtf);
479 }else if( w<0 ){
480 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
481 }else{
482 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
483 }
484}
485
486
487/*
488** Determines if a string is a number of not.
489*/
490static int isNumber(const char *z, int *realnum){
491 if( *z=='-' || *z=='+' ) z++;
492 if( !IsDigit(*z) ){
493 return 0;
494 }
495 z++;
496 if( realnum ) *realnum = 0;
497 while( IsDigit(*z) ){ z++; }
498 if( *z=='.' ){
499 z++;
500 if( !IsDigit(*z) ) return 0;
501 while( IsDigit(*z) ){ z++; }
502 if( realnum ) *realnum = 1;
503 }
504 if( *z=='e' || *z=='E' ){
505 z++;
506 if( *z=='+' || *z=='-' ) z++;
507 if( !IsDigit(*z) ) return 0;
508 while( IsDigit(*z) ){ z++; }
509 if( realnum ) *realnum = 1;
510 }
511 return *z==0;
512}
513
514/*
515** Compute a string length that is limited to what can be stored in
516** lower 30 bits of a 32-bit signed integer.
517*/
518static int strlen30(const char *z){
519 const char *z2 = z;
520 while( *z2 ){ z2++; }
521 return 0x3fffffff & (int)(z2 - z);
522}
523
524/*
525** Return the length of a string in characters. Multibyte UTF8 characters
526** count as a single character.
527*/
528static int strlenChar(const char *z){
529 int n = 0;
530 while( *z ){
531 if( (0xc0&*(z++))!=0x80 ) n++;
532 }
533 return n;
534}
535
536/*
537** This routine reads a line of text from FILE in, stores
538** the text in memory obtained from malloc() and returns a pointer
539** to the text. NULL is returned at end of file, or if malloc()
540** fails.
541**
542** If zLine is not NULL then it is a malloced buffer returned from
543** a previous call to this routine that may be reused.
544*/
545static char *local_getline(char *zLine, FILE *in){
546 int nLine = zLine==0 ? 0 : 100;
547 int n = 0;
548
549 while( 1 ){
550 if( n+100>nLine ){
551 nLine = nLine*2 + 100;
552 zLine = realloc(zLine, nLine);
553 if( zLine==0 ) return 0;
554 }
555 if( fgets(&zLine[n], nLine - n, in)==0 ){
556 if( n==0 ){
557 free(zLine);
558 return 0;
559 }
560 zLine[n] = 0;
561 break;
562 }
563 while( zLine[n] ) n++;
564 if( n>0 && zLine[n-1]=='\n' ){
565 n--;
566 if( n>0 && zLine[n-1]=='\r' ) n--;
567 zLine[n] = 0;
568 break;
569 }
570 }
571#if defined(_WIN32) || defined(WIN32)
572 /* For interactive input on Windows systems, translate the
573 ** multi-byte characterset characters into UTF-8. */
574 if( stdin_is_interactive && in==stdin ){
575 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
576 if( zTrans ){
577 int nTrans = strlen30(zTrans)+1;
578 if( nTrans>nLine ){
579 zLine = realloc(zLine, nTrans);
580 if( zLine==0 ){
581 sqlite3_free(zTrans);
582 return 0;
583 }
584 }
585 memcpy(zLine, zTrans, nTrans);
586 sqlite3_free(zTrans);
587 }
588 }
589#endif /* defined(_WIN32) || defined(WIN32) */
590 return zLine;
591}
592
593/*
594** Retrieve a single line of input text.
595**
596** If in==0 then read from standard input and prompt before each line.
597** If isContinuation is true, then a continuation prompt is appropriate.
598** If isContinuation is zero, then the main prompt should be used.
599**
600** If zPrior is not NULL then it is a buffer from a prior call to this
601** routine that can be reused.
602**
603** The result is stored in space obtained from malloc() and must either
604** be freed by the caller or else passed back into this routine via the
605** zPrior argument for reuse.
606*/
607static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
608 char *zPrompt;
609 char *zResult;
610 if( in!=0 ){
611 zResult = local_getline(zPrior, in);
612 }else{
613 zPrompt = isContinuation ? continuePrompt : mainPrompt;
614#if SHELL_USE_LOCAL_GETLINE
615 printf("%s", zPrompt);
616 fflush(stdout);
617 zResult = local_getline(zPrior, stdin);
618#else
619 free(zPrior);
620 zResult = shell_readline(zPrompt);
621 if( zResult && *zResult ) shell_add_history(zResult);
622#endif
623 }
624 return zResult;
625}
626/*
627** A variable length string to which one can append text.
628*/
629typedef struct ShellText ShellText;
630struct ShellText {
631 char *z;
632 int n;
633 int nAlloc;
634};
635
636/*
637** Initialize and destroy a ShellText object
638*/
639static void initText(ShellText *p){
640 memset(p, 0, sizeof(*p));
641}
642static void freeText(ShellText *p){
643 free(p->z);
644 initText(p);
645}
646
647/* zIn is either a pointer to a NULL-terminated string in memory obtained
648** from malloc(), or a NULL pointer. The string pointed to by zAppend is
649** added to zIn, and the result returned in memory obtained from malloc().
650** zIn, if it was not NULL, is freed.
651**
652** If the third argument, quote, is not '\0', then it is used as a
653** quote character for zAppend.
654*/
655static void appendText(ShellText *p, char const *zAppend, char quote){
656 int len;
657 int i;
658 int nAppend = strlen30(zAppend);
659
660 len = nAppend+p->n+1;
661 if( quote ){
662 len += 2;
663 for(i=0; i<nAppend; i++){
664 if( zAppend[i]==quote ) len++;
665 }
666 }
667
668 if( p->n+len>=p->nAlloc ){
669 p->nAlloc = p->nAlloc*2 + len + 20;
670 p->z = realloc(p->z, p->nAlloc);
671 if( p->z==0 ){
672 memset(p, 0, sizeof(*p));
673 return;
674 }
675 }
676
677 if( quote ){
678 char *zCsr = p->z+p->n;
679 *zCsr++ = quote;
680 for(i=0; i<nAppend; i++){
681 *zCsr++ = zAppend[i];
682 if( zAppend[i]==quote ) *zCsr++ = quote;
683 }
684 *zCsr++ = quote;
685 p->n = (int)(zCsr - p->z);
686 *zCsr = '\0';
687 }else{
688 memcpy(p->z+p->n, zAppend, nAppend);
689 p->n += nAppend;
690 p->z[p->n] = '\0';
691 }
692}
693
694/*
695** Attempt to determine if identifier zName needs to be quoted, either
696** because it contains non-alphanumeric characters, or because it is an
697** SQLite keyword. Be conservative in this estimate: When in doubt assume
698** that quoting is required.
699**
700** Return '"' if quoting is required. Return 0 if no quoting is required.
701*/
702static char quoteChar(const char *zName){
703 /* All SQLite keywords, in alphabetical order */
704 static const char *azKeywords[] = {
705 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
706 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
707 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
708 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
709 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
710 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
711 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
712 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
713 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
714 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
715 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
716 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
717 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
718 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
719 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
720 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
721 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
722 "WITH", "WITHOUT",
723 };
724 int i, lwr, upr, mid, c;
725 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
726 for(i=0; zName[i]; i++){
727 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
728 }
729 lwr = 0;
730 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
731 while( lwr<=upr ){
732 mid = (lwr+upr)/2;
733 c = sqlite3_stricmp(azKeywords[mid], zName);
734 if( c==0 ) return '"';
735 if( c<0 ){
736 lwr = mid+1;
737 }else{
738 upr = mid-1;
739 }
740 }
741 return 0;
742}
743
744/*
drh667a2a22018-01-02 00:04:37 +0000745** Construct a fake object name and column list to describe the structure
746** of the view, virtual table, or table valued function zSchema.zName.
drhceba7922018-01-01 21:28:25 +0000747*/
drh667a2a22018-01-02 00:04:37 +0000748static char *shellFakeSchema(
drhceba7922018-01-01 21:28:25 +0000749 sqlite3 *db, /* The database connection containing the vtab */
750 const char *zSchema, /* Schema of the database holding the vtab */
751 const char *zName /* The name of the virtual table */
752){
753 sqlite3_stmt *pStmt = 0;
754 char *zSql;
drh1d315cf2018-01-01 21:49:43 +0000755 ShellText s;
756 char cQuote;
757 char *zDiv = "(";
drh667a2a22018-01-02 00:04:37 +0000758 int nRow = 0;
drhceba7922018-01-01 21:28:25 +0000759
drh1d315cf2018-01-01 21:49:43 +0000760 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
761 zSchema ? zSchema : "main", zName);
drhceba7922018-01-01 21:28:25 +0000762 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
763 sqlite3_free(zSql);
drh1d315cf2018-01-01 21:49:43 +0000764 initText(&s);
765 if( zSchema ){
766 cQuote = quoteChar(zSchema);
767 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
768 appendText(&s, zSchema, cQuote);
769 appendText(&s, ".", 0);
drhceba7922018-01-01 21:28:25 +0000770 }
drh1d315cf2018-01-01 21:49:43 +0000771 cQuote = quoteChar(zName);
772 appendText(&s, zName, cQuote);
773 while( sqlite3_step(pStmt)==SQLITE_ROW ){
774 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
drh667a2a22018-01-02 00:04:37 +0000775 nRow++;
drh1d315cf2018-01-01 21:49:43 +0000776 appendText(&s, zDiv, 0);
777 zDiv = ",";
778 cQuote = quoteChar(zCol);
779 appendText(&s, zCol, cQuote);
780 }
781 appendText(&s, ")", 0);
drhceba7922018-01-01 21:28:25 +0000782 sqlite3_finalize(pStmt);
drh667a2a22018-01-02 00:04:37 +0000783 if( nRow==0 ){
784 freeText(&s);
785 s.z = 0;
786 }
drh1d315cf2018-01-01 21:49:43 +0000787 return s.z;
drhceba7922018-01-01 21:28:25 +0000788}
789
790/*
drh667a2a22018-01-02 00:04:37 +0000791** SQL function: shell_module_schema(X)
792**
793** Return a fake schema for the table-valued function or eponymous virtual
794** table X.
795*/
796static void shellModuleSchema(
797 sqlite3_context *pCtx,
798 int nVal,
799 sqlite3_value **apVal
800){
801 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
802 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
803 if( zFake ){
804 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %z */", zFake),
805 -1, sqlite3_free);
806 }
807}
808
809/*
drh2ce15c32017-07-11 13:34:40 +0000810** SQL function: shell_add_schema(S,X)
811**
812** Add the schema name X to the CREATE statement in S and return the result.
813** Examples:
814**
815** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
816**
817** Also works on
818**
819** CREATE INDEX
820** CREATE UNIQUE INDEX
821** CREATE VIEW
822** CREATE TRIGGER
823** CREATE VIRTUAL TABLE
824**
825** This UDF is used by the .schema command to insert the schema name of
826** attached databases into the middle of the sqlite_master.sql field.
827*/
828static void shellAddSchemaName(
829 sqlite3_context *pCtx,
830 int nVal,
831 sqlite3_value **apVal
832){
833 static const char *aPrefix[] = {
834 "TABLE",
835 "INDEX",
836 "UNIQUE INDEX",
837 "VIEW",
838 "TRIGGER",
839 "VIRTUAL TABLE"
840 };
841 int i = 0;
842 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
843 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
drh667a2a22018-01-02 00:04:37 +0000844 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
drhceba7922018-01-01 21:28:25 +0000845 sqlite3 *db = sqlite3_context_db_handle(pCtx);
drh2ce15c32017-07-11 13:34:40 +0000846 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
drh89997982017-07-11 18:11:33 +0000847 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
drh2ce15c32017-07-11 13:34:40 +0000848 int n = strlen30(aPrefix[i]);
849 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
drhceba7922018-01-01 21:28:25 +0000850 char *z = 0;
drh667a2a22018-01-02 00:04:37 +0000851 char *zFake = 0;
drhceba7922018-01-01 21:28:25 +0000852 if( zSchema ){
853 char cQuote = quoteChar(zSchema);
854 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
855 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
856 }else{
857 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
858 }
drh2ce15c32017-07-11 13:34:40 +0000859 }
drh667a2a22018-01-02 00:04:37 +0000860 if( zName
861 && aPrefix[i][0]=='V'
862 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
863 ){
864 if( z==0 ){
865 z = sqlite3_mprintf("%s\n/* %z */", zIn, zFake);
866 }else{
867 z = sqlite3_mprintf("%z\n/* %z */", z, zFake);
868 }
drhceba7922018-01-01 21:28:25 +0000869 }
870 if( z ){
871 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
872 return;
873 }
drh2ce15c32017-07-11 13:34:40 +0000874 }
875 }
876 }
877 sqlite3_result_value(pCtx, apVal[0]);
878}
879
880/*
881** The source code for several run-time loadable extensions is inserted
882** below by the ../tool/mkshellc.tcl script. Before processing that included
883** code, we need to override some macros to make the included program code
884** work here in the middle of this regular program.
885*/
886#define SQLITE_EXTENSION_INIT1
drh89997982017-07-11 18:11:33 +0000887#define SQLITE_EXTENSION_INIT2(X) (void)(X)
drh2ce15c32017-07-11 13:34:40 +0000888
mistachkinacae8c32018-01-05 20:08:46 +0000889#if defined(_WIN32) && defined(_MSC_VER)
mistachkindfdfd8c2018-01-04 22:46:08 +0000890INCLUDE test_windirent.c
891#define dirent DIRENT
mistachkindfdfd8c2018-01-04 22:46:08 +0000892#endif
drh2ce15c32017-07-11 13:34:40 +0000893INCLUDE ../ext/misc/shathree.c
894INCLUDE ../ext/misc/fileio.c
drh56eb09b2017-07-11 13:59:07 +0000895INCLUDE ../ext/misc/completion.c
dan72afc3c2017-12-05 18:32:40 +0000896#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +0000897INCLUDE ../ext/misc/zipfile.c
dand1b51d42017-12-16 19:11:26 +0000898INCLUDE ../ext/misc/sqlar.c
dan72afc3c2017-12-05 18:32:40 +0000899#endif
dan43efc182017-12-19 17:42:13 +0000900INCLUDE ../ext/expert/sqlite3expert.h
901INCLUDE ../ext/expert/sqlite3expert.c
drh2ce15c32017-07-11 13:34:40 +0000902
903#if defined(SQLITE_ENABLE_SESSION)
904/*
905** State information for a single open session
906*/
907typedef struct OpenSession OpenSession;
908struct OpenSession {
909 char *zName; /* Symbolic name for this session */
910 int nFilter; /* Number of xFilter rejection GLOB patterns */
911 char **azFilter; /* Array of xFilter rejection GLOB patterns */
912 sqlite3_session *p; /* The open session */
913};
914#endif
915
916/*
917** Shell output mode information from before ".explain on",
918** saved so that it can be restored by ".explain off"
919*/
920typedef struct SavedModeInfo SavedModeInfo;
921struct SavedModeInfo {
922 int valid; /* Is there legit data in here? */
923 int mode; /* Mode prior to ".explain on" */
924 int showHeader; /* The ".header" setting prior to ".explain on" */
925 int colWidth[100]; /* Column widths prior to ".explain on" */
926};
927
dan43efc182017-12-19 17:42:13 +0000928typedef struct ExpertInfo ExpertInfo;
929struct ExpertInfo {
930 sqlite3expert *pExpert;
931 int bVerbose;
932};
933
drh2ce15c32017-07-11 13:34:40 +0000934/*
935** State information about the database connection is contained in an
936** instance of the following structure.
937*/
938typedef struct ShellState ShellState;
939struct ShellState {
940 sqlite3 *db; /* The database */
941 int autoExplain; /* Automatically turn on .explain mode */
942 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
943 int statsOn; /* True to display memory stats before each finalize */
944 int scanstatsOn; /* True to display scan stats before each finalize */
945 int outCount; /* Revert to stdout when reaching zero */
946 int cnt; /* Number of records displayed so far */
947 FILE *out; /* Write results here */
948 FILE *traceOut; /* Output for sqlite3_trace() */
949 int nErr; /* Number of errors seen */
950 int mode; /* An output mode setting */
951 int cMode; /* temporary output mode for the current query */
952 int normalMode; /* Output mode before ".explain on" */
953 int writableSchema; /* True if PRAGMA writable_schema=ON */
954 int showHeader; /* True to show column names in List or Column mode */
955 int nCheck; /* Number of ".check" commands run */
956 unsigned shellFlgs; /* Various flags */
957 char *zDestTable; /* Name of destination table when MODE_Insert */
958 char zTestcase[30]; /* Name of current test case */
959 char colSeparator[20]; /* Column separator character for several modes */
960 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
961 int colWidth[100]; /* Requested width of each column when in column mode*/
962 int actualWidth[100]; /* Actual width of each column */
963 char nullValue[20]; /* The text to print when a NULL comes back from
964 ** the database */
965 char outfile[FILENAME_MAX]; /* Filename for *out */
966 const char *zDbFilename; /* name of the database file */
967 char *zFreeOnClose; /* Filename to free when closing */
968 const char *zVfs; /* Name of VFS to use */
969 sqlite3_stmt *pStmt; /* Current statement if any. */
970 FILE *pLog; /* Write log output here */
971 int *aiIndent; /* Array of indents used in MODE_Explain */
972 int nIndent; /* Size of array aiIndent[] */
973 int iIndent; /* Index of current op in aiIndent[] */
974#if defined(SQLITE_ENABLE_SESSION)
975 int nSession; /* Number of active sessions */
976 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
977#endif
dan43efc182017-12-19 17:42:13 +0000978 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
drh2ce15c32017-07-11 13:34:40 +0000979};
980
drhada70452017-12-21 21:02:27 +0000981/* Allowed values for ShellState.autoEQP
982*/
983#define AUTOEQP_off 0
984#define AUTOEQP_on 1
985#define AUTOEQP_trigger 2
986#define AUTOEQP_full 3
987
drh2ce15c32017-07-11 13:34:40 +0000988/*
989** These are the allowed shellFlgs values
990*/
drhb2a0f752017-08-28 15:51:35 +0000991#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
992#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
993#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
994#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
995#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
996#define SHFLG_CountChanges 0x00000020 /* .changes setting */
997#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
drh2ce15c32017-07-11 13:34:40 +0000998
999/*
1000** Macros for testing and setting shellFlgs
1001*/
1002#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1003#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1004#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1005
1006/*
1007** These are the allowed modes.
1008*/
1009#define MODE_Line 0 /* One column per line. Blank line between records */
1010#define MODE_Column 1 /* One record per line in neat columns */
1011#define MODE_List 2 /* One record per line with a separator */
1012#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1013#define MODE_Html 4 /* Generate an XHTML table */
1014#define MODE_Insert 5 /* Generate SQL "insert" statements */
1015#define MODE_Quote 6 /* Quote values as for SQL */
1016#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1017#define MODE_Csv 8 /* Quote strings, numbers are plain */
1018#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1019#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1020#define MODE_Pretty 11 /* Pretty-print schemas */
1021
1022static const char *modeDescr[] = {
1023 "line",
1024 "column",
1025 "list",
1026 "semi",
1027 "html",
1028 "insert",
1029 "quote",
1030 "tcl",
1031 "csv",
1032 "explain",
1033 "ascii",
1034 "prettyprint",
1035};
1036
1037/*
1038** These are the column/row/line separators used by the various
1039** import/export modes.
1040*/
1041#define SEP_Column "|"
1042#define SEP_Row "\n"
1043#define SEP_Tab "\t"
1044#define SEP_Space " "
1045#define SEP_Comma ","
1046#define SEP_CrLf "\r\n"
1047#define SEP_Unit "\x1F"
1048#define SEP_Record "\x1E"
1049
1050/*
1051** Number of elements in an array
1052*/
1053#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
1054
1055/*
1056** A callback for the sqlite3_log() interface.
1057*/
1058static void shellLog(void *pArg, int iErrCode, const char *zMsg){
1059 ShellState *p = (ShellState*)pArg;
1060 if( p->pLog==0 ) return;
1061 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
1062 fflush(p->pLog);
1063}
1064
1065/*
1066** Output the given string as a hex-encoded blob (eg. X'1234' )
1067*/
1068static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1069 int i;
1070 char *zBlob = (char *)pBlob;
1071 raw_printf(out,"X'");
1072 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1073 raw_printf(out,"'");
1074}
1075
1076/*
1077** Find a string that is not found anywhere in z[]. Return a pointer
1078** to that string.
1079**
1080** Try to use zA and zB first. If both of those are already found in z[]
1081** then make up some string and store it in the buffer zBuf.
1082*/
1083static const char *unused_string(
1084 const char *z, /* Result must not appear anywhere in z */
1085 const char *zA, const char *zB, /* Try these first */
1086 char *zBuf /* Space to store a generated string */
1087){
1088 unsigned i = 0;
1089 if( strstr(z, zA)==0 ) return zA;
1090 if( strstr(z, zB)==0 ) return zB;
1091 do{
1092 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1093 }while( strstr(z,zBuf)!=0 );
1094 return zBuf;
1095}
1096
1097/*
1098** Output the given string as a quoted string using SQL quoting conventions.
1099**
1100** See also: output_quoted_escaped_string()
1101*/
1102static void output_quoted_string(FILE *out, const char *z){
1103 int i;
1104 char c;
1105 setBinaryMode(out, 1);
1106 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1107 if( c==0 ){
1108 utf8_printf(out,"'%s'",z);
1109 }else{
1110 raw_printf(out, "'");
1111 while( *z ){
1112 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1113 if( c=='\'' ) i++;
1114 if( i ){
1115 utf8_printf(out, "%.*s", i, z);
1116 z += i;
1117 }
1118 if( c=='\'' ){
1119 raw_printf(out, "'");
1120 continue;
1121 }
1122 if( c==0 ){
1123 break;
1124 }
1125 z++;
1126 }
1127 raw_printf(out, "'");
1128 }
1129 setTextMode(out, 1);
1130}
1131
1132/*
1133** Output the given string as a quoted string using SQL quoting conventions.
1134** Additionallly , escape the "\n" and "\r" characters so that they do not
1135** get corrupted by end-of-line translation facilities in some operating
1136** systems.
1137**
1138** This is like output_quoted_string() but with the addition of the \r\n
1139** escape mechanism.
1140*/
1141static void output_quoted_escaped_string(FILE *out, const char *z){
1142 int i;
1143 char c;
1144 setBinaryMode(out, 1);
1145 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1146 if( c==0 ){
1147 utf8_printf(out,"'%s'",z);
1148 }else{
1149 const char *zNL = 0;
1150 const char *zCR = 0;
1151 int nNL = 0;
1152 int nCR = 0;
1153 char zBuf1[20], zBuf2[20];
1154 for(i=0; z[i]; i++){
1155 if( z[i]=='\n' ) nNL++;
1156 if( z[i]=='\r' ) nCR++;
1157 }
1158 if( nNL ){
1159 raw_printf(out, "replace(");
1160 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1161 }
1162 if( nCR ){
1163 raw_printf(out, "replace(");
1164 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1165 }
1166 raw_printf(out, "'");
1167 while( *z ){
1168 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1169 if( c=='\'' ) i++;
1170 if( i ){
1171 utf8_printf(out, "%.*s", i, z);
1172 z += i;
1173 }
1174 if( c=='\'' ){
1175 raw_printf(out, "'");
1176 continue;
1177 }
1178 if( c==0 ){
1179 break;
1180 }
1181 z++;
1182 if( c=='\n' ){
1183 raw_printf(out, "%s", zNL);
1184 continue;
1185 }
1186 raw_printf(out, "%s", zCR);
1187 }
1188 raw_printf(out, "'");
1189 if( nCR ){
1190 raw_printf(out, ",'%s',char(13))", zCR);
1191 }
1192 if( nNL ){
1193 raw_printf(out, ",'%s',char(10))", zNL);
1194 }
1195 }
1196 setTextMode(out, 1);
1197}
1198
1199/*
1200** Output the given string as a quoted according to C or TCL quoting rules.
1201*/
1202static void output_c_string(FILE *out, const char *z){
1203 unsigned int c;
1204 fputc('"', out);
1205 while( (c = *(z++))!=0 ){
1206 if( c=='\\' ){
1207 fputc(c, out);
1208 fputc(c, out);
1209 }else if( c=='"' ){
1210 fputc('\\', out);
1211 fputc('"', out);
1212 }else if( c=='\t' ){
1213 fputc('\\', out);
1214 fputc('t', out);
1215 }else if( c=='\n' ){
1216 fputc('\\', out);
1217 fputc('n', out);
1218 }else if( c=='\r' ){
1219 fputc('\\', out);
1220 fputc('r', out);
1221 }else if( !isprint(c&0xff) ){
1222 raw_printf(out, "\\%03o", c&0xff);
1223 }else{
1224 fputc(c, out);
1225 }
1226 }
1227 fputc('"', out);
1228}
1229
1230/*
1231** Output the given string with characters that are special to
1232** HTML escaped.
1233*/
1234static void output_html_string(FILE *out, const char *z){
1235 int i;
1236 if( z==0 ) z = "";
1237 while( *z ){
1238 for(i=0; z[i]
1239 && z[i]!='<'
1240 && z[i]!='&'
1241 && z[i]!='>'
1242 && z[i]!='\"'
1243 && z[i]!='\'';
1244 i++){}
1245 if( i>0 ){
1246 utf8_printf(out,"%.*s",i,z);
1247 }
1248 if( z[i]=='<' ){
1249 raw_printf(out,"&lt;");
1250 }else if( z[i]=='&' ){
1251 raw_printf(out,"&amp;");
1252 }else if( z[i]=='>' ){
1253 raw_printf(out,"&gt;");
1254 }else if( z[i]=='\"' ){
1255 raw_printf(out,"&quot;");
1256 }else if( z[i]=='\'' ){
1257 raw_printf(out,"&#39;");
1258 }else{
1259 break;
1260 }
1261 z += i + 1;
1262 }
1263}
1264
1265/*
1266** If a field contains any character identified by a 1 in the following
1267** array, then the string must be quoted for CSV.
1268*/
1269static const char needCsvQuote[] = {
1270 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1271 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1272 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1273 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1274 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1275 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1276 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1277 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1278 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1279 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1280 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1281 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1282 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1283 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1284 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1285 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1286};
1287
1288/*
1289** Output a single term of CSV. Actually, p->colSeparator is used for
1290** the separator, which may or may not be a comma. p->nullValue is
1291** the null value. Strings are quoted if necessary. The separator
1292** is only issued if bSep is true.
1293*/
1294static void output_csv(ShellState *p, const char *z, int bSep){
1295 FILE *out = p->out;
1296 if( z==0 ){
1297 utf8_printf(out,"%s",p->nullValue);
1298 }else{
1299 int i;
1300 int nSep = strlen30(p->colSeparator);
1301 for(i=0; z[i]; i++){
1302 if( needCsvQuote[((unsigned char*)z)[i]]
1303 || (z[i]==p->colSeparator[0] &&
1304 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
1305 i = 0;
1306 break;
1307 }
1308 }
1309 if( i==0 ){
drh9b7affc2017-11-26 02:14:18 +00001310 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
1311 utf8_printf(out, "%s", zQuoted);
1312 sqlite3_free(zQuoted);
drh2ce15c32017-07-11 13:34:40 +00001313 }else{
1314 utf8_printf(out, "%s", z);
1315 }
1316 }
1317 if( bSep ){
1318 utf8_printf(p->out, "%s", p->colSeparator);
1319 }
1320}
1321
drh2ce15c32017-07-11 13:34:40 +00001322/*
1323** This routine runs when the user presses Ctrl-C
1324*/
1325static void interrupt_handler(int NotUsed){
1326 UNUSED_PARAMETER(NotUsed);
1327 seenInterrupt++;
1328 if( seenInterrupt>2 ) exit(1);
1329 if( globalDb ) sqlite3_interrupt(globalDb);
1330}
mistachkinb4bab902017-10-27 17:09:44 +00001331
1332#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1333/*
1334** This routine runs for console events (e.g. Ctrl-C) on Win32
1335*/
1336static BOOL WINAPI ConsoleCtrlHandler(
1337 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
1338){
1339 if( dwCtrlType==CTRL_C_EVENT ){
1340 interrupt_handler(0);
1341 return TRUE;
1342 }
1343 return FALSE;
1344}
drh2ce15c32017-07-11 13:34:40 +00001345#endif
1346
1347#ifndef SQLITE_OMIT_AUTHORIZATION
1348/*
1349** When the ".auth ON" is set, the following authorizer callback is
1350** invoked. It always returns SQLITE_OK.
1351*/
1352static int shellAuth(
1353 void *pClientData,
1354 int op,
1355 const char *zA1,
1356 const char *zA2,
1357 const char *zA3,
1358 const char *zA4
1359){
1360 ShellState *p = (ShellState*)pClientData;
1361 static const char *azAction[] = { 0,
1362 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1363 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1364 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1365 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1366 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1367 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1368 "PRAGMA", "READ", "SELECT",
1369 "TRANSACTION", "UPDATE", "ATTACH",
1370 "DETACH", "ALTER_TABLE", "REINDEX",
1371 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1372 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1373 };
1374 int i;
1375 const char *az[4];
1376 az[0] = zA1;
1377 az[1] = zA2;
1378 az[2] = zA3;
1379 az[3] = zA4;
1380 utf8_printf(p->out, "authorizer: %s", azAction[op]);
1381 for(i=0; i<4; i++){
1382 raw_printf(p->out, " ");
1383 if( az[i] ){
1384 output_c_string(p->out, az[i]);
1385 }else{
1386 raw_printf(p->out, "NULL");
1387 }
1388 }
1389 raw_printf(p->out, "\n");
1390 return SQLITE_OK;
1391}
1392#endif
1393
1394/*
1395** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1396**
1397** This routine converts some CREATE TABLE statements for shadow tables
1398** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1399*/
1400static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1401 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1402 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1403 }else{
1404 utf8_printf(out, "%s%s", z, zTail);
1405 }
1406}
1407static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1408 char c = z[n];
1409 z[n] = 0;
1410 printSchemaLine(out, z, zTail);
1411 z[n] = c;
1412}
1413
1414/*
drh11be81d2018-01-06 15:46:20 +00001415** Return true if string z[] has nothing but whitespace and comments to the
1416** end of the first line.
1417*/
1418static int wsToEol(const char *z){
1419 int i;
1420 for(i=0; z[i]; i++){
1421 if( z[i]=='\n' ) return 1;
1422 if( IsSpace(z[i]) ) continue;
1423 if( z[i]=='-' && z[i+1]=='-' ) return 1;
1424 return 0;
1425 }
1426 return 1;
1427}
1428
1429
1430/*
drh2ce15c32017-07-11 13:34:40 +00001431** This is the callback routine that the shell
1432** invokes for each row of a query result.
1433*/
1434static int shell_callback(
1435 void *pArg,
1436 int nArg, /* Number of result columns */
1437 char **azArg, /* Text of each result column */
1438 char **azCol, /* Column names */
1439 int *aiType /* Column types */
1440){
1441 int i;
1442 ShellState *p = (ShellState*)pArg;
1443
drhb3c45232017-08-28 14:33:27 +00001444 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001445 switch( p->cMode ){
1446 case MODE_Line: {
1447 int w = 5;
1448 if( azArg==0 ) break;
1449 for(i=0; i<nArg; i++){
1450 int len = strlen30(azCol[i] ? azCol[i] : "");
1451 if( len>w ) w = len;
1452 }
1453 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1454 for(i=0; i<nArg; i++){
1455 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1456 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1457 }
1458 break;
1459 }
1460 case MODE_Explain:
1461 case MODE_Column: {
1462 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1463 const int *colWidth;
1464 int showHdr;
1465 char *rowSep;
1466 if( p->cMode==MODE_Column ){
1467 colWidth = p->colWidth;
1468 showHdr = p->showHeader;
1469 rowSep = p->rowSeparator;
1470 }else{
1471 colWidth = aExplainWidths;
1472 showHdr = 1;
1473 rowSep = SEP_Row;
1474 }
1475 if( p->cnt++==0 ){
1476 for(i=0; i<nArg; i++){
1477 int w, n;
1478 if( i<ArraySize(p->colWidth) ){
1479 w = colWidth[i];
1480 }else{
1481 w = 0;
1482 }
1483 if( w==0 ){
1484 w = strlenChar(azCol[i] ? azCol[i] : "");
1485 if( w<10 ) w = 10;
1486 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1487 if( w<n ) w = n;
1488 }
1489 if( i<ArraySize(p->actualWidth) ){
1490 p->actualWidth[i] = w;
1491 }
1492 if( showHdr ){
1493 utf8_width_print(p->out, w, azCol[i]);
1494 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1495 }
1496 }
1497 if( showHdr ){
1498 for(i=0; i<nArg; i++){
1499 int w;
1500 if( i<ArraySize(p->actualWidth) ){
1501 w = p->actualWidth[i];
1502 if( w<0 ) w = -w;
1503 }else{
1504 w = 10;
1505 }
1506 utf8_printf(p->out,"%-*.*s%s",w,w,
1507 "----------------------------------------------------------"
1508 "----------------------------------------------------------",
1509 i==nArg-1 ? rowSep : " ");
1510 }
1511 }
1512 }
1513 if( azArg==0 ) break;
1514 for(i=0; i<nArg; i++){
1515 int w;
1516 if( i<ArraySize(p->actualWidth) ){
1517 w = p->actualWidth[i];
1518 }else{
1519 w = 10;
1520 }
1521 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1522 w = strlenChar(azArg[i]);
1523 }
1524 if( i==1 && p->aiIndent && p->pStmt ){
1525 if( p->iIndent<p->nIndent ){
1526 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1527 }
1528 p->iIndent++;
1529 }
1530 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1531 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1532 }
1533 break;
1534 }
1535 case MODE_Semi: { /* .schema and .fullschema output */
1536 printSchemaLine(p->out, azArg[0], ";\n");
1537 break;
1538 }
1539 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1540 char *z;
1541 int j;
1542 int nParen = 0;
1543 char cEnd = 0;
1544 char c;
1545 int nLine = 0;
1546 assert( nArg==1 );
1547 if( azArg[0]==0 ) break;
1548 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1549 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1550 ){
1551 utf8_printf(p->out, "%s;\n", azArg[0]);
1552 break;
1553 }
1554 z = sqlite3_mprintf("%s", azArg[0]);
1555 j = 0;
1556 for(i=0; IsSpace(z[i]); i++){}
1557 for(; (c = z[i])!=0; i++){
1558 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001559 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001560 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1561 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1562 j--;
1563 }
1564 z[j++] = c;
1565 }
1566 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1567 z[j] = 0;
1568 if( strlen30(z)>=79 ){
drh11be81d2018-01-06 15:46:20 +00001569 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
drh2ce15c32017-07-11 13:34:40 +00001570 if( c==cEnd ){
1571 cEnd = 0;
1572 }else if( c=='"' || c=='\'' || c=='`' ){
1573 cEnd = c;
1574 }else if( c=='[' ){
1575 cEnd = ']';
drh11be81d2018-01-06 15:46:20 +00001576 }else if( c=='-' && z[i+1]=='-' ){
1577 cEnd = '\n';
drh2ce15c32017-07-11 13:34:40 +00001578 }else if( c=='(' ){
1579 nParen++;
1580 }else if( c==')' ){
1581 nParen--;
1582 if( nLine>0 && nParen==0 && j>0 ){
1583 printSchemaLineN(p->out, z, j, "\n");
1584 j = 0;
1585 }
1586 }
1587 z[j++] = c;
drh11be81d2018-01-06 15:46:20 +00001588 if( nParen==1 && cEnd==0
1589 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
1590 ){
drh2ce15c32017-07-11 13:34:40 +00001591 if( c=='\n' ) j--;
1592 printSchemaLineN(p->out, z, j, "\n ");
1593 j = 0;
1594 nLine++;
1595 while( IsSpace(z[i+1]) ){ i++; }
1596 }
1597 }
1598 z[j] = 0;
1599 }
1600 printSchemaLine(p->out, z, ";\n");
1601 sqlite3_free(z);
1602 break;
1603 }
1604 case MODE_List: {
1605 if( p->cnt++==0 && p->showHeader ){
1606 for(i=0; i<nArg; i++){
1607 utf8_printf(p->out,"%s%s",azCol[i],
1608 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1609 }
1610 }
1611 if( azArg==0 ) break;
1612 for(i=0; i<nArg; i++){
1613 char *z = azArg[i];
1614 if( z==0 ) z = p->nullValue;
1615 utf8_printf(p->out, "%s", z);
1616 if( i<nArg-1 ){
1617 utf8_printf(p->out, "%s", p->colSeparator);
1618 }else{
1619 utf8_printf(p->out, "%s", p->rowSeparator);
1620 }
1621 }
1622 break;
1623 }
1624 case MODE_Html: {
1625 if( p->cnt++==0 && p->showHeader ){
1626 raw_printf(p->out,"<TR>");
1627 for(i=0; i<nArg; i++){
1628 raw_printf(p->out,"<TH>");
1629 output_html_string(p->out, azCol[i]);
1630 raw_printf(p->out,"</TH>\n");
1631 }
1632 raw_printf(p->out,"</TR>\n");
1633 }
1634 if( azArg==0 ) break;
1635 raw_printf(p->out,"<TR>");
1636 for(i=0; i<nArg; i++){
1637 raw_printf(p->out,"<TD>");
1638 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1639 raw_printf(p->out,"</TD>\n");
1640 }
1641 raw_printf(p->out,"</TR>\n");
1642 break;
1643 }
1644 case MODE_Tcl: {
1645 if( p->cnt++==0 && p->showHeader ){
1646 for(i=0; i<nArg; i++){
1647 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1648 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1649 }
1650 utf8_printf(p->out, "%s", p->rowSeparator);
1651 }
1652 if( azArg==0 ) break;
1653 for(i=0; i<nArg; i++){
1654 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1655 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1656 }
1657 utf8_printf(p->out, "%s", p->rowSeparator);
1658 break;
1659 }
1660 case MODE_Csv: {
1661 setBinaryMode(p->out, 1);
1662 if( p->cnt++==0 && p->showHeader ){
1663 for(i=0; i<nArg; i++){
1664 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1665 }
1666 utf8_printf(p->out, "%s", p->rowSeparator);
1667 }
1668 if( nArg>0 ){
1669 for(i=0; i<nArg; i++){
1670 output_csv(p, azArg[i], i<nArg-1);
1671 }
1672 utf8_printf(p->out, "%s", p->rowSeparator);
1673 }
1674 setTextMode(p->out, 1);
1675 break;
1676 }
1677 case MODE_Insert: {
1678 if( azArg==0 ) break;
1679 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
1680 if( p->showHeader ){
1681 raw_printf(p->out,"(");
1682 for(i=0; i<nArg; i++){
1683 if( i>0 ) raw_printf(p->out, ",");
1684 if( quoteChar(azCol[i]) ){
1685 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
1686 utf8_printf(p->out, "%s", z);
1687 sqlite3_free(z);
1688 }else{
1689 raw_printf(p->out, "%s", azCol[i]);
1690 }
1691 }
1692 raw_printf(p->out,")");
1693 }
1694 p->cnt++;
1695 for(i=0; i<nArg; i++){
1696 raw_printf(p->out, i>0 ? "," : " VALUES(");
1697 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1698 utf8_printf(p->out,"NULL");
1699 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1700 if( ShellHasFlag(p, SHFLG_Newlines) ){
1701 output_quoted_string(p->out, azArg[i]);
1702 }else{
1703 output_quoted_escaped_string(p->out, azArg[i]);
1704 }
1705 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1706 utf8_printf(p->out,"%s", azArg[i]);
1707 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1708 char z[50];
1709 double r = sqlite3_column_double(p->pStmt, i);
1710 sqlite3_snprintf(50,z,"%!.20g", r);
1711 raw_printf(p->out, "%s", z);
1712 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1713 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1714 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1715 output_hex_blob(p->out, pBlob, nBlob);
1716 }else if( isNumber(azArg[i], 0) ){
1717 utf8_printf(p->out,"%s", azArg[i]);
1718 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
1719 output_quoted_string(p->out, azArg[i]);
1720 }else{
1721 output_quoted_escaped_string(p->out, azArg[i]);
1722 }
1723 }
1724 raw_printf(p->out,");\n");
1725 break;
1726 }
1727 case MODE_Quote: {
1728 if( azArg==0 ) break;
1729 if( p->cnt==0 && p->showHeader ){
1730 for(i=0; i<nArg; i++){
1731 if( i>0 ) raw_printf(p->out, ",");
1732 output_quoted_string(p->out, azCol[i]);
1733 }
1734 raw_printf(p->out,"\n");
1735 }
1736 p->cnt++;
1737 for(i=0; i<nArg; i++){
1738 if( i>0 ) raw_printf(p->out, ",");
1739 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1740 utf8_printf(p->out,"NULL");
1741 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1742 output_quoted_string(p->out, azArg[i]);
1743 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1744 utf8_printf(p->out,"%s", azArg[i]);
1745 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1746 char z[50];
1747 double r = sqlite3_column_double(p->pStmt, i);
1748 sqlite3_snprintf(50,z,"%!.20g", r);
1749 raw_printf(p->out, "%s", z);
1750 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1751 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1752 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1753 output_hex_blob(p->out, pBlob, nBlob);
1754 }else if( isNumber(azArg[i], 0) ){
1755 utf8_printf(p->out,"%s", azArg[i]);
1756 }else{
1757 output_quoted_string(p->out, azArg[i]);
1758 }
1759 }
1760 raw_printf(p->out,"\n");
1761 break;
1762 }
1763 case MODE_Ascii: {
1764 if( p->cnt++==0 && p->showHeader ){
1765 for(i=0; i<nArg; i++){
1766 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1767 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
1768 }
1769 utf8_printf(p->out, "%s", p->rowSeparator);
1770 }
1771 if( azArg==0 ) break;
1772 for(i=0; i<nArg; i++){
1773 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1774 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
1775 }
1776 utf8_printf(p->out, "%s", p->rowSeparator);
1777 break;
1778 }
1779 }
1780 return 0;
1781}
1782
1783/*
1784** This is the callback routine that the SQLite library
1785** invokes for each row of a query result.
1786*/
1787static int callback(void *pArg, int nArg, char **azArg, char **azCol){
1788 /* since we don't have type info, call the shell_callback with a NULL value */
1789 return shell_callback(pArg, nArg, azArg, azCol, NULL);
1790}
1791
1792/*
1793** This is the callback routine from sqlite3_exec() that appends all
1794** output onto the end of a ShellText object.
1795*/
1796static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
1797 ShellText *p = (ShellText*)pArg;
1798 int i;
1799 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00001800 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001801 if( p->n ) appendText(p, "|", 0);
1802 for(i=0; i<nArg; i++){
1803 if( i ) appendText(p, ",", 0);
1804 if( azArg[i] ) appendText(p, azArg[i], 0);
1805 }
1806 return 0;
1807}
1808
1809/*
1810** Generate an appropriate SELFTEST table in the main database.
1811*/
1812static void createSelftestTable(ShellState *p){
1813 char *zErrMsg = 0;
1814 sqlite3_exec(p->db,
1815 "SAVEPOINT selftest_init;\n"
1816 "CREATE TABLE IF NOT EXISTS selftest(\n"
1817 " tno INTEGER PRIMARY KEY,\n" /* Test number */
1818 " op TEXT,\n" /* Operator: memo run */
1819 " cmd TEXT,\n" /* Command text */
1820 " ans TEXT\n" /* Desired answer */
1821 ");"
1822 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
1823 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
1824 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
1825 " 'memo','Tests generated by --init');\n"
1826 "INSERT INTO [_shell$self]\n"
1827 " SELECT 'run',\n"
1828 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
1829 "FROM sqlite_master ORDER BY 2'',224))',\n"
1830 " hex(sha3_query('SELECT type,name,tbl_name,sql "
1831 "FROM sqlite_master ORDER BY 2',224));\n"
1832 "INSERT INTO [_shell$self]\n"
1833 " SELECT 'run',"
1834 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
1835 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
1836 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
1837 " FROM (\n"
1838 " SELECT name FROM sqlite_master\n"
1839 " WHERE type='table'\n"
1840 " AND name<>'selftest'\n"
1841 " AND coalesce(rootpage,0)>0\n"
1842 " )\n"
1843 " ORDER BY name;\n"
1844 "INSERT INTO [_shell$self]\n"
1845 " VALUES('run','PRAGMA integrity_check','ok');\n"
1846 "INSERT INTO selftest(tno,op,cmd,ans)"
1847 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
1848 "DROP TABLE [_shell$self];"
1849 ,0,0,&zErrMsg);
1850 if( zErrMsg ){
1851 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
1852 sqlite3_free(zErrMsg);
1853 }
1854 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
1855}
1856
1857
1858/*
1859** Set the destination table field of the ShellState structure to
1860** the name of the table given. Escape any quote characters in the
1861** table name.
1862*/
1863static void set_table_name(ShellState *p, const char *zName){
1864 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00001865 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00001866 char *z;
1867
1868 if( p->zDestTable ){
1869 free(p->zDestTable);
1870 p->zDestTable = 0;
1871 }
1872 if( zName==0 ) return;
1873 cQuote = quoteChar(zName);
1874 n = strlen30(zName);
1875 if( cQuote ) n += n+2;
1876 z = p->zDestTable = malloc( n+1 );
1877 if( z==0 ){
1878 raw_printf(stderr,"Error: out of memory\n");
1879 exit(1);
1880 }
1881 n = 0;
1882 if( cQuote ) z[n++] = cQuote;
1883 for(i=0; zName[i]; i++){
1884 z[n++] = zName[i];
1885 if( zName[i]==cQuote ) z[n++] = cQuote;
1886 }
1887 if( cQuote ) z[n++] = cQuote;
1888 z[n] = 0;
1889}
1890
1891
1892/*
1893** Execute a query statement that will generate SQL output. Print
1894** the result columns, comma-separated, on a line and then add a
1895** semicolon terminator to the end of that line.
1896**
1897** If the number of columns is 1 and that column contains text "--"
1898** then write the semicolon on a separate line. That way, if a
1899** "--" comment occurs at the end of the statement, the comment
1900** won't consume the semicolon terminator.
1901*/
1902static int run_table_dump_query(
1903 ShellState *p, /* Query context */
1904 const char *zSelect, /* SELECT statement to extract content */
1905 const char *zFirstRow /* Print before first row, if not NULL */
1906){
1907 sqlite3_stmt *pSelect;
1908 int rc;
1909 int nResult;
1910 int i;
1911 const char *z;
1912 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
1913 if( rc!=SQLITE_OK || !pSelect ){
1914 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1915 sqlite3_errmsg(p->db));
1916 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1917 return rc;
1918 }
1919 rc = sqlite3_step(pSelect);
1920 nResult = sqlite3_column_count(pSelect);
1921 while( rc==SQLITE_ROW ){
1922 if( zFirstRow ){
1923 utf8_printf(p->out, "%s", zFirstRow);
1924 zFirstRow = 0;
1925 }
1926 z = (const char*)sqlite3_column_text(pSelect, 0);
1927 utf8_printf(p->out, "%s", z);
1928 for(i=1; i<nResult; i++){
1929 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
1930 }
1931 if( z==0 ) z = "";
1932 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
1933 if( z[0] ){
1934 raw_printf(p->out, "\n;\n");
1935 }else{
1936 raw_printf(p->out, ";\n");
1937 }
1938 rc = sqlite3_step(pSelect);
1939 }
1940 rc = sqlite3_finalize(pSelect);
1941 if( rc!=SQLITE_OK ){
1942 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1943 sqlite3_errmsg(p->db));
1944 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1945 }
1946 return rc;
1947}
1948
1949/*
1950** Allocate space and save off current error string.
1951*/
1952static char *save_err_msg(
1953 sqlite3 *db /* Database to query */
1954){
1955 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
1956 char *zErrMsg = sqlite3_malloc64(nErrMsg);
1957 if( zErrMsg ){
1958 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
1959 }
1960 return zErrMsg;
1961}
1962
1963#ifdef __linux__
1964/*
1965** Attempt to display I/O stats on Linux using /proc/PID/io
1966*/
1967static void displayLinuxIoStats(FILE *out){
1968 FILE *in;
1969 char z[200];
1970 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
1971 in = fopen(z, "rb");
1972 if( in==0 ) return;
1973 while( fgets(z, sizeof(z), in)!=0 ){
1974 static const struct {
1975 const char *zPattern;
1976 const char *zDesc;
1977 } aTrans[] = {
1978 { "rchar: ", "Bytes received by read():" },
1979 { "wchar: ", "Bytes sent to write():" },
1980 { "syscr: ", "Read() system calls:" },
1981 { "syscw: ", "Write() system calls:" },
1982 { "read_bytes: ", "Bytes read from storage:" },
1983 { "write_bytes: ", "Bytes written to storage:" },
1984 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
1985 };
1986 int i;
1987 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00001988 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00001989 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
1990 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
1991 break;
1992 }
1993 }
1994 }
1995 fclose(in);
1996}
1997#endif
1998
1999/*
2000** Display a single line of status using 64-bit values.
2001*/
2002static void displayStatLine(
2003 ShellState *p, /* The shell context */
2004 char *zLabel, /* Label for this one line */
2005 char *zFormat, /* Format for the result */
2006 int iStatusCtrl, /* Which status to display */
2007 int bReset /* True to reset the stats */
2008){
2009 sqlite3_int64 iCur = -1;
2010 sqlite3_int64 iHiwtr = -1;
2011 int i, nPercent;
2012 char zLine[200];
2013 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2014 for(i=0, nPercent=0; zFormat[i]; i++){
2015 if( zFormat[i]=='%' ) nPercent++;
2016 }
2017 if( nPercent>1 ){
2018 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2019 }else{
2020 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2021 }
2022 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2023}
2024
2025/*
2026** Display memory stats.
2027*/
2028static int display_stats(
2029 sqlite3 *db, /* Database to query */
2030 ShellState *pArg, /* Pointer to ShellState */
2031 int bReset /* True to reset the stats */
2032){
2033 int iCur;
2034 int iHiwtr;
2035
2036 if( pArg && pArg->out ){
2037 displayStatLine(pArg, "Memory Used:",
2038 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2039 displayStatLine(pArg, "Number of Outstanding Allocations:",
2040 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2041 if( pArg->shellFlgs & SHFLG_Pagecache ){
2042 displayStatLine(pArg, "Number of Pcache Pages Used:",
2043 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2044 }
2045 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2046 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
drh2ce15c32017-07-11 13:34:40 +00002047 displayStatLine(pArg, "Largest Allocation:",
2048 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2049 displayStatLine(pArg, "Largest Pcache Allocation:",
2050 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
drh2ce15c32017-07-11 13:34:40 +00002051#ifdef YYTRACKMAXSTACKDEPTH
2052 displayStatLine(pArg, "Deepest Parser Stack:",
2053 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2054#endif
2055 }
2056
2057 if( pArg && pArg->out && db ){
2058 if( pArg->shellFlgs & SHFLG_Lookaside ){
2059 iHiwtr = iCur = -1;
2060 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2061 &iCur, &iHiwtr, bReset);
2062 raw_printf(pArg->out,
2063 "Lookaside Slots Used: %d (max %d)\n",
2064 iCur, iHiwtr);
2065 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2066 &iCur, &iHiwtr, bReset);
2067 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2068 iHiwtr);
2069 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2070 &iCur, &iHiwtr, bReset);
2071 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2072 iHiwtr);
2073 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2074 &iCur, &iHiwtr, bReset);
2075 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2076 iHiwtr);
2077 }
2078 iHiwtr = iCur = -1;
2079 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2080 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2081 iCur);
2082 iHiwtr = iCur = -1;
2083 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2084 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2085 iHiwtr = iCur = -1;
2086 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2087 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2088 iHiwtr = iCur = -1;
2089 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2090 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2091 iHiwtr = iCur = -1;
2092 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2093 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2094 iCur);
2095 iHiwtr = iCur = -1;
2096 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2097 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2098 iCur);
2099 }
2100
2101 if( pArg && pArg->out && db && pArg->pStmt ){
2102 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2103 bReset);
2104 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2105 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2106 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2107 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2108 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2109 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2110 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2111 }
2112
2113#ifdef __linux__
2114 displayLinuxIoStats(pArg->out);
2115#endif
2116
2117 /* Do not remove this machine readable comment: extra-stats-output-here */
2118
2119 return 0;
2120}
2121
2122/*
2123** Display scan stats.
2124*/
2125static void display_scanstats(
2126 sqlite3 *db, /* Database to query */
2127 ShellState *pArg /* Pointer to ShellState */
2128){
2129#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2130 UNUSED_PARAMETER(db);
2131 UNUSED_PARAMETER(pArg);
2132#else
2133 int i, k, n, mx;
2134 raw_printf(pArg->out, "-------- scanstats --------\n");
2135 mx = 0;
2136 for(k=0; k<=mx; k++){
2137 double rEstLoop = 1.0;
2138 for(i=n=0; 1; i++){
2139 sqlite3_stmt *p = pArg->pStmt;
2140 sqlite3_int64 nLoop, nVisit;
2141 double rEst;
2142 int iSid;
2143 const char *zExplain;
2144 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2145 break;
2146 }
2147 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2148 if( iSid>mx ) mx = iSid;
2149 if( iSid!=k ) continue;
2150 if( n==0 ){
2151 rEstLoop = (double)nLoop;
2152 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2153 }
2154 n++;
2155 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2156 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2157 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2158 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2159 rEstLoop *= rEst;
2160 raw_printf(pArg->out,
2161 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2162 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2163 );
2164 }
2165 }
2166 raw_printf(pArg->out, "---------------------------\n");
2167#endif
2168}
2169
2170/*
2171** Parameter azArray points to a zero-terminated array of strings. zStr
2172** points to a single nul-terminated string. Return non-zero if zStr
2173** is equal, according to strcmp(), to any of the strings in the array.
2174** Otherwise, return zero.
2175*/
2176static int str_in_array(const char *zStr, const char **azArray){
2177 int i;
2178 for(i=0; azArray[i]; i++){
2179 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2180 }
2181 return 0;
2182}
2183
2184/*
2185** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2186** and populate the ShellState.aiIndent[] array with the number of
2187** spaces each opcode should be indented before it is output.
2188**
2189** The indenting rules are:
2190**
2191** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2192** all opcodes that occur between the p2 jump destination and the opcode
2193** itself by 2 spaces.
2194**
2195** * For each "Goto", if the jump destination is earlier in the program
2196** and ends on one of:
2197** Yield SeekGt SeekLt RowSetRead Rewind
2198** or if the P1 parameter is one instead of zero,
2199** then indent all opcodes between the earlier instruction
2200** and "Goto" by 2 spaces.
2201*/
2202static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2203 const char *zSql; /* The text of the SQL statement */
2204 const char *z; /* Used to check if this is an EXPLAIN */
2205 int *abYield = 0; /* True if op is an OP_Yield */
2206 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2207 int iOp; /* Index of operation in p->aiIndent[] */
2208
2209 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2210 "NextIfOpen", "PrevIfOpen", 0 };
2211 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2212 "Rewind", 0 };
2213 const char *azGoto[] = { "Goto", 0 };
2214
2215 /* Try to figure out if this is really an EXPLAIN statement. If this
2216 ** cannot be verified, return early. */
2217 if( sqlite3_column_count(pSql)!=8 ){
2218 p->cMode = p->mode;
2219 return;
2220 }
2221 zSql = sqlite3_sql(pSql);
2222 if( zSql==0 ) return;
2223 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2224 if( sqlite3_strnicmp(z, "explain", 7) ){
2225 p->cMode = p->mode;
2226 return;
2227 }
2228
2229 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2230 int i;
2231 int iAddr = sqlite3_column_int(pSql, 0);
2232 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2233
2234 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2235 ** p2 is an instruction address, set variable p2op to the index of that
2236 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2237 ** the current instruction is part of a sub-program generated by an
2238 ** SQL trigger or foreign key. */
2239 int p2 = sqlite3_column_int(pSql, 3);
2240 int p2op = (p2 + (iOp-iAddr));
2241
2242 /* Grow the p->aiIndent array as required */
2243 if( iOp>=nAlloc ){
2244 if( iOp==0 ){
2245 /* Do further verfication that this is explain output. Abort if
2246 ** it is not */
2247 static const char *explainCols[] = {
2248 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2249 int jj;
2250 for(jj=0; jj<ArraySize(explainCols); jj++){
2251 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2252 p->cMode = p->mode;
2253 sqlite3_reset(pSql);
2254 return;
2255 }
2256 }
2257 }
2258 nAlloc += 100;
2259 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2260 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2261 }
2262 abYield[iOp] = str_in_array(zOp, azYield);
2263 p->aiIndent[iOp] = 0;
2264 p->nIndent = iOp+1;
2265
2266 if( str_in_array(zOp, azNext) ){
2267 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2268 }
2269 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2270 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2271 ){
2272 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2273 }
2274 }
2275
2276 p->iIndent = 0;
2277 sqlite3_free(abYield);
2278 sqlite3_reset(pSql);
2279}
2280
2281/*
2282** Free the array allocated by explain_data_prepare().
2283*/
2284static void explain_data_delete(ShellState *p){
2285 sqlite3_free(p->aiIndent);
2286 p->aiIndent = 0;
2287 p->nIndent = 0;
2288 p->iIndent = 0;
2289}
2290
2291/*
2292** Disable and restore .wheretrace and .selecttrace settings.
2293*/
2294#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2295extern int sqlite3SelectTrace;
2296static int savedSelectTrace;
2297#endif
2298#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2299extern int sqlite3WhereTrace;
2300static int savedWhereTrace;
2301#endif
2302static void disable_debug_trace_modes(void){
2303#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2304 savedSelectTrace = sqlite3SelectTrace;
2305 sqlite3SelectTrace = 0;
2306#endif
2307#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2308 savedWhereTrace = sqlite3WhereTrace;
2309 sqlite3WhereTrace = 0;
2310#endif
2311}
2312static void restore_debug_trace_modes(void){
2313#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2314 sqlite3SelectTrace = savedSelectTrace;
2315#endif
2316#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2317 sqlite3WhereTrace = savedWhereTrace;
2318#endif
2319}
2320
2321/*
2322** Run a prepared statement
2323*/
2324static void exec_prepared_stmt(
2325 ShellState *pArg, /* Pointer to ShellState */
2326 sqlite3_stmt *pStmt, /* Statment to run */
2327 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2328){
2329 int rc;
2330
2331 /* perform the first step. this will tell us if we
2332 ** have a result set or not and how wide it is.
2333 */
2334 rc = sqlite3_step(pStmt);
2335 /* if we have a result set... */
2336 if( SQLITE_ROW == rc ){
2337 /* if we have a callback... */
2338 if( xCallback ){
2339 /* allocate space for col name ptr, value ptr, and type */
2340 int nCol = sqlite3_column_count(pStmt);
2341 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2342 if( !pData ){
2343 rc = SQLITE_NOMEM;
2344 }else{
2345 char **azCols = (char **)pData; /* Names of result columns */
2346 char **azVals = &azCols[nCol]; /* Results */
2347 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2348 int i, x;
2349 assert(sizeof(int) <= sizeof(char *));
2350 /* save off ptrs to column names */
2351 for(i=0; i<nCol; i++){
2352 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2353 }
2354 do{
2355 /* extract the data and data types */
2356 for(i=0; i<nCol; i++){
2357 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2358 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2359 azVals[i] = "";
2360 }else{
2361 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2362 }
2363 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2364 rc = SQLITE_NOMEM;
2365 break; /* from for */
2366 }
2367 } /* end for */
2368
2369 /* if data and types extracted successfully... */
2370 if( SQLITE_ROW == rc ){
2371 /* call the supplied callback with the result row data */
2372 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2373 rc = SQLITE_ABORT;
2374 }else{
2375 rc = sqlite3_step(pStmt);
2376 }
2377 }
2378 } while( SQLITE_ROW == rc );
2379 sqlite3_free(pData);
2380 }
2381 }else{
2382 do{
2383 rc = sqlite3_step(pStmt);
2384 } while( rc == SQLITE_ROW );
2385 }
2386 }
2387}
2388
2389/*
dan43efc182017-12-19 17:42:13 +00002390** This function is called to process SQL if the previous shell command
2391** was ".expert". It passes the SQL in the second argument directly to
2392** the sqlite3expert object.
2393**
2394** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2395** code. In this case, (*pzErr) may be set to point to a buffer containing
2396** an English language error message. It is the responsibility of the
2397** caller to eventually free this buffer using sqlite3_free().
2398*/
2399static int expertHandleSQL(
2400 ShellState *pState,
2401 const char *zSql,
2402 char **pzErr
2403){
2404 assert( pState->expert.pExpert );
2405 assert( pzErr==0 || *pzErr==0 );
2406 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2407}
2408
2409/*
2410** This function is called either to silently clean up the object
2411** created by the ".expert" command (if bCancel==1), or to generate a
2412** report from it and then clean it up (if bCancel==0).
2413**
2414** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2415** code. In this case, (*pzErr) may be set to point to a buffer containing
2416** an English language error message. It is the responsibility of the
2417** caller to eventually free this buffer using sqlite3_free().
2418*/
2419static int expertFinish(
2420 ShellState *pState,
2421 int bCancel,
2422 char **pzErr
2423){
2424 int rc = SQLITE_OK;
2425 sqlite3expert *p = pState->expert.pExpert;
2426 assert( p );
2427 assert( bCancel || pzErr==0 || *pzErr==0 );
2428 if( bCancel==0 ){
2429 FILE *out = pState->out;
2430 int bVerbose = pState->expert.bVerbose;
2431
2432 rc = sqlite3_expert_analyze(p, pzErr);
2433 if( rc==SQLITE_OK ){
2434 int nQuery = sqlite3_expert_count(p);
2435 int i;
2436
2437 if( bVerbose ){
2438 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2439 raw_printf(out, "-- Candidates -----------------------------\n");
2440 raw_printf(out, "%s\n", zCand);
2441 }
2442 for(i=0; i<nQuery; i++){
2443 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2444 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2445 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2446 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2447 if( bVerbose ){
2448 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2449 raw_printf(out, "%s\n\n", zSql);
2450 }
2451 raw_printf(out, "%s\n", zIdx);
2452 raw_printf(out, "%s\n", zEQP);
2453 }
2454 }
2455 }
2456 sqlite3_expert_destroy(p);
2457 pState->expert.pExpert = 0;
2458 return rc;
2459}
2460
2461
2462/*
drh2ce15c32017-07-11 13:34:40 +00002463** Execute a statement or set of statements. Print
2464** any result rows/columns depending on the current mode
2465** set via the supplied callback.
2466**
2467** This is very similar to SQLite's built-in sqlite3_exec()
2468** function except it takes a slightly different callback
2469** and callback data argument.
2470*/
2471static int shell_exec(
2472 sqlite3 *db, /* An open database */
2473 const char *zSql, /* SQL to be evaluated */
2474 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
2475 /* (not the same as sqlite3_exec) */
2476 ShellState *pArg, /* Pointer to ShellState */
2477 char **pzErrMsg /* Error msg written here */
2478){
2479 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2480 int rc = SQLITE_OK; /* Return Code */
2481 int rc2;
2482 const char *zLeftover; /* Tail of unprocessed SQL */
2483
2484 if( pzErrMsg ){
2485 *pzErrMsg = NULL;
2486 }
2487
dan43efc182017-12-19 17:42:13 +00002488 if( pArg->expert.pExpert ){
2489 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2490 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2491 }
2492
drh2ce15c32017-07-11 13:34:40 +00002493 while( zSql[0] && (SQLITE_OK == rc) ){
2494 static const char *zStmtSql;
2495 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2496 if( SQLITE_OK != rc ){
2497 if( pzErrMsg ){
2498 *pzErrMsg = save_err_msg(db);
2499 }
2500 }else{
2501 if( !pStmt ){
2502 /* this happens for a comment or white-space */
2503 zSql = zLeftover;
2504 while( IsSpace(zSql[0]) ) zSql++;
2505 continue;
2506 }
2507 zStmtSql = sqlite3_sql(pStmt);
2508 if( zStmtSql==0 ) zStmtSql = "";
2509 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2510
2511 /* save off the prepared statment handle and reset row count */
2512 if( pArg ){
2513 pArg->pStmt = pStmt;
2514 pArg->cnt = 0;
2515 }
2516
2517 /* echo the sql statement if echo on */
2518 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2519 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2520 }
2521
2522 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2523 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2524 sqlite3_stmt *pExplain;
2525 char *zEQP;
drhada70452017-12-21 21:02:27 +00002526 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00002527 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00002528 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2529 if( pArg->autoEQP>=AUTOEQP_trigger ){
2530 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2531 }
drh2ce15c32017-07-11 13:34:40 +00002532 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2533 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2534 if( rc==SQLITE_OK ){
2535 while( sqlite3_step(pExplain)==SQLITE_ROW ){
2536 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2537 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2538 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
2539 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2540 }
2541 }
2542 sqlite3_finalize(pExplain);
2543 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00002544 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00002545 /* Also do an EXPLAIN for ".eqp full" mode */
2546 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2547 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2548 if( rc==SQLITE_OK ){
2549 pArg->cMode = MODE_Explain;
2550 explain_data_prepare(pArg, pExplain);
2551 exec_prepared_stmt(pArg, pExplain, xCallback);
2552 explain_data_delete(pArg);
2553 }
2554 sqlite3_finalize(pExplain);
2555 sqlite3_free(zEQP);
2556 }
drhada70452017-12-21 21:02:27 +00002557 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, triggerEQP, 0);
drh2ce15c32017-07-11 13:34:40 +00002558 restore_debug_trace_modes();
2559 }
2560
2561 if( pArg ){
2562 pArg->cMode = pArg->mode;
2563 if( pArg->autoExplain
2564 && sqlite3_column_count(pStmt)==8
2565 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2566 ){
2567 pArg->cMode = MODE_Explain;
2568 }
2569
2570 /* If the shell is currently in ".explain" mode, gather the extra
2571 ** data required to add indents to the output.*/
2572 if( pArg->cMode==MODE_Explain ){
2573 explain_data_prepare(pArg, pStmt);
2574 }
2575 }
2576
2577 exec_prepared_stmt(pArg, pStmt, xCallback);
2578 explain_data_delete(pArg);
2579
2580 /* print usage stats if stats on */
2581 if( pArg && pArg->statsOn ){
2582 display_stats(db, pArg, 0);
2583 }
2584
2585 /* print loop-counters if required */
2586 if( pArg && pArg->scanstatsOn ){
2587 display_scanstats(db, pArg);
2588 }
2589
2590 /* Finalize the statement just executed. If this fails, save a
2591 ** copy of the error message. Otherwise, set zSql to point to the
2592 ** next statement to execute. */
2593 rc2 = sqlite3_finalize(pStmt);
2594 if( rc!=SQLITE_NOMEM ) rc = rc2;
2595 if( rc==SQLITE_OK ){
2596 zSql = zLeftover;
2597 while( IsSpace(zSql[0]) ) zSql++;
2598 }else if( pzErrMsg ){
2599 *pzErrMsg = save_err_msg(db);
2600 }
2601
2602 /* clear saved stmt handle */
2603 if( pArg ){
2604 pArg->pStmt = NULL;
2605 }
2606 }
2607 } /* end while */
2608
2609 return rc;
2610}
2611
2612/*
2613** Release memory previously allocated by tableColumnList().
2614*/
2615static void freeColumnList(char **azCol){
2616 int i;
2617 for(i=1; azCol[i]; i++){
2618 sqlite3_free(azCol[i]);
2619 }
2620 /* azCol[0] is a static string */
2621 sqlite3_free(azCol);
2622}
2623
2624/*
2625** Return a list of pointers to strings which are the names of all
2626** columns in table zTab. The memory to hold the names is dynamically
2627** allocated and must be released by the caller using a subsequent call
2628** to freeColumnList().
2629**
2630** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2631** value that needs to be preserved, then azCol[0] is filled in with the
2632** name of the rowid column.
2633**
2634** The first regular column in the table is azCol[1]. The list is terminated
2635** by an entry with azCol[i]==0.
2636*/
2637static char **tableColumnList(ShellState *p, const char *zTab){
2638 char **azCol = 0;
2639 sqlite3_stmt *pStmt;
2640 char *zSql;
2641 int nCol = 0;
2642 int nAlloc = 0;
2643 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2644 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
2645 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
2646 int rc;
2647
2648 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2649 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2650 sqlite3_free(zSql);
2651 if( rc ) return 0;
2652 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2653 if( nCol>=nAlloc-2 ){
2654 nAlloc = nAlloc*2 + nCol + 10;
2655 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2656 if( azCol==0 ){
2657 raw_printf(stderr, "Error: out of memory\n");
2658 exit(1);
2659 }
2660 }
2661 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2662 if( sqlite3_column_int(pStmt, 5) ){
2663 nPK++;
2664 if( nPK==1
2665 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2666 "INTEGER")==0
2667 ){
2668 isIPK = 1;
2669 }else{
2670 isIPK = 0;
2671 }
2672 }
2673 }
2674 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00002675 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002676 azCol[0] = 0;
2677 azCol[nCol+1] = 0;
2678
2679 /* The decision of whether or not a rowid really needs to be preserved
2680 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2681 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2682 ** rowids on tables where the rowid is inaccessible because there are other
2683 ** columns in the table named "rowid", "_rowid_", and "oid".
2684 */
2685 if( preserveRowid && isIPK ){
2686 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2687 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2688 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2689 ** ROWID aliases. To distinguish these cases, check to see if
2690 ** there is a "pk" entry in "PRAGMA index_list". There will be
2691 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2692 */
2693 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2694 " WHERE origin='pk'", zTab);
2695 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2696 sqlite3_free(zSql);
2697 if( rc ){
2698 freeColumnList(azCol);
2699 return 0;
2700 }
2701 rc = sqlite3_step(pStmt);
2702 sqlite3_finalize(pStmt);
2703 preserveRowid = rc==SQLITE_ROW;
2704 }
2705 if( preserveRowid ){
2706 /* Only preserve the rowid if we can find a name to use for the
2707 ** rowid */
2708 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2709 int i, j;
2710 for(j=0; j<3; j++){
2711 for(i=1; i<=nCol; i++){
2712 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2713 }
2714 if( i>nCol ){
2715 /* At this point, we know that azRowid[j] is not the name of any
2716 ** ordinary column in the table. Verify that azRowid[j] is a valid
2717 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2718 ** tables will fail this last check */
2719 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2720 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2721 break;
2722 }
2723 }
2724 }
2725 return azCol;
2726}
2727
2728/*
2729** Toggle the reverse_unordered_selects setting.
2730*/
2731static void toggleSelectOrder(sqlite3 *db){
2732 sqlite3_stmt *pStmt = 0;
2733 int iSetting = 0;
2734 char zStmt[100];
2735 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2736 if( sqlite3_step(pStmt)==SQLITE_ROW ){
2737 iSetting = sqlite3_column_int(pStmt, 0);
2738 }
2739 sqlite3_finalize(pStmt);
2740 sqlite3_snprintf(sizeof(zStmt), zStmt,
2741 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2742 sqlite3_exec(db, zStmt, 0, 0, 0);
2743}
2744
2745/*
2746** This is a different callback routine used for dumping the database.
2747** Each row received by this callback consists of a table name,
2748** the table type ("index" or "table") and SQL to create the table.
2749** This routine should print text sufficient to recreate the table.
2750*/
2751static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
2752 int rc;
2753 const char *zTable;
2754 const char *zType;
2755 const char *zSql;
2756 ShellState *p = (ShellState *)pArg;
2757
2758 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00002759 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002760 zTable = azArg[0];
2761 zType = azArg[1];
2762 zSql = azArg[2];
2763
2764 if( strcmp(zTable, "sqlite_sequence")==0 ){
2765 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
2766 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2767 raw_printf(p->out, "ANALYZE sqlite_master;\n");
2768 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2769 return 0;
2770 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2771 char *zIns;
2772 if( !p->writableSchema ){
2773 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2774 p->writableSchema = 1;
2775 }
2776 zIns = sqlite3_mprintf(
2777 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2778 "VALUES('table','%q','%q',0,'%q');",
2779 zTable, zTable, zSql);
2780 utf8_printf(p->out, "%s\n", zIns);
2781 sqlite3_free(zIns);
2782 return 0;
2783 }else{
2784 printSchemaLine(p->out, zSql, ";\n");
2785 }
2786
2787 if( strcmp(zType, "table")==0 ){
2788 ShellText sSelect;
2789 ShellText sTable;
2790 char **azCol;
2791 int i;
2792 char *savedDestTable;
2793 int savedMode;
2794
2795 azCol = tableColumnList(p, zTable);
2796 if( azCol==0 ){
2797 p->nErr++;
2798 return 0;
2799 }
2800
2801 /* Always quote the table name, even if it appears to be pure ascii,
2802 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2803 initText(&sTable);
2804 appendText(&sTable, zTable, quoteChar(zTable));
2805 /* If preserving the rowid, add a column list after the table name.
2806 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2807 ** instead of the usual "INSERT INTO tab VALUES(...)".
2808 */
2809 if( azCol[0] ){
2810 appendText(&sTable, "(", 0);
2811 appendText(&sTable, azCol[0], 0);
2812 for(i=1; azCol[i]; i++){
2813 appendText(&sTable, ",", 0);
2814 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
2815 }
2816 appendText(&sTable, ")", 0);
2817 }
2818
2819 /* Build an appropriate SELECT statement */
2820 initText(&sSelect);
2821 appendText(&sSelect, "SELECT ", 0);
2822 if( azCol[0] ){
2823 appendText(&sSelect, azCol[0], 0);
2824 appendText(&sSelect, ",", 0);
2825 }
2826 for(i=1; azCol[i]; i++){
2827 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
2828 if( azCol[i+1] ){
2829 appendText(&sSelect, ",", 0);
2830 }
2831 }
2832 freeColumnList(azCol);
2833 appendText(&sSelect, " FROM ", 0);
2834 appendText(&sSelect, zTable, quoteChar(zTable));
2835
2836 savedDestTable = p->zDestTable;
2837 savedMode = p->mode;
2838 p->zDestTable = sTable.z;
2839 p->mode = p->cMode = MODE_Insert;
2840 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2841 if( (rc&0xff)==SQLITE_CORRUPT ){
2842 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2843 toggleSelectOrder(p->db);
2844 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2845 toggleSelectOrder(p->db);
2846 }
2847 p->zDestTable = savedDestTable;
2848 p->mode = savedMode;
2849 freeText(&sTable);
2850 freeText(&sSelect);
2851 if( rc ) p->nErr++;
2852 }
2853 return 0;
2854}
2855
2856/*
2857** Run zQuery. Use dump_callback() as the callback routine so that
2858** the contents of the query are output as SQL statements.
2859**
2860** If we get a SQLITE_CORRUPT error, rerun the query after appending
2861** "ORDER BY rowid DESC" to the end.
2862*/
2863static int run_schema_dump_query(
2864 ShellState *p,
2865 const char *zQuery
2866){
2867 int rc;
2868 char *zErr = 0;
2869 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
2870 if( rc==SQLITE_CORRUPT ){
2871 char *zQ2;
2872 int len = strlen30(zQuery);
2873 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2874 if( zErr ){
2875 utf8_printf(p->out, "/****** %s ******/\n", zErr);
2876 sqlite3_free(zErr);
2877 zErr = 0;
2878 }
2879 zQ2 = malloc( len+100 );
2880 if( zQ2==0 ) return rc;
2881 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
2882 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
2883 if( rc ){
2884 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
2885 }else{
2886 rc = SQLITE_CORRUPT;
2887 }
2888 sqlite3_free(zErr);
2889 free(zQ2);
2890 }
2891 return rc;
2892}
2893
2894/*
2895** Text of a help message
2896*/
2897static char zHelp[] =
2898#ifndef SQLITE_OMIT_AUTHORIZATION
2899 ".auth ON|OFF Show authorizer callbacks\n"
2900#endif
2901 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
2902 ".bail on|off Stop after hitting an error. Default OFF\n"
2903 ".binary on|off Turn binary output on or off. Default OFF\n"
2904 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
2905 ".changes on|off Show number of rows changed by SQL\n"
2906 ".check GLOB Fail if output since .testcase does not match\n"
2907 ".clone NEWDB Clone data into NEWDB from the existing database\n"
2908 ".databases List names and files of attached databases\n"
2909 ".dbinfo ?DB? Show status information about the database\n"
2910 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
2911 " If TABLE specified, only dump tables matching\n"
2912 " LIKE pattern TABLE.\n"
2913 ".echo on|off Turn command echo on or off\n"
2914 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
2915 ".exit Exit this program\n"
dan2e1ea572017-12-21 18:55:24 +00002916 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
drh2ce15c32017-07-11 13:34:40 +00002917/* Because explain mode comes on automatically now, the ".explain" mode
2918** is removed from the help screen. It is still supported for legacy, however */
2919/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
2920 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
2921 ".headers on|off Turn display of headers on or off\n"
2922 ".help Show this message\n"
2923 ".import FILE TABLE Import data from FILE into TABLE\n"
2924#ifndef SQLITE_OMIT_TEST_CONTROL
2925 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
2926#endif
2927 ".indexes ?TABLE? Show names of all indexes\n"
2928 " If TABLE specified, only show indexes for tables\n"
2929 " matching LIKE pattern TABLE.\n"
2930#ifdef SQLITE_ENABLE_IOTRACE
2931 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
2932#endif
2933 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
2934 ".lint OPTIONS Report potential schema issues. Options:\n"
2935 " fkey-indexes Find missing foreign key indexes\n"
2936#ifndef SQLITE_OMIT_LOAD_EXTENSION
2937 ".load FILE ?ENTRY? Load an extension library\n"
2938#endif
2939 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
2940 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
2941 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
2942 " csv Comma-separated values\n"
2943 " column Left-aligned columns. (See .width)\n"
2944 " html HTML <table> code\n"
2945 " insert SQL insert statements for TABLE\n"
2946 " line One value per line\n"
2947 " list Values delimited by \"|\"\n"
2948 " quote Escape answers as for SQL\n"
2949 " tabs Tab-separated values\n"
2950 " tcl TCL list elements\n"
2951 ".nullvalue STRING Use STRING in place of NULL values\n"
2952 ".once FILENAME Output for the next SQL command only to FILENAME\n"
2953 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
2954 " The --new option starts with an empty file\n"
2955 ".output ?FILENAME? Send output to FILENAME or stdout\n"
2956 ".print STRING... Print literal STRING\n"
2957 ".prompt MAIN CONTINUE Replace the standard prompts\n"
2958 ".quit Exit this program\n"
2959 ".read FILENAME Execute SQL in FILENAME\n"
2960 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
2961 ".save FILE Write in-memory database into FILE\n"
2962 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
2963 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
2964 " Add --indent for pretty-printing\n"
2965 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
2966 ".separator COL ?ROW? Change the column separator and optionally the row\n"
2967 " separator for both the output mode and .import\n"
2968#if defined(SQLITE_ENABLE_SESSION)
2969 ".session CMD ... Create or control sessions\n"
2970#endif
2971 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
2972 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
2973 ".show Show the current values for various settings\n"
2974 ".stats ?on|off? Show stats or turn stats on or off\n"
2975 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
2976 ".tables ?TABLE? List names of tables\n"
2977 " If TABLE specified, only list tables matching\n"
2978 " LIKE pattern TABLE.\n"
2979 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
2980 ".timeout MS Try opening locked tables for MS milliseconds\n"
2981 ".timer on|off Turn SQL timer on or off\n"
2982 ".trace FILE|off Output each SQL statement as it is run\n"
2983 ".vfsinfo ?AUX? Information about the top-level VFS\n"
2984 ".vfslist List all available VFSes\n"
2985 ".vfsname ?AUX? Print the name of the VFS stack\n"
2986 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
2987 " Negative values right-justify\n"
2988;
2989
2990#if defined(SQLITE_ENABLE_SESSION)
2991/*
2992** Print help information for the ".sessions" command
2993*/
2994void session_help(ShellState *p){
2995 raw_printf(p->out,
2996 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
2997 "If ?NAME? is omitted, the first defined session is used.\n"
2998 "Subcommands:\n"
2999 " attach TABLE Attach TABLE\n"
3000 " changeset FILE Write a changeset into FILE\n"
3001 " close Close one session\n"
3002 " enable ?BOOLEAN? Set or query the enable bit\n"
3003 " filter GLOB... Reject tables matching GLOBs\n"
3004 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3005 " isempty Query whether the session is empty\n"
3006 " list List currently open session names\n"
3007 " open DB NAME Open a new session on DB\n"
3008 " patchset FILE Write a patchset into FILE\n"
3009 );
3010}
3011#endif
3012
3013
3014/* Forward reference */
3015static int process_input(ShellState *p, FILE *in);
3016
3017/*
3018** Read the content of file zName into memory obtained from sqlite3_malloc64()
3019** and return a pointer to the buffer. The caller is responsible for freeing
3020** the memory.
3021**
3022** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3023** read.
3024**
3025** For convenience, a nul-terminator byte is always appended to the data read
3026** from the file before the buffer is returned. This byte is not included in
3027** the final value of (*pnByte), if applicable.
3028**
3029** NULL is returned if any error is encountered. The final value of *pnByte
3030** is undefined in this case.
3031*/
3032static char *readFile(const char *zName, int *pnByte){
3033 FILE *in = fopen(zName, "rb");
3034 long nIn;
3035 size_t nRead;
3036 char *pBuf;
3037 if( in==0 ) return 0;
3038 fseek(in, 0, SEEK_END);
3039 nIn = ftell(in);
3040 rewind(in);
3041 pBuf = sqlite3_malloc64( nIn+1 );
3042 if( pBuf==0 ) return 0;
3043 nRead = fread(pBuf, nIn, 1, in);
3044 fclose(in);
3045 if( nRead!=1 ){
3046 sqlite3_free(pBuf);
3047 return 0;
3048 }
3049 pBuf[nIn] = 0;
3050 if( pnByte ) *pnByte = nIn;
3051 return pBuf;
3052}
3053
3054#if defined(SQLITE_ENABLE_SESSION)
3055/*
3056** Close a single OpenSession object and release all of its associated
3057** resources.
3058*/
3059static void session_close(OpenSession *pSession){
3060 int i;
3061 sqlite3session_delete(pSession->p);
3062 sqlite3_free(pSession->zName);
3063 for(i=0; i<pSession->nFilter; i++){
3064 sqlite3_free(pSession->azFilter[i]);
3065 }
3066 sqlite3_free(pSession->azFilter);
3067 memset(pSession, 0, sizeof(OpenSession));
3068}
3069#endif
3070
3071/*
3072** Close all OpenSession objects and release all associated resources.
3073*/
3074#if defined(SQLITE_ENABLE_SESSION)
3075static void session_close_all(ShellState *p){
3076 int i;
3077 for(i=0; i<p->nSession; i++){
3078 session_close(&p->aSession[i]);
3079 }
3080 p->nSession = 0;
3081}
3082#else
3083# define session_close_all(X)
3084#endif
3085
3086/*
3087** Implementation of the xFilter function for an open session. Omit
3088** any tables named by ".session filter" but let all other table through.
3089*/
3090#if defined(SQLITE_ENABLE_SESSION)
3091static int session_filter(void *pCtx, const char *zTab){
3092 OpenSession *pSession = (OpenSession*)pCtx;
3093 int i;
3094 for(i=0; i<pSession->nFilter; i++){
3095 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3096 }
3097 return 1;
3098}
3099#endif
3100
3101/*
3102** Make sure the database is open. If it is not, then open it. If
3103** the database fails to open, print an error message and exit.
3104*/
3105static void open_db(ShellState *p, int keepAlive){
3106 if( p->db==0 ){
3107 sqlite3_initialize();
3108 sqlite3_open(p->zDbFilename, &p->db);
3109 globalDb = p->db;
3110 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3111 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3112 p->zDbFilename, sqlite3_errmsg(p->db));
3113 if( keepAlive ) return;
3114 exit(1);
3115 }
3116#ifndef SQLITE_OMIT_LOAD_EXTENSION
3117 sqlite3_enable_load_extension(p->db, 1);
3118#endif
3119 sqlite3_fileio_init(p->db, 0, 0);
3120 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00003121 sqlite3_completion_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003122#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00003123 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00003124 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003125#endif
drhceba7922018-01-01 21:28:25 +00003126 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00003127 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00003128 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3129 shellModuleSchema, 0, 0);
drh2ce15c32017-07-11 13:34:40 +00003130 }
3131}
3132
drh56eb09b2017-07-11 13:59:07 +00003133#if HAVE_READLINE || HAVE_EDITLINE
3134/*
3135** Readline completion callbacks
3136*/
3137static char *readline_completion_generator(const char *text, int state){
3138 static sqlite3_stmt *pStmt = 0;
3139 char *zRet;
3140 if( state==0 ){
3141 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00003142 sqlite3_finalize(pStmt);
3143 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3144 " FROM completion(%Q) ORDER BY 1", text);
3145 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3146 sqlite3_free(zSql);
3147 }
3148 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00003149 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00003150 }else{
3151 sqlite3_finalize(pStmt);
3152 pStmt = 0;
3153 zRet = 0;
3154 }
3155 return zRet;
3156}
3157static char **readline_completion(const char *zText, int iStart, int iEnd){
3158 rl_attempted_completion_over = 1;
3159 return rl_completion_matches(zText, readline_completion_generator);
3160}
3161
3162#elif HAVE_LINENOISE
3163/*
3164** Linenoise completion callback
3165*/
3166static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00003167 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00003168 int i, iStart;
3169 sqlite3_stmt *pStmt = 0;
3170 char *zSql;
3171 char zBuf[1000];
3172
3173 if( nLine>sizeof(zBuf)-30 ) return;
3174 if( zLine[0]=='.' ) return;
3175 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
3176 if( i==nLine-1 ) return;
3177 iStart = i+1;
3178 memcpy(zBuf, zLine, iStart);
3179 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3180 " FROM completion(%Q,%Q) ORDER BY 1",
3181 &zLine[iStart], zLine);
3182 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3183 sqlite3_free(zSql);
3184 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3185 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3186 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
3187 int nCompletion = sqlite3_column_bytes(pStmt, 0);
3188 if( iStart+nCompletion < sizeof(zBuf)-1 ){
3189 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
3190 linenoiseAddCompletion(lc, zBuf);
3191 }
3192 }
3193 sqlite3_finalize(pStmt);
3194}
3195#endif
3196
drh2ce15c32017-07-11 13:34:40 +00003197/*
3198** Do C-language style dequoting.
3199**
3200** \a -> alarm
3201** \b -> backspace
3202** \t -> tab
3203** \n -> newline
3204** \v -> vertical tab
3205** \f -> form feed
3206** \r -> carriage return
3207** \s -> space
3208** \" -> "
3209** \' -> '
3210** \\ -> backslash
3211** \NNN -> ascii character NNN in octal
3212*/
3213static void resolve_backslashes(char *z){
3214 int i, j;
3215 char c;
3216 while( *z && *z!='\\' ) z++;
3217 for(i=j=0; (c = z[i])!=0; i++, j++){
3218 if( c=='\\' && z[i+1]!=0 ){
3219 c = z[++i];
3220 if( c=='a' ){
3221 c = '\a';
3222 }else if( c=='b' ){
3223 c = '\b';
3224 }else if( c=='t' ){
3225 c = '\t';
3226 }else if( c=='n' ){
3227 c = '\n';
3228 }else if( c=='v' ){
3229 c = '\v';
3230 }else if( c=='f' ){
3231 c = '\f';
3232 }else if( c=='r' ){
3233 c = '\r';
3234 }else if( c=='"' ){
3235 c = '"';
3236 }else if( c=='\'' ){
3237 c = '\'';
3238 }else if( c=='\\' ){
3239 c = '\\';
3240 }else if( c>='0' && c<='7' ){
3241 c -= '0';
3242 if( z[i+1]>='0' && z[i+1]<='7' ){
3243 i++;
3244 c = (c<<3) + z[i] - '0';
3245 if( z[i+1]>='0' && z[i+1]<='7' ){
3246 i++;
3247 c = (c<<3) + z[i] - '0';
3248 }
3249 }
3250 }
3251 }
3252 z[j] = c;
3253 }
3254 if( j<i ) z[j] = 0;
3255}
3256
3257/*
3258** Return the value of a hexadecimal digit. Return -1 if the input
3259** is not a hex digit.
3260*/
3261static int hexDigitValue(char c){
3262 if( c>='0' && c<='9' ) return c - '0';
3263 if( c>='a' && c<='f' ) return c - 'a' + 10;
3264 if( c>='A' && c<='F' ) return c - 'A' + 10;
3265 return -1;
3266}
3267
3268/*
3269** Interpret zArg as an integer value, possibly with suffixes.
3270*/
3271static sqlite3_int64 integerValue(const char *zArg){
3272 sqlite3_int64 v = 0;
3273 static const struct { char *zSuffix; int iMult; } aMult[] = {
3274 { "KiB", 1024 },
3275 { "MiB", 1024*1024 },
3276 { "GiB", 1024*1024*1024 },
3277 { "KB", 1000 },
3278 { "MB", 1000000 },
3279 { "GB", 1000000000 },
3280 { "K", 1000 },
3281 { "M", 1000000 },
3282 { "G", 1000000000 },
3283 };
3284 int i;
3285 int isNeg = 0;
3286 if( zArg[0]=='-' ){
3287 isNeg = 1;
3288 zArg++;
3289 }else if( zArg[0]=='+' ){
3290 zArg++;
3291 }
3292 if( zArg[0]=='0' && zArg[1]=='x' ){
3293 int x;
3294 zArg += 2;
3295 while( (x = hexDigitValue(zArg[0]))>=0 ){
3296 v = (v<<4) + x;
3297 zArg++;
3298 }
3299 }else{
3300 while( IsDigit(zArg[0]) ){
3301 v = v*10 + zArg[0] - '0';
3302 zArg++;
3303 }
3304 }
3305 for(i=0; i<ArraySize(aMult); i++){
3306 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3307 v *= aMult[i].iMult;
3308 break;
3309 }
3310 }
3311 return isNeg? -v : v;
3312}
3313
3314/*
3315** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3316** for TRUE and FALSE. Return the integer value if appropriate.
3317*/
3318static int booleanValue(const char *zArg){
3319 int i;
3320 if( zArg[0]=='0' && zArg[1]=='x' ){
3321 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3322 }else{
3323 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3324 }
3325 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3326 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3327 return 1;
3328 }
3329 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3330 return 0;
3331 }
3332 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3333 zArg);
3334 return 0;
3335}
3336
3337/*
3338** Set or clear a shell flag according to a boolean value.
3339*/
3340static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3341 if( booleanValue(zArg) ){
3342 ShellSetFlag(p, mFlag);
3343 }else{
3344 ShellClearFlag(p, mFlag);
3345 }
3346}
3347
3348/*
3349** Close an output file, assuming it is not stderr or stdout
3350*/
3351static void output_file_close(FILE *f){
3352 if( f && f!=stdout && f!=stderr ) fclose(f);
3353}
3354
3355/*
3356** Try to open an output file. The names "stdout" and "stderr" are
3357** recognized and do the right thing. NULL is returned if the output
3358** filename is "off".
3359*/
3360static FILE *output_file_open(const char *zFile){
3361 FILE *f;
3362 if( strcmp(zFile,"stdout")==0 ){
3363 f = stdout;
3364 }else if( strcmp(zFile, "stderr")==0 ){
3365 f = stderr;
3366 }else if( strcmp(zFile, "off")==0 ){
3367 f = 0;
3368 }else{
3369 f = fopen(zFile, "wb");
3370 if( f==0 ){
3371 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3372 }
3373 }
3374 return f;
3375}
3376
3377#if !defined(SQLITE_UNTESTABLE)
3378#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3379/*
3380** A routine for handling output from sqlite3_trace().
3381*/
3382static int sql_trace_callback(
3383 unsigned mType,
3384 void *pArg,
3385 void *pP,
3386 void *pX
3387){
3388 FILE *f = (FILE*)pArg;
3389 UNUSED_PARAMETER(mType);
3390 UNUSED_PARAMETER(pP);
3391 if( f ){
3392 const char *z = (const char*)pX;
drhaf2770f2018-01-05 14:55:43 +00003393 int i = strlen30(z);
drh2ce15c32017-07-11 13:34:40 +00003394 while( i>0 && z[i-1]==';' ){ i--; }
3395 utf8_printf(f, "%.*s;\n", i, z);
3396 }
3397 return 0;
3398}
3399#endif
3400#endif
3401
3402/*
3403** A no-op routine that runs with the ".breakpoint" doc-command. This is
3404** a useful spot to set a debugger breakpoint.
3405*/
3406static void test_breakpoint(void){
3407 static int nCall = 0;
3408 nCall++;
3409}
3410
3411/*
3412** An object used to read a CSV and other files for import.
3413*/
3414typedef struct ImportCtx ImportCtx;
3415struct ImportCtx {
3416 const char *zFile; /* Name of the input file */
3417 FILE *in; /* Read the CSV text from this input stream */
3418 char *z; /* Accumulated text for a field */
3419 int n; /* Number of bytes in z */
3420 int nAlloc; /* Space allocated for z[] */
3421 int nLine; /* Current line number */
3422 int bNotFirst; /* True if one or more bytes already read */
3423 int cTerm; /* Character that terminated the most recent field */
3424 int cColSep; /* The column separator character. (Usually ",") */
3425 int cRowSep; /* The row separator character. (Usually "\n") */
3426};
3427
3428/* Append a single byte to z[] */
3429static void import_append_char(ImportCtx *p, int c){
3430 if( p->n+1>=p->nAlloc ){
3431 p->nAlloc += p->nAlloc + 100;
3432 p->z = sqlite3_realloc64(p->z, p->nAlloc);
3433 if( p->z==0 ){
3434 raw_printf(stderr, "out of memory\n");
3435 exit(1);
3436 }
3437 }
3438 p->z[p->n++] = (char)c;
3439}
3440
3441/* Read a single field of CSV text. Compatible with rfc4180 and extended
3442** with the option of having a separator other than ",".
3443**
3444** + Input comes from p->in.
3445** + Store results in p->z of length p->n. Space to hold p->z comes
3446** from sqlite3_malloc64().
3447** + Use p->cSep as the column separator. The default is ",".
3448** + Use p->rSep as the row separator. The default is "\n".
3449** + Keep track of the line number in p->nLine.
3450** + Store the character that terminates the field in p->cTerm. Store
3451** EOF on end-of-file.
3452** + Report syntax errors on stderr
3453*/
3454static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3455 int c;
3456 int cSep = p->cColSep;
3457 int rSep = p->cRowSep;
3458 p->n = 0;
3459 c = fgetc(p->in);
3460 if( c==EOF || seenInterrupt ){
3461 p->cTerm = EOF;
3462 return 0;
3463 }
3464 if( c=='"' ){
3465 int pc, ppc;
3466 int startLine = p->nLine;
3467 int cQuote = c;
3468 pc = ppc = 0;
3469 while( 1 ){
3470 c = fgetc(p->in);
3471 if( c==rSep ) p->nLine++;
3472 if( c==cQuote ){
3473 if( pc==cQuote ){
3474 pc = 0;
3475 continue;
3476 }
3477 }
3478 if( (c==cSep && pc==cQuote)
3479 || (c==rSep && pc==cQuote)
3480 || (c==rSep && pc=='\r' && ppc==cQuote)
3481 || (c==EOF && pc==cQuote)
3482 ){
3483 do{ p->n--; }while( p->z[p->n]!=cQuote );
3484 p->cTerm = c;
3485 break;
3486 }
3487 if( pc==cQuote && c!='\r' ){
3488 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3489 p->zFile, p->nLine, cQuote);
3490 }
3491 if( c==EOF ){
3492 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3493 p->zFile, startLine, cQuote);
3494 p->cTerm = c;
3495 break;
3496 }
3497 import_append_char(p, c);
3498 ppc = pc;
3499 pc = c;
3500 }
3501 }else{
3502 /* If this is the first field being parsed and it begins with the
3503 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3504 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3505 import_append_char(p, c);
3506 c = fgetc(p->in);
3507 if( (c&0xff)==0xbb ){
3508 import_append_char(p, c);
3509 c = fgetc(p->in);
3510 if( (c&0xff)==0xbf ){
3511 p->bNotFirst = 1;
3512 p->n = 0;
3513 return csv_read_one_field(p);
3514 }
3515 }
3516 }
3517 while( c!=EOF && c!=cSep && c!=rSep ){
3518 import_append_char(p, c);
3519 c = fgetc(p->in);
3520 }
3521 if( c==rSep ){
3522 p->nLine++;
3523 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3524 }
3525 p->cTerm = c;
3526 }
3527 if( p->z ) p->z[p->n] = 0;
3528 p->bNotFirst = 1;
3529 return p->z;
3530}
3531
3532/* Read a single field of ASCII delimited text.
3533**
3534** + Input comes from p->in.
3535** + Store results in p->z of length p->n. Space to hold p->z comes
3536** from sqlite3_malloc64().
3537** + Use p->cSep as the column separator. The default is "\x1F".
3538** + Use p->rSep as the row separator. The default is "\x1E".
3539** + Keep track of the row number in p->nLine.
3540** + Store the character that terminates the field in p->cTerm. Store
3541** EOF on end-of-file.
3542** + Report syntax errors on stderr
3543*/
3544static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3545 int c;
3546 int cSep = p->cColSep;
3547 int rSep = p->cRowSep;
3548 p->n = 0;
3549 c = fgetc(p->in);
3550 if( c==EOF || seenInterrupt ){
3551 p->cTerm = EOF;
3552 return 0;
3553 }
3554 while( c!=EOF && c!=cSep && c!=rSep ){
3555 import_append_char(p, c);
3556 c = fgetc(p->in);
3557 }
3558 if( c==rSep ){
3559 p->nLine++;
3560 }
3561 p->cTerm = c;
3562 if( p->z ) p->z[p->n] = 0;
3563 return p->z;
3564}
3565
3566/*
3567** Try to transfer data for table zTable. If an error is seen while
3568** moving forward, try to go backwards. The backwards movement won't
3569** work for WITHOUT ROWID tables.
3570*/
3571static void tryToCloneData(
3572 ShellState *p,
3573 sqlite3 *newDb,
3574 const char *zTable
3575){
3576 sqlite3_stmt *pQuery = 0;
3577 sqlite3_stmt *pInsert = 0;
3578 char *zQuery = 0;
3579 char *zInsert = 0;
3580 int rc;
3581 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00003582 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00003583 int k = 0;
3584 int cnt = 0;
3585 const int spinRate = 10000;
3586
3587 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3588 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3589 if( rc ){
3590 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3591 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3592 zQuery);
3593 goto end_data_xfer;
3594 }
3595 n = sqlite3_column_count(pQuery);
3596 zInsert = sqlite3_malloc64(200 + nTable + n*3);
3597 if( zInsert==0 ){
3598 raw_printf(stderr, "out of memory\n");
3599 goto end_data_xfer;
3600 }
3601 sqlite3_snprintf(200+nTable,zInsert,
3602 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00003603 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00003604 for(j=1; j<n; j++){
3605 memcpy(zInsert+i, ",?", 2);
3606 i += 2;
3607 }
3608 memcpy(zInsert+i, ");", 3);
3609 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3610 if( rc ){
3611 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3612 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3613 zQuery);
3614 goto end_data_xfer;
3615 }
3616 for(k=0; k<2; k++){
3617 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3618 for(i=0; i<n; i++){
3619 switch( sqlite3_column_type(pQuery, i) ){
3620 case SQLITE_NULL: {
3621 sqlite3_bind_null(pInsert, i+1);
3622 break;
3623 }
3624 case SQLITE_INTEGER: {
3625 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3626 break;
3627 }
3628 case SQLITE_FLOAT: {
3629 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3630 break;
3631 }
3632 case SQLITE_TEXT: {
3633 sqlite3_bind_text(pInsert, i+1,
3634 (const char*)sqlite3_column_text(pQuery,i),
3635 -1, SQLITE_STATIC);
3636 break;
3637 }
3638 case SQLITE_BLOB: {
3639 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3640 sqlite3_column_bytes(pQuery,i),
3641 SQLITE_STATIC);
3642 break;
3643 }
3644 }
3645 } /* End for */
3646 rc = sqlite3_step(pInsert);
3647 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3648 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3649 sqlite3_errmsg(newDb));
3650 }
3651 sqlite3_reset(pInsert);
3652 cnt++;
3653 if( (cnt%spinRate)==0 ){
3654 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3655 fflush(stdout);
3656 }
3657 } /* End while */
3658 if( rc==SQLITE_DONE ) break;
3659 sqlite3_finalize(pQuery);
3660 sqlite3_free(zQuery);
3661 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3662 zTable);
3663 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3664 if( rc ){
3665 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
3666 break;
3667 }
3668 } /* End for(k=0...) */
3669
3670end_data_xfer:
3671 sqlite3_finalize(pQuery);
3672 sqlite3_finalize(pInsert);
3673 sqlite3_free(zQuery);
3674 sqlite3_free(zInsert);
3675}
3676
3677
3678/*
3679** Try to transfer all rows of the schema that match zWhere. For
3680** each row, invoke xForEach() on the object defined by that row.
3681** If an error is encountered while moving forward through the
3682** sqlite_master table, try again moving backwards.
3683*/
3684static void tryToCloneSchema(
3685 ShellState *p,
3686 sqlite3 *newDb,
3687 const char *zWhere,
3688 void (*xForEach)(ShellState*,sqlite3*,const char*)
3689){
3690 sqlite3_stmt *pQuery = 0;
3691 char *zQuery = 0;
3692 int rc;
3693 const unsigned char *zName;
3694 const unsigned char *zSql;
3695 char *zErrMsg = 0;
3696
3697 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3698 " WHERE %s", zWhere);
3699 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3700 if( rc ){
3701 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3702 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3703 zQuery);
3704 goto end_schema_xfer;
3705 }
3706 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3707 zName = sqlite3_column_text(pQuery, 0);
3708 zSql = sqlite3_column_text(pQuery, 1);
3709 printf("%s... ", zName); fflush(stdout);
3710 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3711 if( zErrMsg ){
3712 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3713 sqlite3_free(zErrMsg);
3714 zErrMsg = 0;
3715 }
3716 if( xForEach ){
3717 xForEach(p, newDb, (const char*)zName);
3718 }
3719 printf("done\n");
3720 }
3721 if( rc!=SQLITE_DONE ){
3722 sqlite3_finalize(pQuery);
3723 sqlite3_free(zQuery);
3724 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3725 " WHERE %s ORDER BY rowid DESC", zWhere);
3726 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3727 if( rc ){
3728 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3729 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3730 zQuery);
3731 goto end_schema_xfer;
3732 }
3733 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3734 zName = sqlite3_column_text(pQuery, 0);
3735 zSql = sqlite3_column_text(pQuery, 1);
3736 printf("%s... ", zName); fflush(stdout);
3737 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3738 if( zErrMsg ){
3739 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3740 sqlite3_free(zErrMsg);
3741 zErrMsg = 0;
3742 }
3743 if( xForEach ){
3744 xForEach(p, newDb, (const char*)zName);
3745 }
3746 printf("done\n");
3747 }
3748 }
3749end_schema_xfer:
3750 sqlite3_finalize(pQuery);
3751 sqlite3_free(zQuery);
3752}
3753
3754/*
3755** Open a new database file named "zNewDb". Try to recover as much information
3756** as possible out of the main database (which might be corrupt) and write it
3757** into zNewDb.
3758*/
3759static void tryToClone(ShellState *p, const char *zNewDb){
3760 int rc;
3761 sqlite3 *newDb = 0;
3762 if( access(zNewDb,0)==0 ){
3763 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
3764 return;
3765 }
3766 rc = sqlite3_open(zNewDb, &newDb);
3767 if( rc ){
3768 utf8_printf(stderr, "Cannot create output database: %s\n",
3769 sqlite3_errmsg(newDb));
3770 }else{
3771 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
3772 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
3773 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3774 tryToCloneSchema(p, newDb, "type!='table'", 0);
3775 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
3776 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3777 }
3778 sqlite3_close(newDb);
3779}
3780
3781/*
3782** Change the output file back to stdout
3783*/
3784static void output_reset(ShellState *p){
3785 if( p->outfile[0]=='|' ){
3786#ifndef SQLITE_OMIT_POPEN
3787 pclose(p->out);
3788#endif
3789 }else{
3790 output_file_close(p->out);
3791 }
3792 p->outfile[0] = 0;
3793 p->out = stdout;
3794}
3795
3796/*
3797** Run an SQL command and return the single integer result.
3798*/
3799static int db_int(ShellState *p, const char *zSql){
3800 sqlite3_stmt *pStmt;
3801 int res = 0;
3802 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3803 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3804 res = sqlite3_column_int(pStmt,0);
3805 }
3806 sqlite3_finalize(pStmt);
3807 return res;
3808}
3809
3810/*
3811** Convert a 2-byte or 4-byte big-endian integer into a native integer
3812*/
3813static unsigned int get2byteInt(unsigned char *a){
3814 return (a[0]<<8) + a[1];
3815}
3816static unsigned int get4byteInt(unsigned char *a){
3817 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
3818}
3819
3820/*
3821** Implementation of the ".info" command.
3822**
3823** Return 1 on error, 2 to exit, and 0 otherwise.
3824*/
3825static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
3826 static const struct { const char *zName; int ofst; } aField[] = {
3827 { "file change counter:", 24 },
3828 { "database page count:", 28 },
3829 { "freelist page count:", 36 },
3830 { "schema cookie:", 40 },
3831 { "schema format:", 44 },
3832 { "default cache size:", 48 },
3833 { "autovacuum top root:", 52 },
3834 { "incremental vacuum:", 64 },
3835 { "text encoding:", 56 },
3836 { "user version:", 60 },
3837 { "application id:", 68 },
3838 { "software version:", 96 },
3839 };
3840 static const struct { const char *zName; const char *zSql; } aQuery[] = {
3841 { "number of tables:",
3842 "SELECT count(*) FROM %s WHERE type='table'" },
3843 { "number of indexes:",
3844 "SELECT count(*) FROM %s WHERE type='index'" },
3845 { "number of triggers:",
3846 "SELECT count(*) FROM %s WHERE type='trigger'" },
3847 { "number of views:",
3848 "SELECT count(*) FROM %s WHERE type='view'" },
3849 { "schema size:",
3850 "SELECT total(length(sql)) FROM %s" },
3851 };
drh2ce15c32017-07-11 13:34:40 +00003852 int i;
3853 char *zSchemaTab;
3854 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00003855 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00003856 unsigned char aHdr[100];
3857 open_db(p, 0);
3858 if( p->db==0 ) return 1;
drh512e6c32017-10-11 17:51:08 +00003859 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
3860 -1, &pStmt, 0);
3861 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
3862 if( sqlite3_step(pStmt)==SQLITE_ROW
3863 && sqlite3_column_bytes(pStmt,0)>100
3864 ){
3865 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
3866 sqlite3_finalize(pStmt);
3867 }else{
drh2ce15c32017-07-11 13:34:40 +00003868 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00003869 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00003870 return 1;
3871 }
3872 i = get2byteInt(aHdr+16);
3873 if( i==1 ) i = 65536;
3874 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
3875 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
3876 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
3877 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
3878 for(i=0; i<ArraySize(aField); i++){
3879 int ofst = aField[i].ofst;
3880 unsigned int val = get4byteInt(aHdr + ofst);
3881 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
3882 switch( ofst ){
3883 case 56: {
3884 if( val==1 ) raw_printf(p->out, " (utf8)");
3885 if( val==2 ) raw_printf(p->out, " (utf16le)");
3886 if( val==3 ) raw_printf(p->out, " (utf16be)");
3887 }
3888 }
3889 raw_printf(p->out, "\n");
3890 }
3891 if( zDb==0 ){
3892 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
3893 }else if( strcmp(zDb,"temp")==0 ){
3894 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
3895 }else{
3896 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
3897 }
3898 for(i=0; i<ArraySize(aQuery); i++){
3899 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
3900 int val = db_int(p, zSql);
3901 sqlite3_free(zSql);
3902 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
3903 }
3904 sqlite3_free(zSchemaTab);
3905 return 0;
3906}
3907
3908/*
3909** Print the current sqlite3_errmsg() value to stderr and return 1.
3910*/
3911static int shellDatabaseError(sqlite3 *db){
3912 const char *zErr = sqlite3_errmsg(db);
3913 utf8_printf(stderr, "Error: %s\n", zErr);
3914 return 1;
3915}
3916
3917/*
3918** Print an out-of-memory message to stderr and return 1.
3919*/
3920static int shellNomemError(void){
3921 raw_printf(stderr, "Error: out of memory\n");
3922 return 1;
3923}
3924
3925/*
3926** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
3927** if they match and FALSE (0) if they do not match.
3928**
3929** Globbing rules:
3930**
3931** '*' Matches any sequence of zero or more characters.
3932**
3933** '?' Matches exactly one character.
3934**
3935** [...] Matches one character from the enclosed list of
3936** characters.
3937**
3938** [^...] Matches one character not in the enclosed list.
3939**
3940** '#' Matches any sequence of one or more digits with an
3941** optional + or - sign in front
3942**
3943** ' ' Any span of whitespace matches any other span of
3944** whitespace.
3945**
3946** Extra whitespace at the end of z[] is ignored.
3947*/
3948static int testcase_glob(const char *zGlob, const char *z){
3949 int c, c2;
3950 int invert;
3951 int seen;
3952
3953 while( (c = (*(zGlob++)))!=0 ){
3954 if( IsSpace(c) ){
3955 if( !IsSpace(*z) ) return 0;
3956 while( IsSpace(*zGlob) ) zGlob++;
3957 while( IsSpace(*z) ) z++;
3958 }else if( c=='*' ){
3959 while( (c=(*(zGlob++))) == '*' || c=='?' ){
3960 if( c=='?' && (*(z++))==0 ) return 0;
3961 }
3962 if( c==0 ){
3963 return 1;
3964 }else if( c=='[' ){
3965 while( *z && testcase_glob(zGlob-1,z)==0 ){
3966 z++;
3967 }
3968 return (*z)!=0;
3969 }
3970 while( (c2 = (*(z++)))!=0 ){
3971 while( c2!=c ){
3972 c2 = *(z++);
3973 if( c2==0 ) return 0;
3974 }
3975 if( testcase_glob(zGlob,z) ) return 1;
3976 }
3977 return 0;
3978 }else if( c=='?' ){
3979 if( (*(z++))==0 ) return 0;
3980 }else if( c=='[' ){
3981 int prior_c = 0;
3982 seen = 0;
3983 invert = 0;
3984 c = *(z++);
3985 if( c==0 ) return 0;
3986 c2 = *(zGlob++);
3987 if( c2=='^' ){
3988 invert = 1;
3989 c2 = *(zGlob++);
3990 }
3991 if( c2==']' ){
3992 if( c==']' ) seen = 1;
3993 c2 = *(zGlob++);
3994 }
3995 while( c2 && c2!=']' ){
3996 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
3997 c2 = *(zGlob++);
3998 if( c>=prior_c && c<=c2 ) seen = 1;
3999 prior_c = 0;
4000 }else{
4001 if( c==c2 ){
4002 seen = 1;
4003 }
4004 prior_c = c2;
4005 }
4006 c2 = *(zGlob++);
4007 }
4008 if( c2==0 || (seen ^ invert)==0 ) return 0;
4009 }else if( c=='#' ){
4010 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4011 if( !IsDigit(z[0]) ) return 0;
4012 z++;
4013 while( IsDigit(z[0]) ){ z++; }
4014 }else{
4015 if( c!=(*(z++)) ) return 0;
4016 }
4017 }
4018 while( IsSpace(*z) ){ z++; }
4019 return *z==0;
4020}
4021
4022
4023/*
4024** Compare the string as a command-line option with either one or two
4025** initial "-" characters.
4026*/
4027static int optionMatch(const char *zStr, const char *zOpt){
4028 if( zStr[0]!='-' ) return 0;
4029 zStr++;
4030 if( zStr[0]=='-' ) zStr++;
4031 return strcmp(zStr, zOpt)==0;
4032}
4033
4034/*
4035** Delete a file.
4036*/
4037int shellDeleteFile(const char *zFilename){
4038 int rc;
4039#ifdef _WIN32
4040 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4041 rc = _wunlink(z);
4042 sqlite3_free(z);
4043#else
4044 rc = unlink(zFilename);
4045#endif
4046 return rc;
4047}
4048
4049
4050/*
4051** The implementation of SQL scalar function fkey_collate_clause(), used
4052** by the ".lint fkey-indexes" command. This scalar function is always
4053** called with four arguments - the parent table name, the parent column name,
4054** the child table name and the child column name.
4055**
4056** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4057**
4058** If either of the named tables or columns do not exist, this function
4059** returns an empty string. An empty string is also returned if both tables
4060** and columns exist but have the same default collation sequence. Or,
4061** if both exist but the default collation sequences are different, this
4062** function returns the string " COLLATE <parent-collation>", where
4063** <parent-collation> is the default collation sequence of the parent column.
4064*/
4065static void shellFkeyCollateClause(
4066 sqlite3_context *pCtx,
4067 int nVal,
4068 sqlite3_value **apVal
4069){
4070 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4071 const char *zParent;
4072 const char *zParentCol;
4073 const char *zParentSeq;
4074 const char *zChild;
4075 const char *zChildCol;
4076 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4077 int rc;
4078
4079 assert( nVal==4 );
4080 zParent = (const char*)sqlite3_value_text(apVal[0]);
4081 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4082 zChild = (const char*)sqlite3_value_text(apVal[2]);
4083 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4084
4085 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4086 rc = sqlite3_table_column_metadata(
4087 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4088 );
4089 if( rc==SQLITE_OK ){
4090 rc = sqlite3_table_column_metadata(
4091 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4092 );
4093 }
4094
4095 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4096 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4097 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4098 sqlite3_free(z);
4099 }
4100}
4101
4102
4103/*
4104** The implementation of dot-command ".lint fkey-indexes".
4105*/
4106static int lintFkeyIndexes(
4107 ShellState *pState, /* Current shell tool state */
4108 char **azArg, /* Array of arguments passed to dot command */
4109 int nArg /* Number of entries in azArg[] */
4110){
4111 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4112 FILE *out = pState->out; /* Stream to write non-error output to */
4113 int bVerbose = 0; /* If -verbose is present */
4114 int bGroupByParent = 0; /* If -groupbyparent is present */
4115 int i; /* To iterate through azArg[] */
4116 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4117 int rc; /* Return code */
4118 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4119
4120 /*
4121 ** This SELECT statement returns one row for each foreign key constraint
4122 ** in the schema of the main database. The column values are:
4123 **
4124 ** 0. The text of an SQL statement similar to:
4125 **
danf9679312017-12-01 18:40:18 +00004126 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00004127 **
danf9679312017-12-01 18:40:18 +00004128 ** This SELECT is similar to the one that the foreign keys implementation
4129 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00004130 ** be used to optimize this query, then it can also be used by the FK
4131 ** implementation to optimize DELETE or UPDATE statements on the parent
4132 ** table.
4133 **
4134 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4135 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4136 ** contains an index that can be used to optimize the query.
4137 **
4138 ** 2. Human readable text that describes the child table and columns. e.g.
4139 **
4140 ** "child_table(child_key1, child_key2)"
4141 **
4142 ** 3. Human readable text that describes the parent table and columns. e.g.
4143 **
4144 ** "parent_table(parent_key1, parent_key2)"
4145 **
4146 ** 4. A full CREATE INDEX statement for an index that could be used to
4147 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4148 **
4149 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4150 **
4151 ** 5. The name of the parent table.
4152 **
4153 ** These six values are used by the C logic below to generate the report.
4154 */
4155 const char *zSql =
4156 "SELECT "
danf9679312017-12-01 18:40:18 +00004157 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00004158 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4159 " || fkey_collate_clause("
4160 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4161 ", "
4162 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4163 " || group_concat('*=?', ' AND ') || ')'"
4164 ", "
4165 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4166 ", "
4167 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4168 ", "
4169 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4170 " || ' ON ' || quote(s.name) || '('"
4171 " || group_concat(quote(f.[from]) ||"
4172 " fkey_collate_clause("
4173 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4174 " || ');'"
4175 ", "
4176 " f.[table] "
4177 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4178 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4179 "GROUP BY s.name, f.id "
4180 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4181 ;
4182 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4183
4184 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00004185 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00004186 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4187 bVerbose = 1;
4188 }
4189 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4190 bGroupByParent = 1;
4191 zIndent = " ";
4192 }
4193 else{
4194 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4195 azArg[0], azArg[1]
4196 );
4197 return SQLITE_ERROR;
4198 }
4199 }
4200
4201 /* Register the fkey_collate_clause() SQL function */
4202 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4203 0, shellFkeyCollateClause, 0, 0
4204 );
4205
4206
4207 if( rc==SQLITE_OK ){
4208 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4209 }
4210 if( rc==SQLITE_OK ){
4211 sqlite3_bind_int(pSql, 1, bGroupByParent);
4212 }
4213
4214 if( rc==SQLITE_OK ){
4215 int rc2;
4216 char *zPrev = 0;
4217 while( SQLITE_ROW==sqlite3_step(pSql) ){
4218 int res = -1;
4219 sqlite3_stmt *pExplain = 0;
4220 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4221 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4222 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4223 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4224 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4225 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4226
4227 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4228 if( rc!=SQLITE_OK ) break;
4229 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4230 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4231 res = (
4232 0==sqlite3_strglob(zGlob, zPlan)
4233 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4234 );
4235 }
4236 rc = sqlite3_finalize(pExplain);
4237 if( rc!=SQLITE_OK ) break;
4238
4239 if( res<0 ){
4240 raw_printf(stderr, "Error: internal error");
4241 break;
4242 }else{
4243 if( bGroupByParent
4244 && (bVerbose || res==0)
4245 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4246 ){
4247 raw_printf(out, "-- Parent table %s\n", zParent);
4248 sqlite3_free(zPrev);
4249 zPrev = sqlite3_mprintf("%s", zParent);
4250 }
4251
4252 if( res==0 ){
4253 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4254 }else if( bVerbose ){
4255 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4256 zIndent, zFrom, zTarget
4257 );
4258 }
4259 }
4260 }
4261 sqlite3_free(zPrev);
4262
4263 if( rc!=SQLITE_OK ){
4264 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4265 }
4266
4267 rc2 = sqlite3_finalize(pSql);
4268 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4269 rc = rc2;
4270 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4271 }
4272 }else{
4273 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4274 }
4275
4276 return rc;
4277}
4278
4279/*
4280** Implementation of ".lint" dot command.
4281*/
4282static int lintDotCommand(
4283 ShellState *pState, /* Current shell tool state */
4284 char **azArg, /* Array of arguments passed to dot command */
4285 int nArg /* Number of entries in azArg[] */
4286){
4287 int n;
drhaf2770f2018-01-05 14:55:43 +00004288 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00004289 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4290 return lintFkeyIndexes(pState, azArg, nArg);
4291
4292 usage:
4293 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4294 raw_printf(stderr, "Where sub-commands are:\n");
4295 raw_printf(stderr, " fkey-indexes\n");
4296 return SQLITE_ERROR;
4297}
4298
danfd0245d2017-12-07 15:44:29 +00004299static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00004300 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00004301 int *pRc,
4302 const char *zSql,
4303 sqlite3_stmt **ppStmt
4304){
4305 *ppStmt = 0;
4306 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004307 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00004308 if( rc!=SQLITE_OK ){
4309 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00004310 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00004311 );
4312 *pRc = rc;
4313 }
4314 }
4315}
4316
danac15e2d2017-12-14 19:15:07 +00004317static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00004318 sqlite3 *db,
4319 int *pRc,
danac15e2d2017-12-14 19:15:07 +00004320 sqlite3_stmt **ppStmt,
4321 const char *zFmt,
4322 ...
dan3f67ddf2017-12-13 20:04:53 +00004323){
danac15e2d2017-12-14 19:15:07 +00004324 *ppStmt = 0;
4325 if( *pRc==SQLITE_OK ){
4326 va_list ap;
4327 char *z;
4328 va_start(ap, zFmt);
4329 z = sqlite3_vmprintf(zFmt, ap);
dan3f67ddf2017-12-13 20:04:53 +00004330 if( z==0 ){
4331 *pRc = SQLITE_NOMEM;
4332 }else{
4333 shellPrepare(db, pRc, z, ppStmt);
4334 sqlite3_free(z);
4335 }
dan3f67ddf2017-12-13 20:04:53 +00004336 }
4337}
4338
danfd0245d2017-12-07 15:44:29 +00004339static void shellFinalize(
4340 int *pRc,
4341 sqlite3_stmt *pStmt
4342){
dan25c12182017-12-07 21:03:33 +00004343 if( pStmt ){
4344 sqlite3 *db = sqlite3_db_handle(pStmt);
4345 int rc = sqlite3_finalize(pStmt);
4346 if( *pRc==SQLITE_OK ){
4347 if( rc!=SQLITE_OK ){
4348 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4349 }
4350 *pRc = rc;
4351 }
4352 }
danfd0245d2017-12-07 15:44:29 +00004353}
4354
4355static void shellReset(
4356 int *pRc,
4357 sqlite3_stmt *pStmt
4358){
4359 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00004360 if( *pRc==SQLITE_OK ){
4361 if( rc!=SQLITE_OK ){
4362 sqlite3 *db = sqlite3_db_handle(pStmt);
4363 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4364 }
4365 *pRc = rc;
4366 }
danfd0245d2017-12-07 15:44:29 +00004367}
4368
dan88be0202017-12-09 17:58:02 +00004369/*
4370** Structure representing a single ".ar" command.
4371*/
4372typedef struct ArCommand ArCommand;
4373struct ArCommand {
4374 int eCmd; /* An AR_CMD_* value */
4375 const char *zFile; /* --file argument, or NULL */
4376 const char *zDir; /* --directory argument, or NULL */
4377 int bVerbose; /* True if --verbose */
dan5a78b812017-12-27 18:54:11 +00004378 int bZip; /* True if --zip */
dan88be0202017-12-09 17:58:02 +00004379 int nArg; /* Number of command arguments */
4380 char **azArg; /* Array of command arguments */
4381};
4382
4383/*
4384** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4385*/
dan0d0547f2017-12-14 15:40:42 +00004386static int arUsage(FILE *f){
4387 raw_printf(f,
4388"\n"
4389"Usage: .ar [OPTION...] [FILE...]\n"
4390"The .ar command manages sqlar archives.\n"
4391"\n"
4392"Examples:\n"
4393" .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4394" .ar -tf archive.sar # List members of archive.sar\n"
4395" .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4396"\n"
4397"Each command line must feature exactly one command option:\n"
4398" -c, --create Create a new archive\n"
4399" -u, --update Update or add files to an existing archive\n"
4400" -t, --list List contents of archive\n"
4401" -x, --extract Extract files from archive\n"
4402"\n"
4403"And zero or more optional options:\n"
4404" -v, --verbose Print each filename as it is processed\n"
4405" -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
4406" -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
4407"\n"
4408"See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4409"\n"
4410);
4411 return SQLITE_ERROR;
4412}
4413
4414/*
4415** Print an error message for the .ar command to stderr and return
4416** SQLITE_ERROR.
4417*/
4418static int arErrorMsg(const char *zFmt, ...){
4419 va_list ap;
4420 char *z;
4421 va_start(ap, zFmt);
4422 z = sqlite3_vmprintf(zFmt, ap);
4423 va_end(ap);
4424 raw_printf(stderr, "Error: %s (try \".ar --help\")\n", z);
4425 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00004426 return SQLITE_ERROR;
4427}
4428
4429/*
4430** Values for ArCommand.eCmd.
4431*/
dand4b56e52017-12-12 20:04:59 +00004432#define AR_CMD_CREATE 1
4433#define AR_CMD_EXTRACT 2
4434#define AR_CMD_LIST 3
4435#define AR_CMD_UPDATE 4
dan0d0547f2017-12-14 15:40:42 +00004436#define AR_CMD_HELP 5
dand4b56e52017-12-12 20:04:59 +00004437
4438/*
4439** Other (non-command) switches.
4440*/
dan0d0547f2017-12-14 15:40:42 +00004441#define AR_SWITCH_VERBOSE 6
4442#define AR_SWITCH_FILE 7
4443#define AR_SWITCH_DIRECTORY 8
dan5a78b812017-12-27 18:54:11 +00004444#define AR_SWITCH_ZIP 9
dand4b56e52017-12-12 20:04:59 +00004445
4446static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
4447 switch( eSwitch ){
4448 case AR_CMD_CREATE:
4449 case AR_CMD_EXTRACT:
4450 case AR_CMD_LIST:
4451 case AR_CMD_UPDATE:
dan0d0547f2017-12-14 15:40:42 +00004452 case AR_CMD_HELP:
4453 if( pAr->eCmd ){
4454 return arErrorMsg("multiple command options");
4455 }
dand4b56e52017-12-12 20:04:59 +00004456 pAr->eCmd = eSwitch;
4457 break;
4458
4459 case AR_SWITCH_VERBOSE:
4460 pAr->bVerbose = 1;
4461 break;
dan5a78b812017-12-27 18:54:11 +00004462 case AR_SWITCH_ZIP:
4463 pAr->bZip = 1;
4464 break;
dand4b56e52017-12-12 20:04:59 +00004465
4466 case AR_SWITCH_FILE:
4467 pAr->zFile = zArg;
4468 break;
4469 case AR_SWITCH_DIRECTORY:
4470 pAr->zDir = zArg;
4471 break;
4472 }
4473
4474 return SQLITE_OK;
4475}
dan88be0202017-12-09 17:58:02 +00004476
4477/*
4478** Parse the command line for an ".ar" command. The results are written into
4479** structure (*pAr). SQLITE_OK is returned if the command line is parsed
4480** successfully, otherwise an error message is written to stderr and
4481** SQLITE_ERROR returned.
4482*/
4483static int arParseCommand(
4484 char **azArg, /* Array of arguments passed to dot command */
4485 int nArg, /* Number of entries in azArg[] */
4486 ArCommand *pAr /* Populate this object */
4487){
dand4b56e52017-12-12 20:04:59 +00004488 struct ArSwitch {
4489 char cShort;
4490 const char *zLong;
4491 int eSwitch;
4492 int bArg;
4493 } aSwitch[] = {
4494 { 'c', "create", AR_CMD_CREATE, 0 },
4495 { 'x', "extract", AR_CMD_EXTRACT, 0 },
4496 { 't', "list", AR_CMD_LIST, 0 },
4497 { 'u', "update", AR_CMD_UPDATE, 0 },
dan0d0547f2017-12-14 15:40:42 +00004498 { 'h', "help", AR_CMD_HELP, 0 },
dand4b56e52017-12-12 20:04:59 +00004499 { 'v', "verbose", AR_SWITCH_VERBOSE, 0 },
4500 { 'f', "file", AR_SWITCH_FILE, 1 },
dan5a78b812017-12-27 18:54:11 +00004501 { 'C', "directory", AR_SWITCH_DIRECTORY, 1 },
4502 { 'z', "zip", AR_SWITCH_ZIP, 0 }
dand4b56e52017-12-12 20:04:59 +00004503 };
4504 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
4505 struct ArSwitch *pEnd = &aSwitch[nSwitch];
4506
dan88be0202017-12-09 17:58:02 +00004507 if( nArg<=1 ){
dan0d0547f2017-12-14 15:40:42 +00004508 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00004509 }else{
4510 char *z = azArg[1];
4511 memset(pAr, 0, sizeof(ArCommand));
4512
4513 if( z[0]!='-' ){
4514 /* Traditional style [tar] invocation */
4515 int i;
4516 int iArg = 2;
4517 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00004518 const char *zArg = 0;
4519 struct ArSwitch *pOpt;
4520 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4521 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00004522 }
dan0d0547f2017-12-14 15:40:42 +00004523 if( pOpt==pEnd ){
4524 return arErrorMsg("unrecognized option: %c", z[i]);
4525 }
dand4b56e52017-12-12 20:04:59 +00004526 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00004527 if( iArg>=nArg ){
4528 return arErrorMsg("option requires an argument: %c",z[i]);
4529 }
dand4b56e52017-12-12 20:04:59 +00004530 zArg = azArg[iArg++];
4531 }
4532 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00004533 }
dan88be0202017-12-09 17:58:02 +00004534 pAr->nArg = nArg-iArg;
4535 if( pAr->nArg>0 ){
4536 pAr->azArg = &azArg[iArg];
4537 }
dand4b56e52017-12-12 20:04:59 +00004538 }else{
4539 /* Non-traditional invocation */
4540 int iArg;
4541 for(iArg=1; iArg<nArg; iArg++){
4542 int n;
4543 z = azArg[iArg];
4544 if( z[0]!='-' ){
4545 /* All remaining command line words are command arguments. */
4546 pAr->azArg = &azArg[iArg];
4547 pAr->nArg = nArg-iArg;
4548 break;
4549 }
drhaf2770f2018-01-05 14:55:43 +00004550 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00004551
4552 if( z[1]!='-' ){
4553 int i;
4554 /* One or more short options */
4555 for(i=1; i<n; i++){
4556 const char *zArg = 0;
4557 struct ArSwitch *pOpt;
4558 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4559 if( z[i]==pOpt->cShort ) break;
4560 }
dan0d0547f2017-12-14 15:40:42 +00004561 if( pOpt==pEnd ){
4562 return arErrorMsg("unrecognized option: %c\n", z[i]);
4563 }
dand4b56e52017-12-12 20:04:59 +00004564 if( pOpt->bArg ){
4565 if( i<(n-1) ){
4566 zArg = &z[i+1];
4567 i = n;
4568 }else{
dan0d0547f2017-12-14 15:40:42 +00004569 if( iArg>=(nArg-1) ){
4570 return arErrorMsg("option requires an argument: %c\n",z[i]);
4571 }
dand4b56e52017-12-12 20:04:59 +00004572 zArg = azArg[++iArg];
4573 }
4574 }
4575 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
4576 }
4577 }else if( z[2]=='\0' ){
4578 /* A -- option, indicating that all remaining command line words
4579 ** are command arguments. */
4580 pAr->azArg = &azArg[iArg+1];
4581 pAr->nArg = nArg-iArg-1;
4582 break;
4583 }else{
4584 /* A long option */
4585 const char *zArg = 0; /* Argument for option, if any */
4586 struct ArSwitch *pMatch = 0; /* Matching option */
4587 struct ArSwitch *pOpt; /* Iterator */
4588 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4589 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00004590 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00004591 if( pMatch ){
dan0d0547f2017-12-14 15:40:42 +00004592 return arErrorMsg("ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00004593 }else{
4594 pMatch = pOpt;
4595 }
4596 }
4597 }
4598
4599 if( pMatch==0 ){
dan0d0547f2017-12-14 15:40:42 +00004600 return arErrorMsg("unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00004601 }
4602 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00004603 if( iArg>=(nArg-1) ){
4604 return arErrorMsg("option requires an argument: %s", z);
4605 }
dand4b56e52017-12-12 20:04:59 +00004606 zArg = azArg[++iArg];
4607 }
4608 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
4609 }
4610 }
dan88be0202017-12-09 17:58:02 +00004611 }
4612 }
4613
4614 return SQLITE_OK;
4615}
4616
4617/*
dan3f67ddf2017-12-13 20:04:53 +00004618** This function assumes that all arguments within the ArCommand.azArg[]
4619** array refer to archive members, as for the --extract or --list commands.
4620** It checks that each of them are present. If any specified file is not
4621** present in the archive, an error is printed to stderr and an error
4622** code returned. Otherwise, if all specified arguments are present in
4623** the archive, SQLITE_OK is returned.
4624**
4625** This function strips any trailing '/' characters from each argument.
4626** This is consistent with the way the [tar] command seems to work on
4627** Linux.
4628*/
4629static int arCheckEntries(sqlite3 *db, ArCommand *pAr){
4630 int rc = SQLITE_OK;
4631 if( pAr->nArg ){
4632 int i;
4633 sqlite3_stmt *pTest = 0;
4634
dan5a78b812017-12-27 18:54:11 +00004635 shellPreparePrintf(db, &rc, &pTest, "SELECT name FROM %s WHERE name=?1",
4636 pAr->bZip ? "zipfile(?2)" : "sqlar"
4637 );
4638 if( rc==SQLITE_OK && pAr->bZip ){
4639 sqlite3_bind_text(pTest, 2, pAr->zFile, -1, SQLITE_TRANSIENT);
4640 }
dan3f67ddf2017-12-13 20:04:53 +00004641 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
4642 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00004643 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00004644 int bOk = 0;
4645 while( n>0 && z[n-1]=='/' ) n--;
4646 z[n] = '\0';
4647 sqlite3_bind_text(pTest, 1, z, -1, SQLITE_STATIC);
4648 if( SQLITE_ROW==sqlite3_step(pTest) ){
4649 bOk = 1;
4650 }
4651 shellReset(&rc, pTest);
4652 if( rc==SQLITE_OK && bOk==0 ){
4653 raw_printf(stderr, "not found in archive: %s\n", z);
4654 rc = SQLITE_ERROR;
4655 }
4656 }
4657 shellFinalize(&rc, pTest);
4658 }
4659
4660 return rc;
4661}
4662
4663/*
4664** Format a WHERE clause that can be used against the "sqlar" table to
4665** identify all archive members that match the command arguments held
4666** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
4667** The caller is responsible for eventually calling sqlite3_free() on
4668** any non-NULL (*pzWhere) value.
4669*/
4670static void arWhereClause(
4671 int *pRc,
4672 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00004673 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00004674){
4675 char *zWhere = 0;
4676 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00004677 if( pAr->nArg==0 ){
4678 zWhere = sqlite3_mprintf("1");
4679 }else{
4680 int i;
4681 const char *zSep = "";
4682 for(i=0; i<pAr->nArg; i++){
4683 const char *z = pAr->azArg[i];
4684 zWhere = sqlite3_mprintf(
4685 "%z%s name = '%q' OR name BETWEEN '%q/' AND '%q0'",
4686 zWhere, zSep, z, z, z
4687 );
4688 if( zWhere==0 ){
4689 *pRc = SQLITE_NOMEM;
4690 break;
4691 }
4692 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00004693 }
dan3f67ddf2017-12-13 20:04:53 +00004694 }
4695 }
4696 *pzWhere = zWhere;
4697}
4698
4699/*
danb5090e42017-12-27 21:13:21 +00004700** Argument zMode must point to a buffer at least 11 bytes in size. This
4701** function populates this buffer with the string interpretation of
4702** the unix file mode passed as the second argument (e.g. "drwxr-xr-x").
4703*/
4704static void shellModeToString(char *zMode, int mode){
4705 int i;
4706
4707 /* Magic numbers copied from [man 2 stat] */
4708 if( mode & 0040000 ){
4709 zMode[0] = 'd';
4710 }else if( (mode & 0120000)==0120000 ){
4711 zMode[0] = 'l';
4712 }else{
4713 zMode[0] = '-';
4714 }
4715
4716 for(i=0; i<3; i++){
4717 int m = (mode >> ((2-i)*3));
4718 char *a = &zMode[1 + i*3];
4719 a[0] = (m & 0x4) ? 'r' : '-';
4720 a[1] = (m & 0x2) ? 'w' : '-';
4721 a[2] = (m & 0x1) ? 'x' : '-';
4722 }
4723 zMode[10] = '\0';
4724}
4725
4726/*
dan88be0202017-12-09 17:58:02 +00004727** Implementation of .ar "lisT" command.
4728*/
dand4b56e52017-12-12 20:04:59 +00004729static int arListCommand(ShellState *p, sqlite3 *db, ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00004730 const char *zSql = "SELECT %s FROM %s WHERE %s";
dan5a78b812017-12-27 18:54:11 +00004731 const char *zTbl = (pAr->bZip ? "zipfile(?)" : "sqlar");
danb5090e42017-12-27 21:13:21 +00004732 const char *azCols[] = {
4733 "name",
4734 "mode, sz, datetime(mtime, 'unixepoch'), name"
4735 };
dan5a78b812017-12-27 18:54:11 +00004736
dan3f67ddf2017-12-13 20:04:53 +00004737 char *zWhere = 0;
4738 sqlite3_stmt *pSql = 0;
4739 int rc;
4740
4741 rc = arCheckEntries(db, pAr);
4742 arWhereClause(&rc, pAr, &zWhere);
4743
danb5090e42017-12-27 21:13:21 +00004744 shellPreparePrintf(db, &rc, &pSql, zSql, azCols[pAr->bVerbose], zTbl, zWhere);
dan5a78b812017-12-27 18:54:11 +00004745 if( rc==SQLITE_OK && pAr->bZip ){
4746 sqlite3_bind_text(pSql, 1, pAr->zFile, -1, SQLITE_TRANSIENT);
4747 }
dan3f67ddf2017-12-13 20:04:53 +00004748 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
danb5090e42017-12-27 21:13:21 +00004749 if( pAr->bVerbose ){
4750 char zMode[11];
4751 shellModeToString(zMode, sqlite3_column_int(pSql, 0));
4752
4753 raw_printf(p->out, "%s % 10d %s %s\n", zMode,
4754 sqlite3_column_int(pSql, 1),
4755 sqlite3_column_text(pSql, 2),
4756 sqlite3_column_text(pSql, 3)
4757 );
4758 }else{
4759 raw_printf(p->out, "%s\n", sqlite3_column_text(pSql, 0));
4760 }
dan3f67ddf2017-12-13 20:04:53 +00004761 }
dan5a78b812017-12-27 18:54:11 +00004762
4763 shellFinalize(&rc, pSql);
dan3f67ddf2017-12-13 20:04:53 +00004764 return rc;
dan88be0202017-12-09 17:58:02 +00004765}
4766
4767
danfd0245d2017-12-07 15:44:29 +00004768/*
4769** Implementation of .ar "eXtract" command.
4770*/
dand4b56e52017-12-12 20:04:59 +00004771static int arExtractCommand(ShellState *p, sqlite3 *db, ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00004772 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00004773 "SELECT "
4774 " :1 || name, "
dan5a78b812017-12-27 18:54:11 +00004775 " writefile(?1 || name, %s, mode, mtime) "
4776 "FROM %s WHERE (%s) AND (data IS NULL OR ?2 = 0)";
4777
4778 const char *azExtraArg[] = {
4779 "sqlar_uncompress(data, sz)",
4780 "zipfile_uncompress(data, sz, method)"
4781 };
4782 const char *azSource[] = {
4783 "sqlar", "zipfile(?3)"
4784 };
4785
4786
dan25c12182017-12-07 21:03:33 +00004787
danfd0245d2017-12-07 15:44:29 +00004788 sqlite3_stmt *pSql = 0;
4789 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00004790 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00004791 char *zWhere = 0;
danac15e2d2017-12-14 19:15:07 +00004792 int i;
dan2ad09492017-12-09 18:28:22 +00004793
dan3f67ddf2017-12-13 20:04:53 +00004794 /* If arguments are specified, check that they actually exist within
4795 ** the archive before proceeding. And formulate a WHERE clause to
4796 ** match them. */
4797 rc = arCheckEntries(db, pAr);
4798 arWhereClause(&rc, pAr, &zWhere);
4799
4800 if( rc==SQLITE_OK ){
4801 if( pAr->zDir ){
4802 zDir = sqlite3_mprintf("%s/", pAr->zDir);
4803 }else{
4804 zDir = sqlite3_mprintf("");
4805 }
4806 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00004807 }
danfd0245d2017-12-07 15:44:29 +00004808
dan5a78b812017-12-27 18:54:11 +00004809 shellPreparePrintf(db, &rc, &pSql, zSql1,
4810 azExtraArg[pAr->bZip], azSource[pAr->bZip], zWhere
4811 );
4812
dan2ad09492017-12-09 18:28:22 +00004813 if( rc==SQLITE_OK ){
4814 sqlite3_bind_text(pSql, 1, zDir, -1, SQLITE_STATIC);
dan5a78b812017-12-27 18:54:11 +00004815 if( pAr->bZip ){
4816 sqlite3_bind_text(pSql, 3, pAr->zFile, -1, SQLITE_STATIC);
4817 }
dan25c12182017-12-07 21:03:33 +00004818
danac15e2d2017-12-14 19:15:07 +00004819 /* Run the SELECT statement twice. The first time, writefile() is called
4820 ** for all archive members that should be extracted. The second time,
4821 ** only for the directories. This is because the timestamps for
4822 ** extracted directories must be reset after they are populated (as
4823 ** populating them changes the timestamp). */
4824 for(i=0; i<2; i++){
4825 sqlite3_bind_int(pSql, 2, i);
4826 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
4827 if( i==0 && pAr->bVerbose ){
4828 raw_printf(p->out, "%s\n", sqlite3_column_text(pSql, 0));
4829 }
4830 }
4831 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00004832 }
danac15e2d2017-12-14 19:15:07 +00004833 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00004834 }
dan25c12182017-12-07 21:03:33 +00004835
dan2ad09492017-12-09 18:28:22 +00004836 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00004837 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00004838 return rc;
4839}
4840
dan1ad3f612017-12-11 20:22:02 +00004841
danfd0245d2017-12-07 15:44:29 +00004842/*
dan06741a32017-12-13 20:17:18 +00004843** Implementation of .ar "create" and "update" commands.
danfd0245d2017-12-07 15:44:29 +00004844**
4845** Create the "sqlar" table in the database if it does not already exist.
4846** Then add each file in the azFile[] array to the archive. Directories
4847** are added recursively. If argument bVerbose is non-zero, a message is
4848** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00004849**
4850** The create command is the same as update, except that it drops
4851** any existing "sqlar" table before beginning.
danfd0245d2017-12-07 15:44:29 +00004852*/
dan06741a32017-12-13 20:17:18 +00004853static int arCreateUpdate(
danfd0245d2017-12-07 15:44:29 +00004854 ShellState *p, /* Shell state pointer */
dand4b56e52017-12-12 20:04:59 +00004855 sqlite3 *db,
dan06741a32017-12-13 20:17:18 +00004856 ArCommand *pAr, /* Command arguments and options */
4857 int bUpdate
danfd0245d2017-12-07 15:44:29 +00004858){
dand4b56e52017-12-12 20:04:59 +00004859 const char *zSql = "SELECT name, mode, mtime, data FROM fsdir(?, ?)";
4860 const char *zCreate =
danfd0245d2017-12-07 15:44:29 +00004861 "CREATE TABLE IF NOT EXISTS sqlar("
4862 "name TEXT PRIMARY KEY, -- name of the file\n"
4863 "mode INT, -- access permissions\n"
4864 "mtime INT, -- last modification time\n"
4865 "sz INT, -- original file size\n"
4866 "data BLOB -- compressed content\n"
dand4b56e52017-12-12 20:04:59 +00004867 ")";
4868 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
dand1b51d42017-12-16 19:11:26 +00004869 const char *zInsert = "REPLACE INTO sqlar VALUES(?,?,?,?,sqlar_compress(?))";
danfd0245d2017-12-07 15:44:29 +00004870
4871 sqlite3_stmt *pStmt = 0; /* Directory traverser */
4872 sqlite3_stmt *pInsert = 0; /* Compilation of zInsert */
4873 int i; /* For iterating through azFile[] */
4874 int rc; /* Return code */
4875
dan5a78b812017-12-27 18:54:11 +00004876 assert( pAr->bZip==0 );
4877
dand4b56e52017-12-12 20:04:59 +00004878 rc = sqlite3_exec(db, "SAVEPOINT ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00004879 if( rc!=SQLITE_OK ) return rc;
4880
dan06741a32017-12-13 20:17:18 +00004881 if( bUpdate==0 ){
4882 rc = sqlite3_exec(db, zDrop, 0, 0, 0);
4883 if( rc!=SQLITE_OK ) return rc;
4884 }
dand4b56e52017-12-12 20:04:59 +00004885
4886 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
4887 shellPrepare(db, &rc, zInsert, &pInsert);
4888 shellPrepare(db, &rc, zSql, &pStmt);
dan1ad3f612017-12-11 20:22:02 +00004889 sqlite3_bind_text(pStmt, 2, pAr->zDir, -1, SQLITE_STATIC);
danfd0245d2017-12-07 15:44:29 +00004890
dan88be0202017-12-09 17:58:02 +00004891 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
4892 sqlite3_bind_text(pStmt, 1, pAr->azArg[i], -1, SQLITE_STATIC);
danfd0245d2017-12-07 15:44:29 +00004893 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
4894 int sz;
4895 const char *zName = (const char*)sqlite3_column_text(pStmt, 0);
4896 int mode = sqlite3_column_int(pStmt, 1);
4897 unsigned int mtime = sqlite3_column_int(pStmt, 2);
4898
dan88be0202017-12-09 17:58:02 +00004899 if( pAr->bVerbose ){
dan0d0547f2017-12-14 15:40:42 +00004900 raw_printf(p->out, "%s\n", zName);
danfd0245d2017-12-07 15:44:29 +00004901 }
4902
4903 sqlite3_bind_text(pInsert, 1, zName, -1, SQLITE_STATIC);
4904 sqlite3_bind_int(pInsert, 2, mode);
4905 sqlite3_bind_int64(pInsert, 3, (sqlite3_int64)mtime);
4906
4907 if( S_ISDIR(mode) ){
4908 sz = 0;
4909 sqlite3_bind_null(pInsert, 5);
danfd0245d2017-12-07 15:44:29 +00004910 }else{
dand1b51d42017-12-16 19:11:26 +00004911 sqlite3_bind_value(pInsert, 5, sqlite3_column_value(pStmt, 3));
4912 if( S_ISLNK(mode) ){
4913 sz = -1;
danfd0245d2017-12-07 15:44:29 +00004914 }else{
dand1b51d42017-12-16 19:11:26 +00004915 sz = sqlite3_column_bytes(pStmt, 3);
danfd0245d2017-12-07 15:44:29 +00004916 }
4917 }
4918
dand1b51d42017-12-16 19:11:26 +00004919 sqlite3_bind_int(pInsert, 4, sz);
4920 sqlite3_step(pInsert);
4921 rc = sqlite3_reset(pInsert);
danfd0245d2017-12-07 15:44:29 +00004922 }
4923 shellReset(&rc, pStmt);
4924 }
4925
4926 if( rc!=SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004927 sqlite3_exec(db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00004928 }else{
dand4b56e52017-12-12 20:04:59 +00004929 rc = sqlite3_exec(db, "RELEASE ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00004930 }
4931 shellFinalize(&rc, pStmt);
4932 shellFinalize(&rc, pInsert);
danfd0245d2017-12-07 15:44:29 +00004933 return rc;
4934}
4935
4936/*
dan06741a32017-12-13 20:17:18 +00004937** Implementation of .ar "Create" command.
4938**
4939** Create the "sqlar" table in the database if it does not already exist.
4940** Then add each file in the azFile[] array to the archive. Directories
4941** are added recursively. If argument bVerbose is non-zero, a message is
4942** printed on stdout for each file archived.
4943*/
4944static int arCreateCommand(
4945 ShellState *p, /* Shell state pointer */
4946 sqlite3 *db,
4947 ArCommand *pAr /* Command arguments and options */
4948){
4949 return arCreateUpdate(p, db, pAr, 0);
4950}
4951
4952/*
4953** Implementation of .ar "Update" command.
4954*/
4955static int arUpdateCmd(ShellState *p, sqlite3 *db, ArCommand *pAr){
4956 return arCreateUpdate(p, db, pAr, 1);
4957}
4958
4959
4960/*
danfd0245d2017-12-07 15:44:29 +00004961** Implementation of ".ar" dot command.
4962*/
4963static int arDotCommand(
4964 ShellState *pState, /* Current shell tool state */
4965 char **azArg, /* Array of arguments passed to dot command */
4966 int nArg /* Number of entries in azArg[] */
4967){
dan88be0202017-12-09 17:58:02 +00004968 ArCommand cmd;
4969 int rc;
4970 rc = arParseCommand(azArg, nArg, &cmd);
4971 if( rc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004972 sqlite3 *db = 0; /* Database handle to use as archive */
4973
dan5a78b812017-12-27 18:54:11 +00004974 if( cmd.bZip ){
4975 if( cmd.zFile==0 ){
4976 raw_printf(stderr, "zip format requires a --file switch\n");
4977 return SQLITE_ERROR;
4978 }else
4979 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
4980 raw_printf(stderr, "zip archives are read-only\n");
4981 return SQLITE_ERROR;
4982 }
4983 db = pState->db;
4984 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00004985 int flags;
4986 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
4987 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
4988 }else{
4989 flags = SQLITE_OPEN_READONLY;
4990 }
4991 rc = sqlite3_open_v2(cmd.zFile, &db, flags, 0);
4992 if( rc!=SQLITE_OK ){
4993 raw_printf(stderr, "cannot open file: %s (%s)\n",
4994 cmd.zFile, sqlite3_errmsg(db)
4995 );
4996 sqlite3_close(db);
4997 return rc;
4998 }
danece4b0c2017-12-12 20:28:36 +00004999 sqlite3_fileio_init(db, 0, 0);
mistachkin3acaf4c2018-01-05 00:53:03 +00005000#ifdef SQLITE_HAVE_ZLIB
dand1b51d42017-12-16 19:11:26 +00005001 sqlite3_sqlar_init(db, 0, 0);
mistachkin3acaf4c2018-01-05 00:53:03 +00005002#endif
dand4b56e52017-12-12 20:04:59 +00005003 }else{
5004 db = pState->db;
5005 }
5006
dan88be0202017-12-09 17:58:02 +00005007 switch( cmd.eCmd ){
5008 case AR_CMD_CREATE:
dand4b56e52017-12-12 20:04:59 +00005009 rc = arCreateCommand(pState, db, &cmd);
dan88be0202017-12-09 17:58:02 +00005010 break;
danfd0245d2017-12-07 15:44:29 +00005011
dan88be0202017-12-09 17:58:02 +00005012 case AR_CMD_EXTRACT:
dand4b56e52017-12-12 20:04:59 +00005013 rc = arExtractCommand(pState, db, &cmd);
dan88be0202017-12-09 17:58:02 +00005014 break;
5015
5016 case AR_CMD_LIST:
dand4b56e52017-12-12 20:04:59 +00005017 rc = arListCommand(pState, db, &cmd);
dan88be0202017-12-09 17:58:02 +00005018 break;
5019
dan0d0547f2017-12-14 15:40:42 +00005020 case AR_CMD_HELP:
5021 arUsage(pState->out);
5022 break;
5023
dan88be0202017-12-09 17:58:02 +00005024 default:
5025 assert( cmd.eCmd==AR_CMD_UPDATE );
dand4b56e52017-12-12 20:04:59 +00005026 rc = arUpdateCmd(pState, db, &cmd);
dan88be0202017-12-09 17:58:02 +00005027 break;
danfd0245d2017-12-07 15:44:29 +00005028 }
dand4b56e52017-12-12 20:04:59 +00005029
5030 if( cmd.zFile ){
5031 sqlite3_close(db);
5032 }
danfd0245d2017-12-07 15:44:29 +00005033 }
5034
dan88be0202017-12-09 17:58:02 +00005035 return rc;
danfd0245d2017-12-07 15:44:29 +00005036}
5037
dan43efc182017-12-19 17:42:13 +00005038/*
5039** Implementation of ".expert" dot command.
5040*/
5041static int expertDotCommand(
5042 ShellState *pState, /* Current shell tool state */
5043 char **azArg, /* Array of arguments passed to dot command */
5044 int nArg /* Number of entries in azArg[] */
5045){
5046 int rc = SQLITE_OK;
5047 char *zErr = 0;
5048 int i;
5049 int iSample = 0;
5050
5051 assert( pState->expert.pExpert==0 );
5052 memset(&pState->expert, 0, sizeof(ExpertInfo));
5053
5054 for(i=1; rc==SQLITE_OK && i<nArg; i++){
5055 char *z = azArg[i];
5056 int n;
5057 if( z[0]=='-' && z[1]=='-' ) z++;
drhaf2770f2018-01-05 14:55:43 +00005058 n = strlen30(z);
dan43efc182017-12-19 17:42:13 +00005059 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
5060 pState->expert.bVerbose = 1;
5061 }
5062 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
5063 if( i==(nArg-1) ){
5064 raw_printf(stderr, "option requires an argument: %s\n", z);
5065 rc = SQLITE_ERROR;
5066 }else{
5067 iSample = (int)integerValue(azArg[++i]);
5068 if( iSample<0 || iSample>100 ){
5069 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
5070 rc = SQLITE_ERROR;
5071 }
5072 }
5073 }
5074 else{
5075 raw_printf(stderr, "unknown option: %s\n", z);
5076 rc = SQLITE_ERROR;
5077 }
5078 }
5079
5080 if( rc==SQLITE_OK ){
5081 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
5082 if( pState->expert.pExpert==0 ){
5083 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
5084 rc = SQLITE_ERROR;
5085 }else{
5086 sqlite3_expert_config(
5087 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
5088 );
5089 }
5090 }
5091
5092 return rc;
5093}
5094
drh2ce15c32017-07-11 13:34:40 +00005095
5096/*
5097** If an input line begins with "." then invoke this routine to
5098** process that line.
5099**
5100** Return 1 on error, 2 to exit, and 0 otherwise.
5101*/
5102static int do_meta_command(char *zLine, ShellState *p){
5103 int h = 1;
5104 int nArg = 0;
5105 int n, c;
5106 int rc = 0;
5107 char *azArg[50];
5108
dan43efc182017-12-19 17:42:13 +00005109 if( p->expert.pExpert ){
5110 expertFinish(p, 1, 0);
5111 }
5112
drh2ce15c32017-07-11 13:34:40 +00005113 /* Parse the input line into tokens.
5114 */
5115 while( zLine[h] && nArg<ArraySize(azArg) ){
5116 while( IsSpace(zLine[h]) ){ h++; }
5117 if( zLine[h]==0 ) break;
5118 if( zLine[h]=='\'' || zLine[h]=='"' ){
5119 int delim = zLine[h++];
5120 azArg[nArg++] = &zLine[h];
5121 while( zLine[h] && zLine[h]!=delim ){
5122 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5123 h++;
5124 }
5125 if( zLine[h]==delim ){
5126 zLine[h++] = 0;
5127 }
5128 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5129 }else{
5130 azArg[nArg++] = &zLine[h];
5131 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5132 if( zLine[h] ) zLine[h++] = 0;
5133 resolve_backslashes(azArg[nArg-1]);
5134 }
5135 }
5136
5137 /* Process the input line.
5138 */
5139 if( nArg==0 ) return 0; /* no tokens, no error */
5140 n = strlen30(azArg[0]);
5141 c = azArg[0][0];
5142
5143#ifndef SQLITE_OMIT_AUTHORIZATION
5144 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5145 if( nArg!=2 ){
5146 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5147 rc = 1;
5148 goto meta_command_exit;
5149 }
5150 open_db(p, 0);
5151 if( booleanValue(azArg[1]) ){
5152 sqlite3_set_authorizer(p->db, shellAuth, p);
5153 }else{
5154 sqlite3_set_authorizer(p->db, 0, 0);
5155 }
5156 }else
5157#endif
5158
danfd0245d2017-12-07 15:44:29 +00005159#ifndef SQLITE_OMIT_VIRTUALTABLE
5160 if( c=='a' && strncmp(azArg[0], "ar", n)==0 ){
5161 open_db(p, 0);
5162 rc = arDotCommand(p, azArg, nArg);
5163 }else
5164#endif
5165
drh2ce15c32017-07-11 13:34:40 +00005166 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5167 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5168 ){
5169 const char *zDestFile = 0;
5170 const char *zDb = 0;
5171 sqlite3 *pDest;
5172 sqlite3_backup *pBackup;
5173 int j;
5174 for(j=1; j<nArg; j++){
5175 const char *z = azArg[j];
5176 if( z[0]=='-' ){
5177 while( z[0]=='-' ) z++;
5178 /* No options to process at this time */
5179 {
5180 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
5181 return 1;
5182 }
5183 }else if( zDestFile==0 ){
5184 zDestFile = azArg[j];
5185 }else if( zDb==0 ){
5186 zDb = zDestFile;
5187 zDestFile = azArg[j];
5188 }else{
5189 raw_printf(stderr, "too many arguments to .backup\n");
5190 return 1;
5191 }
5192 }
5193 if( zDestFile==0 ){
5194 raw_printf(stderr, "missing FILENAME argument on .backup\n");
5195 return 1;
5196 }
5197 if( zDb==0 ) zDb = "main";
5198 rc = sqlite3_open(zDestFile, &pDest);
5199 if( rc!=SQLITE_OK ){
5200 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
5201 sqlite3_close(pDest);
5202 return 1;
5203 }
5204 open_db(p, 0);
5205 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5206 if( pBackup==0 ){
5207 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5208 sqlite3_close(pDest);
5209 return 1;
5210 }
5211 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5212 sqlite3_backup_finish(pBackup);
5213 if( rc==SQLITE_DONE ){
5214 rc = 0;
5215 }else{
5216 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5217 rc = 1;
5218 }
5219 sqlite3_close(pDest);
5220 }else
5221
5222 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5223 if( nArg==2 ){
5224 bail_on_error = booleanValue(azArg[1]);
5225 }else{
5226 raw_printf(stderr, "Usage: .bail on|off\n");
5227 rc = 1;
5228 }
5229 }else
5230
5231 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5232 if( nArg==2 ){
5233 if( booleanValue(azArg[1]) ){
5234 setBinaryMode(p->out, 1);
5235 }else{
5236 setTextMode(p->out, 1);
5237 }
5238 }else{
5239 raw_printf(stderr, "Usage: .binary on|off\n");
5240 rc = 1;
5241 }
5242 }else
5243
5244 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5245 if( nArg==2 ){
5246#if defined(_WIN32) || defined(WIN32)
5247 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5248 rc = !SetCurrentDirectoryW(z);
5249 sqlite3_free(z);
5250#else
5251 rc = chdir(azArg[1]);
5252#endif
5253 if( rc ){
5254 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5255 rc = 1;
5256 }
5257 }else{
5258 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5259 rc = 1;
5260 }
5261 }else
5262
5263 /* The undocumented ".breakpoint" command causes a call to the no-op
5264 ** routine named test_breakpoint().
5265 */
5266 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5267 test_breakpoint();
5268 }else
5269
5270 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5271 if( nArg==2 ){
5272 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
5273 }else{
5274 raw_printf(stderr, "Usage: .changes on|off\n");
5275 rc = 1;
5276 }
5277 }else
5278
5279 /* Cancel output redirection, if it is currently set (by .testcase)
5280 ** Then read the content of the testcase-out.txt file and compare against
5281 ** azArg[1]. If there are differences, report an error and exit.
5282 */
5283 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5284 char *zRes = 0;
5285 output_reset(p);
5286 if( nArg!=2 ){
5287 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
5288 rc = 2;
5289 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
5290 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5291 rc = 2;
5292 }else if( testcase_glob(azArg[1],zRes)==0 ){
5293 utf8_printf(stderr,
5294 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5295 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00005296 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00005297 }else{
5298 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
5299 p->nCheck++;
5300 }
5301 sqlite3_free(zRes);
5302 }else
5303
5304 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5305 if( nArg==2 ){
5306 tryToClone(p, azArg[1]);
5307 }else{
5308 raw_printf(stderr, "Usage: .clone FILENAME\n");
5309 rc = 1;
5310 }
5311 }else
5312
5313 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
5314 ShellState data;
5315 char *zErrMsg = 0;
5316 open_db(p, 0);
5317 memcpy(&data, p, sizeof(data));
5318 data.showHeader = 0;
5319 data.cMode = data.mode = MODE_List;
5320 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
5321 data.cnt = 0;
5322 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5323 callback, &data, &zErrMsg);
5324 if( zErrMsg ){
5325 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5326 sqlite3_free(zErrMsg);
5327 rc = 1;
5328 }
5329 }else
5330
5331 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
5332 rc = shell_dbinfo_command(p, nArg, azArg);
5333 }else
5334
5335 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
5336 const char *zLike = 0;
5337 int i;
5338 int savedShowHeader = p->showHeader;
5339 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
5340 for(i=1; i<nArg; i++){
5341 if( azArg[i][0]=='-' ){
5342 const char *z = azArg[i]+1;
5343 if( z[0]=='-' ) z++;
5344 if( strcmp(z,"preserve-rowids")==0 ){
5345#ifdef SQLITE_OMIT_VIRTUALTABLE
5346 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5347 " with SQLITE_OMIT_VIRTUALTABLE\n");
5348 rc = 1;
5349 goto meta_command_exit;
5350#else
5351 ShellSetFlag(p, SHFLG_PreserveRowid);
5352#endif
5353 }else
5354 if( strcmp(z,"newlines")==0 ){
5355 ShellSetFlag(p, SHFLG_Newlines);
5356 }else
5357 {
5358 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
5359 rc = 1;
5360 goto meta_command_exit;
5361 }
5362 }else if( zLike ){
5363 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
5364 "?--newlines? ?LIKE-PATTERN?\n");
5365 rc = 1;
5366 goto meta_command_exit;
5367 }else{
5368 zLike = azArg[i];
5369 }
5370 }
5371 open_db(p, 0);
5372 /* When playing back a "dump", the content might appear in an order
5373 ** which causes immediate foreign key constraints to be violated.
5374 ** So disable foreign-key constraint enforcement to prevent problems. */
5375 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
5376 raw_printf(p->out, "BEGIN TRANSACTION;\n");
5377 p->writableSchema = 0;
5378 p->showHeader = 0;
5379 /* Set writable_schema=ON since doing so forces SQLite to initialize
5380 ** as much of the schema as it can even if the sqlite_master table is
5381 ** corrupt. */
5382 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5383 p->nErr = 0;
5384 if( zLike==0 ){
5385 run_schema_dump_query(p,
5386 "SELECT name, type, sql FROM sqlite_master "
5387 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5388 );
5389 run_schema_dump_query(p,
5390 "SELECT name, type, sql FROM sqlite_master "
5391 "WHERE name=='sqlite_sequence'"
5392 );
5393 run_table_dump_query(p,
5394 "SELECT sql FROM sqlite_master "
5395 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5396 );
5397 }else{
5398 char *zSql;
5399 zSql = sqlite3_mprintf(
5400 "SELECT name, type, sql FROM sqlite_master "
5401 "WHERE tbl_name LIKE %Q AND type=='table'"
5402 " AND sql NOT NULL", zLike);
5403 run_schema_dump_query(p,zSql);
5404 sqlite3_free(zSql);
5405 zSql = sqlite3_mprintf(
5406 "SELECT sql FROM sqlite_master "
5407 "WHERE sql NOT NULL"
5408 " AND type IN ('index','trigger','view')"
5409 " AND tbl_name LIKE %Q", zLike);
5410 run_table_dump_query(p, zSql, 0);
5411 sqlite3_free(zSql);
5412 }
5413 if( p->writableSchema ){
5414 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
5415 p->writableSchema = 0;
5416 }
5417 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5418 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
5419 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5420 p->showHeader = savedShowHeader;
5421 }else
5422
5423 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5424 if( nArg==2 ){
5425 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
5426 }else{
5427 raw_printf(stderr, "Usage: .echo on|off\n");
5428 rc = 1;
5429 }
5430 }else
5431
5432 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5433 if( nArg==2 ){
5434 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00005435 p->autoEQP = AUTOEQP_full;
5436 }else if( strcmp(azArg[1],"trigger")==0 ){
5437 p->autoEQP = AUTOEQP_trigger;
drh2ce15c32017-07-11 13:34:40 +00005438 }else{
5439 p->autoEQP = booleanValue(azArg[1]);
5440 }
5441 }else{
drhada70452017-12-21 21:02:27 +00005442 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00005443 rc = 1;
5444 }
5445 }else
5446
5447 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
5448 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
5449 rc = 2;
5450 }else
5451
5452 /* The ".explain" command is automatic now. It is largely pointless. It
5453 ** retained purely for backwards compatibility */
5454 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
5455 int val = 1;
5456 if( nArg>=2 ){
5457 if( strcmp(azArg[1],"auto")==0 ){
5458 val = 99;
5459 }else{
5460 val = booleanValue(azArg[1]);
5461 }
5462 }
5463 if( val==1 && p->mode!=MODE_Explain ){
5464 p->normalMode = p->mode;
5465 p->mode = MODE_Explain;
5466 p->autoExplain = 0;
5467 }else if( val==0 ){
5468 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5469 p->autoExplain = 0;
5470 }else if( val==99 ){
5471 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5472 p->autoExplain = 1;
5473 }
5474 }else
5475
dan43efc182017-12-19 17:42:13 +00005476 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
5477 open_db(p, 0);
5478 expertDotCommand(p, azArg, nArg);
5479 }else
5480
drh2ce15c32017-07-11 13:34:40 +00005481 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
5482 ShellState data;
5483 char *zErrMsg = 0;
5484 int doStats = 0;
5485 memcpy(&data, p, sizeof(data));
5486 data.showHeader = 0;
5487 data.cMode = data.mode = MODE_Semi;
5488 if( nArg==2 && optionMatch(azArg[1], "indent") ){
5489 data.cMode = data.mode = MODE_Pretty;
5490 nArg = 1;
5491 }
5492 if( nArg!=1 ){
5493 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
5494 rc = 1;
5495 goto meta_command_exit;
5496 }
5497 open_db(p, 0);
5498 rc = sqlite3_exec(p->db,
5499 "SELECT sql FROM"
5500 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5501 " FROM sqlite_master UNION ALL"
5502 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5503 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
5504 "ORDER BY rowid",
5505 callback, &data, &zErrMsg
5506 );
5507 if( rc==SQLITE_OK ){
5508 sqlite3_stmt *pStmt;
5509 rc = sqlite3_prepare_v2(p->db,
5510 "SELECT rowid FROM sqlite_master"
5511 " WHERE name GLOB 'sqlite_stat[134]'",
5512 -1, &pStmt, 0);
5513 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5514 sqlite3_finalize(pStmt);
5515 }
5516 if( doStats==0 ){
5517 raw_printf(p->out, "/* No STAT tables available */\n");
5518 }else{
5519 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5520 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5521 callback, &data, &zErrMsg);
5522 data.cMode = data.mode = MODE_Insert;
5523 data.zDestTable = "sqlite_stat1";
5524 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5525 shell_callback, &data,&zErrMsg);
5526 data.zDestTable = "sqlite_stat3";
5527 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5528 shell_callback, &data,&zErrMsg);
5529 data.zDestTable = "sqlite_stat4";
5530 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5531 shell_callback, &data, &zErrMsg);
5532 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5533 }
5534 }else
5535
5536 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5537 if( nArg==2 ){
5538 p->showHeader = booleanValue(azArg[1]);
5539 }else{
5540 raw_printf(stderr, "Usage: .headers on|off\n");
5541 rc = 1;
5542 }
5543 }else
5544
5545 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
5546 utf8_printf(p->out, "%s", zHelp);
5547 }else
5548
5549 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
5550 char *zTable; /* Insert data into this table */
5551 char *zFile; /* Name of file to extra content from */
5552 sqlite3_stmt *pStmt = NULL; /* A statement */
5553 int nCol; /* Number of columns in the table */
5554 int nByte; /* Number of bytes in an SQL string */
5555 int i, j; /* Loop counters */
5556 int needCommit; /* True to COMMIT or ROLLBACK at end */
5557 int nSep; /* Number of bytes in p->colSeparator[] */
5558 char *zSql; /* An SQL statement */
5559 ImportCtx sCtx; /* Reader context */
5560 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5561 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
5562
5563 if( nArg!=3 ){
5564 raw_printf(stderr, "Usage: .import FILE TABLE\n");
5565 goto meta_command_exit;
5566 }
5567 zFile = azArg[1];
5568 zTable = azArg[2];
5569 seenInterrupt = 0;
5570 memset(&sCtx, 0, sizeof(sCtx));
5571 open_db(p, 0);
5572 nSep = strlen30(p->colSeparator);
5573 if( nSep==0 ){
5574 raw_printf(stderr,
5575 "Error: non-null column separator required for import\n");
5576 return 1;
5577 }
5578 if( nSep>1 ){
5579 raw_printf(stderr, "Error: multi-character column separators not allowed"
5580 " for import\n");
5581 return 1;
5582 }
5583 nSep = strlen30(p->rowSeparator);
5584 if( nSep==0 ){
5585 raw_printf(stderr, "Error: non-null row separator required for import\n");
5586 return 1;
5587 }
5588 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5589 /* When importing CSV (only), if the row separator is set to the
5590 ** default output row separator, change it to the default input
5591 ** row separator. This avoids having to maintain different input
5592 ** and output row separators. */
5593 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5594 nSep = strlen30(p->rowSeparator);
5595 }
5596 if( nSep>1 ){
5597 raw_printf(stderr, "Error: multi-character row separators not allowed"
5598 " for import\n");
5599 return 1;
5600 }
5601 sCtx.zFile = zFile;
5602 sCtx.nLine = 1;
5603 if( sCtx.zFile[0]=='|' ){
5604#ifdef SQLITE_OMIT_POPEN
5605 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
5606 return 1;
5607#else
5608 sCtx.in = popen(sCtx.zFile+1, "r");
5609 sCtx.zFile = "<pipe>";
5610 xCloser = pclose;
5611#endif
5612 }else{
5613 sCtx.in = fopen(sCtx.zFile, "rb");
5614 xCloser = fclose;
5615 }
5616 if( p->mode==MODE_Ascii ){
5617 xRead = ascii_read_one_field;
5618 }else{
5619 xRead = csv_read_one_field;
5620 }
5621 if( sCtx.in==0 ){
5622 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5623 return 1;
5624 }
5625 sCtx.cColSep = p->colSeparator[0];
5626 sCtx.cRowSep = p->rowSeparator[0];
5627 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
5628 if( zSql==0 ){
5629 raw_printf(stderr, "Error: out of memory\n");
5630 xCloser(sCtx.in);
5631 return 1;
5632 }
5633 nByte = strlen30(zSql);
5634 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5635 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
5636 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
5637 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5638 char cSep = '(';
5639 while( xRead(&sCtx) ){
5640 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
5641 cSep = ',';
5642 if( sCtx.cTerm!=sCtx.cColSep ) break;
5643 }
5644 if( cSep=='(' ){
5645 sqlite3_free(zCreate);
5646 sqlite3_free(sCtx.z);
5647 xCloser(sCtx.in);
5648 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
5649 return 1;
5650 }
5651 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5652 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5653 sqlite3_free(zCreate);
5654 if( rc ){
5655 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
5656 sqlite3_errmsg(p->db));
5657 sqlite3_free(sCtx.z);
5658 xCloser(sCtx.in);
5659 return 1;
5660 }
5661 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5662 }
5663 sqlite3_free(zSql);
5664 if( rc ){
5665 if (pStmt) sqlite3_finalize(pStmt);
5666 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
5667 xCloser(sCtx.in);
5668 return 1;
5669 }
5670 nCol = sqlite3_column_count(pStmt);
5671 sqlite3_finalize(pStmt);
5672 pStmt = 0;
5673 if( nCol==0 ) return 0; /* no columns, no error */
5674 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
5675 if( zSql==0 ){
5676 raw_printf(stderr, "Error: out of memory\n");
5677 xCloser(sCtx.in);
5678 return 1;
5679 }
5680 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
5681 j = strlen30(zSql);
5682 for(i=1; i<nCol; i++){
5683 zSql[j++] = ',';
5684 zSql[j++] = '?';
5685 }
5686 zSql[j++] = ')';
5687 zSql[j] = 0;
5688 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5689 sqlite3_free(zSql);
5690 if( rc ){
5691 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5692 if (pStmt) sqlite3_finalize(pStmt);
5693 xCloser(sCtx.in);
5694 return 1;
5695 }
5696 needCommit = sqlite3_get_autocommit(p->db);
5697 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
5698 do{
5699 int startLine = sCtx.nLine;
5700 for(i=0; i<nCol; i++){
5701 char *z = xRead(&sCtx);
5702 /*
5703 ** Did we reach end-of-file before finding any columns?
5704 ** If so, stop instead of NULL filling the remaining columns.
5705 */
5706 if( z==0 && i==0 ) break;
5707 /*
5708 ** Did we reach end-of-file OR end-of-line before finding any
5709 ** columns in ASCII mode? If so, stop instead of NULL filling
5710 ** the remaining columns.
5711 */
5712 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
5713 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
5714 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
5715 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5716 "filling the rest with NULL\n",
5717 sCtx.zFile, startLine, nCol, i+1);
5718 i += 2;
5719 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
5720 }
5721 }
5722 if( sCtx.cTerm==sCtx.cColSep ){
5723 do{
5724 xRead(&sCtx);
5725 i++;
5726 }while( sCtx.cTerm==sCtx.cColSep );
5727 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5728 "extras ignored\n",
5729 sCtx.zFile, startLine, nCol, i);
5730 }
5731 if( i>=nCol ){
5732 sqlite3_step(pStmt);
5733 rc = sqlite3_reset(pStmt);
5734 if( rc!=SQLITE_OK ){
5735 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5736 startLine, sqlite3_errmsg(p->db));
5737 }
5738 }
5739 }while( sCtx.cTerm!=EOF );
5740
5741 xCloser(sCtx.in);
5742 sqlite3_free(sCtx.z);
5743 sqlite3_finalize(pStmt);
5744 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
5745 }else
5746
5747#ifndef SQLITE_UNTESTABLE
5748 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5749 char *zSql;
5750 char *zCollist = 0;
5751 sqlite3_stmt *pStmt;
5752 int tnum = 0;
5753 int i;
5754 if( nArg!=3 ){
5755 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5756 rc = 1;
5757 goto meta_command_exit;
5758 }
5759 open_db(p, 0);
5760 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5761 " WHERE name='%q' AND type='index'", azArg[1]);
5762 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5763 sqlite3_free(zSql);
5764 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5765 tnum = sqlite3_column_int(pStmt, 0);
5766 }
5767 sqlite3_finalize(pStmt);
5768 if( tnum==0 ){
5769 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5770 rc = 1;
5771 goto meta_command_exit;
5772 }
5773 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5774 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5775 sqlite3_free(zSql);
5776 i = 0;
5777 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5778 char zLabel[20];
5779 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
5780 i++;
5781 if( zCol==0 ){
5782 if( sqlite3_column_int(pStmt,1)==-1 ){
5783 zCol = "_ROWID_";
5784 }else{
5785 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5786 zCol = zLabel;
5787 }
5788 }
5789 if( zCollist==0 ){
5790 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5791 }else{
5792 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5793 }
5794 }
5795 sqlite3_finalize(pStmt);
5796 zSql = sqlite3_mprintf(
5797 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5798 azArg[2], zCollist, zCollist);
5799 sqlite3_free(zCollist);
5800 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5801 if( rc==SQLITE_OK ){
5802 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5803 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5804 if( rc ){
5805 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5806 }else{
5807 utf8_printf(stdout, "%s;\n", zSql);
5808 raw_printf(stdout,
5809 "WARNING: writing to an imposter table will corrupt the index!\n"
5810 );
5811 }
5812 }else{
5813 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
5814 rc = 1;
5815 }
5816 sqlite3_free(zSql);
5817 }else
5818#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5819
5820#ifdef SQLITE_ENABLE_IOTRACE
5821 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
5822 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
5823 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5824 iotrace = 0;
5825 if( nArg<2 ){
5826 sqlite3IoTrace = 0;
5827 }else if( strcmp(azArg[1], "-")==0 ){
5828 sqlite3IoTrace = iotracePrintf;
5829 iotrace = stdout;
5830 }else{
5831 iotrace = fopen(azArg[1], "w");
5832 if( iotrace==0 ){
5833 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
5834 sqlite3IoTrace = 0;
5835 rc = 1;
5836 }else{
5837 sqlite3IoTrace = iotracePrintf;
5838 }
5839 }
5840 }else
5841#endif
5842
5843 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5844 static const struct {
5845 const char *zLimitName; /* Name of a limit */
5846 int limitCode; /* Integer code for that limit */
5847 } aLimit[] = {
5848 { "length", SQLITE_LIMIT_LENGTH },
5849 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5850 { "column", SQLITE_LIMIT_COLUMN },
5851 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5852 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5853 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5854 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5855 { "attached", SQLITE_LIMIT_ATTACHED },
5856 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5857 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5858 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5859 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5860 };
5861 int i, n2;
5862 open_db(p, 0);
5863 if( nArg==1 ){
5864 for(i=0; i<ArraySize(aLimit); i++){
5865 printf("%20s %d\n", aLimit[i].zLimitName,
5866 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5867 }
5868 }else if( nArg>3 ){
5869 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
5870 rc = 1;
5871 goto meta_command_exit;
5872 }else{
5873 int iLimit = -1;
5874 n2 = strlen30(azArg[1]);
5875 for(i=0; i<ArraySize(aLimit); i++){
5876 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5877 if( iLimit<0 ){
5878 iLimit = i;
5879 }else{
5880 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
5881 rc = 1;
5882 goto meta_command_exit;
5883 }
5884 }
5885 }
5886 if( iLimit<0 ){
5887 utf8_printf(stderr, "unknown limit: \"%s\"\n"
5888 "enter \".limits\" with no arguments for a list.\n",
5889 azArg[1]);
5890 rc = 1;
5891 goto meta_command_exit;
5892 }
5893 if( nArg==3 ){
5894 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5895 (int)integerValue(azArg[2]));
5896 }
5897 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5898 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5899 }
5900 }else
5901
5902 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
5903 open_db(p, 0);
5904 lintDotCommand(p, azArg, nArg);
5905 }else
5906
5907#ifndef SQLITE_OMIT_LOAD_EXTENSION
5908 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
5909 const char *zFile, *zProc;
5910 char *zErrMsg = 0;
5911 if( nArg<2 ){
5912 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
5913 rc = 1;
5914 goto meta_command_exit;
5915 }
5916 zFile = azArg[1];
5917 zProc = nArg>=3 ? azArg[2] : 0;
5918 open_db(p, 0);
5919 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5920 if( rc!=SQLITE_OK ){
5921 utf8_printf(stderr, "Error: %s\n", zErrMsg);
5922 sqlite3_free(zErrMsg);
5923 rc = 1;
5924 }
5925 }else
5926#endif
5927
5928 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5929 if( nArg!=2 ){
5930 raw_printf(stderr, "Usage: .log FILENAME\n");
5931 rc = 1;
5932 }else{
5933 const char *zFile = azArg[1];
5934 output_file_close(p->pLog);
5935 p->pLog = output_file_open(zFile);
5936 }
5937 }else
5938
5939 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5940 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00005941 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00005942 int c2 = zMode[0];
5943 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
5944 p->mode = MODE_Line;
5945 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5946 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
5947 p->mode = MODE_Column;
5948 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5949 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
5950 p->mode = MODE_List;
5951 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5952 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5953 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
5954 p->mode = MODE_Html;
5955 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
5956 p->mode = MODE_Tcl;
5957 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
5958 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5959 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
5960 p->mode = MODE_Csv;
5961 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
5962 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
5963 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
5964 p->mode = MODE_List;
5965 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
5966 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
5967 p->mode = MODE_Insert;
5968 set_table_name(p, nArg>=3 ? azArg[2] : "table");
5969 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5970 p->mode = MODE_Quote;
5971 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5972 p->mode = MODE_Ascii;
5973 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5974 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
5975 }else if( nArg==1 ){
5976 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
5977 }else{
5978 raw_printf(stderr, "Error: mode should be one of: "
5979 "ascii column csv html insert line list quote tabs tcl\n");
5980 rc = 1;
5981 }
5982 p->cMode = p->mode;
5983 }else
5984
5985 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5986 if( nArg==2 ){
5987 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5988 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
5989 }else{
5990 raw_printf(stderr, "Usage: .nullvalue STRING\n");
5991 rc = 1;
5992 }
5993 }else
5994
5995 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
5996 char *zNewFilename; /* Name of the database file to open */
5997 int iName = 1; /* Index in azArg[] of the filename */
5998 int newFlag = 0; /* True to delete file before opening */
5999 /* Close the existing database */
6000 session_close_all(p);
6001 sqlite3_close(p->db);
6002 p->db = 0;
6003 p->zDbFilename = 0;
6004 sqlite3_free(p->zFreeOnClose);
6005 p->zFreeOnClose = 0;
6006 /* Check for command-line arguments */
6007 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6008 const char *z = azArg[iName];
6009 if( optionMatch(z,"new") ){
6010 newFlag = 1;
6011 }else if( z[0]=='-' ){
6012 utf8_printf(stderr, "unknown option: %s\n", z);
6013 rc = 1;
6014 goto meta_command_exit;
6015 }
6016 }
6017 /* If a filename is specified, try to open it first */
6018 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
6019 if( zNewFilename ){
6020 if( newFlag ) shellDeleteFile(zNewFilename);
6021 p->zDbFilename = zNewFilename;
6022 open_db(p, 1);
6023 if( p->db==0 ){
6024 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6025 sqlite3_free(zNewFilename);
6026 }else{
6027 p->zFreeOnClose = zNewFilename;
6028 }
6029 }
6030 if( p->db==0 ){
6031 /* As a fall-back open a TEMP database */
6032 p->zDbFilename = 0;
6033 open_db(p, 0);
6034 }
6035 }else
6036
6037 if( c=='o'
6038 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
6039 ){
6040 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
6041 if( nArg>2 ){
6042 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
6043 rc = 1;
6044 goto meta_command_exit;
6045 }
6046 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6047 if( nArg<2 ){
6048 raw_printf(stderr, "Usage: .once FILE\n");
6049 rc = 1;
6050 goto meta_command_exit;
6051 }
6052 p->outCount = 2;
6053 }else{
6054 p->outCount = 0;
6055 }
6056 output_reset(p);
6057 if( zFile[0]=='|' ){
6058#ifdef SQLITE_OMIT_POPEN
6059 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6060 rc = 1;
6061 p->out = stdout;
6062#else
6063 p->out = popen(zFile + 1, "w");
6064 if( p->out==0 ){
6065 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
6066 p->out = stdout;
6067 rc = 1;
6068 }else{
6069 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6070 }
6071#endif
6072 }else{
6073 p->out = output_file_open(zFile);
6074 if( p->out==0 ){
6075 if( strcmp(zFile,"off")!=0 ){
6076 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
6077 }
6078 p->out = stdout;
6079 rc = 1;
6080 } else {
6081 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6082 }
6083 }
6084 }else
6085
6086 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6087 int i;
6088 for(i=1; i<nArg; i++){
6089 if( i>1 ) raw_printf(p->out, " ");
6090 utf8_printf(p->out, "%s", azArg[i]);
6091 }
6092 raw_printf(p->out, "\n");
6093 }else
6094
6095 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
6096 if( nArg >= 2) {
6097 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6098 }
6099 if( nArg >= 3) {
6100 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6101 }
6102 }else
6103
6104 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
6105 rc = 2;
6106 }else
6107
6108 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6109 FILE *alt;
6110 if( nArg!=2 ){
6111 raw_printf(stderr, "Usage: .read FILE\n");
6112 rc = 1;
6113 goto meta_command_exit;
6114 }
6115 alt = fopen(azArg[1], "rb");
6116 if( alt==0 ){
6117 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6118 rc = 1;
6119 }else{
6120 rc = process_input(p, alt);
6121 fclose(alt);
6122 }
6123 }else
6124
6125 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
6126 const char *zSrcFile;
6127 const char *zDb;
6128 sqlite3 *pSrc;
6129 sqlite3_backup *pBackup;
6130 int nTimeout = 0;
6131
6132 if( nArg==2 ){
6133 zSrcFile = azArg[1];
6134 zDb = "main";
6135 }else if( nArg==3 ){
6136 zSrcFile = azArg[2];
6137 zDb = azArg[1];
6138 }else{
6139 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
6140 rc = 1;
6141 goto meta_command_exit;
6142 }
6143 rc = sqlite3_open(zSrcFile, &pSrc);
6144 if( rc!=SQLITE_OK ){
6145 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
6146 sqlite3_close(pSrc);
6147 return 1;
6148 }
6149 open_db(p, 0);
6150 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6151 if( pBackup==0 ){
6152 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6153 sqlite3_close(pSrc);
6154 return 1;
6155 }
6156 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6157 || rc==SQLITE_BUSY ){
6158 if( rc==SQLITE_BUSY ){
6159 if( nTimeout++ >= 3 ) break;
6160 sqlite3_sleep(100);
6161 }
6162 }
6163 sqlite3_backup_finish(pBackup);
6164 if( rc==SQLITE_DONE ){
6165 rc = 0;
6166 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
6167 raw_printf(stderr, "Error: source database is busy\n");
6168 rc = 1;
6169 }else{
6170 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6171 rc = 1;
6172 }
6173 sqlite3_close(pSrc);
6174 }else
6175
6176
6177 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6178 if( nArg==2 ){
6179 p->scanstatsOn = booleanValue(azArg[1]);
6180#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6181 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
6182#endif
6183 }else{
6184 raw_printf(stderr, "Usage: .scanstats on|off\n");
6185 rc = 1;
6186 }
6187 }else
6188
6189 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
6190 ShellText sSelect;
6191 ShellState data;
6192 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00006193 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00006194 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00006195 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00006196 int bDebug = 0;
6197 int ii;
drh2ce15c32017-07-11 13:34:40 +00006198
6199 open_db(p, 0);
6200 memcpy(&data, p, sizeof(data));
6201 data.showHeader = 0;
6202 data.cMode = data.mode = MODE_Semi;
6203 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00006204 for(ii=1; ii<nArg; ii++){
6205 if( optionMatch(azArg[ii],"indent") ){
6206 data.cMode = data.mode = MODE_Pretty;
6207 }else if( optionMatch(azArg[ii],"debug") ){
6208 bDebug = 1;
6209 }else if( zName==0 ){
6210 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00006211 }else{
drhceba7922018-01-01 21:28:25 +00006212 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6213 rc = 1;
6214 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00006215 }
drh2ce15c32017-07-11 13:34:40 +00006216 }
drhceba7922018-01-01 21:28:25 +00006217 if( zName!=0 ){
drh667a2a22018-01-02 00:04:37 +00006218 int isMaster = sqlite3_strlike(zName, "sqlite_master", 0)==0;
6219 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master",0)==0 ){
drh2ce15c32017-07-11 13:34:40 +00006220 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00006221 new_argv[0] = sqlite3_mprintf(
6222 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00006223 " type text,\n"
6224 " name text,\n"
6225 " tbl_name text,\n"
6226 " rootpage integer,\n"
6227 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00006228 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00006229 new_argv[1] = 0;
6230 new_colv[0] = "sql";
6231 new_colv[1] = 0;
6232 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00006233 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00006234 }
drh2ce15c32017-07-11 13:34:40 +00006235 }
6236 if( zDiv ){
6237 sqlite3_stmt *pStmt = 0;
6238 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6239 -1, &pStmt, 0);
6240 if( rc ){
6241 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6242 sqlite3_finalize(pStmt);
6243 rc = 1;
6244 goto meta_command_exit;
6245 }
6246 appendText(&sSelect, "SELECT sql FROM", 0);
6247 iSchema = 0;
6248 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6249 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6250 char zScNum[30];
6251 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6252 appendText(&sSelect, zDiv, 0);
6253 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00006254 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
6255 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00006256 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00006257 }else{
drhceba7922018-01-01 21:28:25 +00006258 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00006259 }
drhceba7922018-01-01 21:28:25 +00006260 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6261 appendText(&sSelect, zScNum, 0);
6262 appendText(&sSelect, " AS snum, ", 0);
6263 appendText(&sSelect, zDb, '\'');
6264 appendText(&sSelect, " AS sname FROM ", 0);
6265 appendText(&sSelect, zDb, '"');
6266 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00006267 }
6268 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00006269#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00006270 if( zName ){
6271 appendText(&sSelect,
6272 " UNION ALL SELECT shell_module_schema(name),"
6273 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6274 }
drhcde7b772018-01-02 12:50:40 +00006275#endif
drh2ce15c32017-07-11 13:34:40 +00006276 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00006277 if( zName ){
6278 char *zQarg = sqlite3_mprintf("%Q", zName);
6279 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00006280 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6281 }else{
6282 appendText(&sSelect, "lower(tbl_name)", 0);
6283 }
drhceba7922018-01-01 21:28:25 +00006284 appendText(&sSelect, strchr(zName, '*') ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00006285 appendText(&sSelect, zQarg, 0);
6286 appendText(&sSelect, " AND ", 0);
6287 sqlite3_free(zQarg);
6288 }
6289 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6290 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00006291 if( bDebug ){
6292 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
6293 }else{
6294 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6295 }
drh2ce15c32017-07-11 13:34:40 +00006296 freeText(&sSelect);
6297 }
6298 if( zErrMsg ){
6299 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6300 sqlite3_free(zErrMsg);
6301 rc = 1;
6302 }else if( rc != SQLITE_OK ){
6303 raw_printf(stderr,"Error: querying schema information\n");
6304 rc = 1;
6305 }else{
6306 rc = 0;
6307 }
6308 }else
6309
6310#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6311 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
6312 sqlite3SelectTrace = (int)integerValue(azArg[1]);
6313 }else
6314#endif
6315
6316#if defined(SQLITE_ENABLE_SESSION)
6317 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
6318 OpenSession *pSession = &p->aSession[0];
6319 char **azCmd = &azArg[1];
6320 int iSes = 0;
6321 int nCmd = nArg - 1;
6322 int i;
6323 if( nArg<=1 ) goto session_syntax_error;
6324 open_db(p, 0);
6325 if( nArg>=3 ){
6326 for(iSes=0; iSes<p->nSession; iSes++){
6327 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
6328 }
6329 if( iSes<p->nSession ){
6330 pSession = &p->aSession[iSes];
6331 azCmd++;
6332 nCmd--;
6333 }else{
6334 pSession = &p->aSession[0];
6335 iSes = 0;
6336 }
6337 }
6338
6339 /* .session attach TABLE
6340 ** Invoke the sqlite3session_attach() interface to attach a particular
6341 ** table so that it is never filtered.
6342 */
6343 if( strcmp(azCmd[0],"attach")==0 ){
6344 if( nCmd!=2 ) goto session_syntax_error;
6345 if( pSession->p==0 ){
6346 session_not_open:
6347 raw_printf(stderr, "ERROR: No sessions are open\n");
6348 }else{
6349 rc = sqlite3session_attach(pSession->p, azCmd[1]);
6350 if( rc ){
6351 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
6352 rc = 0;
6353 }
6354 }
6355 }else
6356
6357 /* .session changeset FILE
6358 ** .session patchset FILE
6359 ** Write a changeset or patchset into a file. The file is overwritten.
6360 */
6361 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
6362 FILE *out = 0;
6363 if( nCmd!=2 ) goto session_syntax_error;
6364 if( pSession->p==0 ) goto session_not_open;
6365 out = fopen(azCmd[1], "wb");
6366 if( out==0 ){
6367 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
6368 }else{
6369 int szChng;
6370 void *pChng;
6371 if( azCmd[0][0]=='c' ){
6372 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
6373 }else{
6374 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
6375 }
6376 if( rc ){
6377 printf("Error: error code %d\n", rc);
6378 rc = 0;
6379 }
6380 if( pChng
6381 && fwrite(pChng, szChng, 1, out)!=1 ){
6382 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
6383 szChng);
6384 }
6385 sqlite3_free(pChng);
6386 fclose(out);
6387 }
6388 }else
6389
6390 /* .session close
6391 ** Close the identified session
6392 */
6393 if( strcmp(azCmd[0], "close")==0 ){
6394 if( nCmd!=1 ) goto session_syntax_error;
6395 if( p->nSession ){
6396 session_close(pSession);
6397 p->aSession[iSes] = p->aSession[--p->nSession];
6398 }
6399 }else
6400
6401 /* .session enable ?BOOLEAN?
6402 ** Query or set the enable flag
6403 */
6404 if( strcmp(azCmd[0], "enable")==0 ){
6405 int ii;
6406 if( nCmd>2 ) goto session_syntax_error;
6407 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6408 if( p->nSession ){
6409 ii = sqlite3session_enable(pSession->p, ii);
6410 utf8_printf(p->out, "session %s enable flag = %d\n",
6411 pSession->zName, ii);
6412 }
6413 }else
6414
6415 /* .session filter GLOB ....
6416 ** Set a list of GLOB patterns of table names to be excluded.
6417 */
6418 if( strcmp(azCmd[0], "filter")==0 ){
6419 int ii, nByte;
6420 if( nCmd<2 ) goto session_syntax_error;
6421 if( p->nSession ){
6422 for(ii=0; ii<pSession->nFilter; ii++){
6423 sqlite3_free(pSession->azFilter[ii]);
6424 }
6425 sqlite3_free(pSession->azFilter);
6426 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6427 pSession->azFilter = sqlite3_malloc( nByte );
6428 if( pSession->azFilter==0 ){
6429 raw_printf(stderr, "Error: out or memory\n");
6430 exit(1);
6431 }
6432 for(ii=1; ii<nCmd; ii++){
6433 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
6434 }
6435 pSession->nFilter = ii-1;
6436 }
6437 }else
6438
6439 /* .session indirect ?BOOLEAN?
6440 ** Query or set the indirect flag
6441 */
6442 if( strcmp(azCmd[0], "indirect")==0 ){
6443 int ii;
6444 if( nCmd>2 ) goto session_syntax_error;
6445 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6446 if( p->nSession ){
6447 ii = sqlite3session_indirect(pSession->p, ii);
6448 utf8_printf(p->out, "session %s indirect flag = %d\n",
6449 pSession->zName, ii);
6450 }
6451 }else
6452
6453 /* .session isempty
6454 ** Determine if the session is empty
6455 */
6456 if( strcmp(azCmd[0], "isempty")==0 ){
6457 int ii;
6458 if( nCmd!=1 ) goto session_syntax_error;
6459 if( p->nSession ){
6460 ii = sqlite3session_isempty(pSession->p);
6461 utf8_printf(p->out, "session %s isempty flag = %d\n",
6462 pSession->zName, ii);
6463 }
6464 }else
6465
6466 /* .session list
6467 ** List all currently open sessions
6468 */
6469 if( strcmp(azCmd[0],"list")==0 ){
6470 for(i=0; i<p->nSession; i++){
6471 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
6472 }
6473 }else
6474
6475 /* .session open DB NAME
6476 ** Open a new session called NAME on the attached database DB.
6477 ** DB is normally "main".
6478 */
6479 if( strcmp(azCmd[0],"open")==0 ){
6480 char *zName;
6481 if( nCmd!=3 ) goto session_syntax_error;
6482 zName = azCmd[2];
6483 if( zName[0]==0 ) goto session_syntax_error;
6484 for(i=0; i<p->nSession; i++){
6485 if( strcmp(p->aSession[i].zName,zName)==0 ){
6486 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
6487 goto meta_command_exit;
6488 }
6489 }
6490 if( p->nSession>=ArraySize(p->aSession) ){
6491 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
6492 goto meta_command_exit;
6493 }
6494 pSession = &p->aSession[p->nSession];
6495 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
6496 if( rc ){
6497 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
6498 rc = 0;
6499 goto meta_command_exit;
6500 }
6501 pSession->nFilter = 0;
6502 sqlite3session_table_filter(pSession->p, session_filter, pSession);
6503 p->nSession++;
6504 pSession->zName = sqlite3_mprintf("%s", zName);
6505 }else
6506 /* If no command name matches, show a syntax error */
6507 session_syntax_error:
6508 session_help(p);
6509 }else
6510#endif
6511
6512#ifdef SQLITE_DEBUG
6513 /* Undocumented commands for internal testing. Subject to change
6514 ** without notice. */
6515 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
6516 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
6517 int i, v;
6518 for(i=1; i<nArg; i++){
6519 v = booleanValue(azArg[i]);
6520 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
6521 }
6522 }
6523 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
6524 int i; sqlite3_int64 v;
6525 for(i=1; i<nArg; i++){
6526 char zBuf[200];
6527 v = integerValue(azArg[i]);
6528 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
6529 utf8_printf(p->out, "%s", zBuf);
6530 }
6531 }
6532 }else
6533#endif
6534
6535 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6536 int bIsInit = 0; /* True to initialize the SELFTEST table */
6537 int bVerbose = 0; /* Verbose output */
6538 int bSelftestExists; /* True if SELFTEST already exists */
6539 int i, k; /* Loop counters */
6540 int nTest = 0; /* Number of tests runs */
6541 int nErr = 0; /* Number of errors seen */
6542 ShellText str; /* Answer for a query */
6543 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
6544
6545 open_db(p,0);
6546 for(i=1; i<nArg; i++){
6547 const char *z = azArg[i];
6548 if( z[0]=='-' && z[1]=='-' ) z++;
6549 if( strcmp(z,"-init")==0 ){
6550 bIsInit = 1;
6551 }else
6552 if( strcmp(z,"-v")==0 ){
6553 bVerbose++;
6554 }else
6555 {
6556 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6557 azArg[i], azArg[0]);
6558 raw_printf(stderr, "Should be one of: --init -v\n");
6559 rc = 1;
6560 goto meta_command_exit;
6561 }
6562 }
6563 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6564 != SQLITE_OK ){
6565 bSelftestExists = 0;
6566 }else{
6567 bSelftestExists = 1;
6568 }
6569 if( bIsInit ){
6570 createSelftestTable(p);
6571 bSelftestExists = 1;
6572 }
6573 initText(&str);
6574 appendText(&str, "x", 0);
6575 for(k=bSelftestExists; k>=0; k--){
6576 if( k==1 ){
6577 rc = sqlite3_prepare_v2(p->db,
6578 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6579 -1, &pStmt, 0);
6580 }else{
6581 rc = sqlite3_prepare_v2(p->db,
6582 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6583 " (1,'run','PRAGMA integrity_check','ok')",
6584 -1, &pStmt, 0);
6585 }
6586 if( rc ){
6587 raw_printf(stderr, "Error querying the selftest table\n");
6588 rc = 1;
6589 sqlite3_finalize(pStmt);
6590 goto meta_command_exit;
6591 }
6592 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6593 int tno = sqlite3_column_int(pStmt, 0);
6594 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6595 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6596 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
6597
6598 k = 0;
6599 if( bVerbose>0 ){
6600 char *zQuote = sqlite3_mprintf("%q", zSql);
6601 printf("%d: %s %s\n", tno, zOp, zSql);
6602 sqlite3_free(zQuote);
6603 }
6604 if( strcmp(zOp,"memo")==0 ){
6605 utf8_printf(p->out, "%s\n", zSql);
6606 }else
6607 if( strcmp(zOp,"run")==0 ){
6608 char *zErrMsg = 0;
6609 str.n = 0;
6610 str.z[0] = 0;
6611 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6612 nTest++;
6613 if( bVerbose ){
6614 utf8_printf(p->out, "Result: %s\n", str.z);
6615 }
6616 if( rc || zErrMsg ){
6617 nErr++;
6618 rc = 1;
6619 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6620 sqlite3_free(zErrMsg);
6621 }else if( strcmp(zAns,str.z)!=0 ){
6622 nErr++;
6623 rc = 1;
6624 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6625 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6626 }
6627 }else
6628 {
6629 utf8_printf(stderr,
6630 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
6631 rc = 1;
6632 break;
6633 }
6634 } /* End loop over rows of content from SELFTEST */
6635 sqlite3_finalize(pStmt);
6636 } /* End loop over k */
6637 freeText(&str);
6638 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6639 }else
6640
6641 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
6642 if( nArg<2 || nArg>3 ){
6643 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
6644 rc = 1;
6645 }
6646 if( nArg>=2 ){
6647 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
6648 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
6649 }
6650 if( nArg>=3 ){
6651 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6652 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
6653 }
6654 }else
6655
6656 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6657 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6658 int i; /* Loop counter */
6659 int bSchema = 0; /* Also hash the schema */
6660 int bSeparate = 0; /* Hash each table separately */
6661 int iSize = 224; /* Hash algorithm to use */
6662 int bDebug = 0; /* Only show the query that would have run */
6663 sqlite3_stmt *pStmt; /* For querying tables names */
6664 char *zSql; /* SQL to be run */
6665 char *zSep; /* Separator */
6666 ShellText sSql; /* Complete SQL for the query to run the hash */
6667 ShellText sQuery; /* Set of queries used to read all content */
6668 open_db(p, 0);
6669 for(i=1; i<nArg; i++){
6670 const char *z = azArg[i];
6671 if( z[0]=='-' ){
6672 z++;
6673 if( z[0]=='-' ) z++;
6674 if( strcmp(z,"schema")==0 ){
6675 bSchema = 1;
6676 }else
6677 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6678 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
6679 ){
6680 iSize = atoi(&z[5]);
6681 }else
6682 if( strcmp(z,"debug")==0 ){
6683 bDebug = 1;
6684 }else
6685 {
6686 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6687 azArg[i], azArg[0]);
6688 raw_printf(stderr, "Should be one of: --schema"
6689 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6690 rc = 1;
6691 goto meta_command_exit;
6692 }
6693 }else if( zLike ){
6694 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6695 rc = 1;
6696 goto meta_command_exit;
6697 }else{
6698 zLike = z;
6699 bSeparate = 1;
6700 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
6701 }
6702 }
6703 if( bSchema ){
6704 zSql = "SELECT lower(name) FROM sqlite_master"
6705 " WHERE type='table' AND coalesce(rootpage,0)>1"
6706 " UNION ALL SELECT 'sqlite_master'"
6707 " ORDER BY 1 collate nocase";
6708 }else{
6709 zSql = "SELECT lower(name) FROM sqlite_master"
6710 " WHERE type='table' AND coalesce(rootpage,0)>1"
6711 " AND name NOT LIKE 'sqlite_%'"
6712 " ORDER BY 1 collate nocase";
6713 }
6714 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6715 initText(&sQuery);
6716 initText(&sSql);
6717 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6718 zSep = "VALUES(";
6719 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6720 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6721 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6722 if( strncmp(zTab, "sqlite_",7)!=0 ){
6723 appendText(&sQuery,"SELECT * FROM ", 0);
6724 appendText(&sQuery,zTab,'"');
6725 appendText(&sQuery," NOT INDEXED;", 0);
6726 }else if( strcmp(zTab, "sqlite_master")==0 ){
6727 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6728 " ORDER BY name;", 0);
6729 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6730 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6731 " ORDER BY name;", 0);
6732 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6733 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6734 " ORDER BY tbl,idx;", 0);
6735 }else if( strcmp(zTab, "sqlite_stat3")==0
6736 || strcmp(zTab, "sqlite_stat4")==0 ){
6737 appendText(&sQuery, "SELECT * FROM ", 0);
6738 appendText(&sQuery, zTab, 0);
6739 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6740 }
6741 appendText(&sSql, zSep, 0);
6742 appendText(&sSql, sQuery.z, '\'');
6743 sQuery.n = 0;
6744 appendText(&sSql, ",", 0);
6745 appendText(&sSql, zTab, '\'');
6746 zSep = "),(";
6747 }
6748 sqlite3_finalize(pStmt);
6749 if( bSeparate ){
6750 zSql = sqlite3_mprintf(
6751 "%s))"
6752 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6753 " FROM [sha3sum$query]",
6754 sSql.z, iSize);
6755 }else{
6756 zSql = sqlite3_mprintf(
6757 "%s))"
6758 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6759 " FROM [sha3sum$query]",
6760 sSql.z, iSize);
6761 }
6762 freeText(&sQuery);
6763 freeText(&sSql);
6764 if( bDebug ){
6765 utf8_printf(p->out, "%s\n", zSql);
6766 }else{
6767 shell_exec(p->db, zSql, shell_callback, p, 0);
6768 }
6769 sqlite3_free(zSql);
6770 }else
6771
6772 if( c=='s'
6773 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
6774 ){
6775 char *zCmd;
6776 int i, x;
6777 if( nArg<2 ){
6778 raw_printf(stderr, "Usage: .system COMMAND\n");
6779 rc = 1;
6780 goto meta_command_exit;
6781 }
6782 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
6783 for(i=2; i<nArg; i++){
6784 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6785 zCmd, azArg[i]);
6786 }
6787 x = system(zCmd);
6788 sqlite3_free(zCmd);
6789 if( x ) raw_printf(stderr, "System command returns %d\n", x);
6790 }else
6791
6792 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00006793 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00006794 int i;
6795 if( nArg!=1 ){
6796 raw_printf(stderr, "Usage: .show\n");
6797 rc = 1;
6798 goto meta_command_exit;
6799 }
6800 utf8_printf(p->out, "%12.12s: %s\n","echo",
6801 azBool[ShellHasFlag(p, SHFLG_Echo)]);
6802 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
6803 utf8_printf(p->out, "%12.12s: %s\n","explain",
6804 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
6805 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
6806 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6807 utf8_printf(p->out, "%12.12s: ", "nullvalue");
6808 output_c_string(p->out, p->nullValue);
6809 raw_printf(p->out, "\n");
6810 utf8_printf(p->out,"%12.12s: %s\n","output",
6811 strlen30(p->outfile) ? p->outfile : "stdout");
6812 utf8_printf(p->out,"%12.12s: ", "colseparator");
6813 output_c_string(p->out, p->colSeparator);
6814 raw_printf(p->out, "\n");
6815 utf8_printf(p->out,"%12.12s: ", "rowseparator");
6816 output_c_string(p->out, p->rowSeparator);
6817 raw_printf(p->out, "\n");
6818 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
6819 utf8_printf(p->out, "%12.12s: ", "width");
6820 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
6821 raw_printf(p->out, "%d ", p->colWidth[i]);
6822 }
6823 raw_printf(p->out, "\n");
6824 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6825 p->zDbFilename ? p->zDbFilename : "");
6826 }else
6827
6828 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6829 if( nArg==2 ){
6830 p->statsOn = booleanValue(azArg[1]);
6831 }else if( nArg==1 ){
6832 display_stats(p->db, p, 0);
6833 }else{
6834 raw_printf(stderr, "Usage: .stats ?on|off?\n");
6835 rc = 1;
6836 }
6837 }else
6838
6839 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6840 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6841 || strncmp(azArg[0], "indexes", n)==0) )
6842 ){
6843 sqlite3_stmt *pStmt;
6844 char **azResult;
6845 int nRow, nAlloc;
6846 int ii;
6847 ShellText s;
6848 initText(&s);
6849 open_db(p, 0);
6850 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
6851 if( rc ) return shellDatabaseError(p->db);
6852
6853 if( nArg>2 && c=='i' ){
6854 /* It is an historical accident that the .indexes command shows an error
6855 ** when called with the wrong number of arguments whereas the .tables
6856 ** command does not. */
6857 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6858 rc = 1;
6859 goto meta_command_exit;
6860 }
6861 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
6862 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
6863 if( zDbName==0 ) continue;
6864 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
6865 if( sqlite3_stricmp(zDbName, "main")==0 ){
6866 appendText(&s, "SELECT name FROM ", 0);
6867 }else{
6868 appendText(&s, "SELECT ", 0);
6869 appendText(&s, zDbName, '\'');
6870 appendText(&s, "||'.'||name FROM ", 0);
6871 }
6872 appendText(&s, zDbName, '"');
6873 appendText(&s, ".sqlite_master ", 0);
6874 if( c=='t' ){
6875 appendText(&s," WHERE type IN ('table','view')"
6876 " AND name NOT LIKE 'sqlite_%'"
6877 " AND name LIKE ?1", 0);
6878 }else{
6879 appendText(&s," WHERE type='index'"
6880 " AND tbl_name LIKE ?1", 0);
6881 }
6882 }
6883 rc = sqlite3_finalize(pStmt);
6884 appendText(&s, " ORDER BY 1", 0);
6885 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
6886 freeText(&s);
6887 if( rc ) return shellDatabaseError(p->db);
6888
6889 /* Run the SQL statement prepared by the above block. Store the results
6890 ** as an array of nul-terminated strings in azResult[]. */
6891 nRow = nAlloc = 0;
6892 azResult = 0;
6893 if( nArg>1 ){
6894 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
6895 }else{
6896 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6897 }
6898 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6899 if( nRow>=nAlloc ){
6900 char **azNew;
6901 int n2 = nAlloc*2 + 10;
6902 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
6903 if( azNew==0 ){
6904 rc = shellNomemError();
6905 break;
6906 }
6907 nAlloc = n2;
6908 azResult = azNew;
6909 }
6910 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
6911 if( 0==azResult[nRow] ){
6912 rc = shellNomemError();
6913 break;
6914 }
6915 nRow++;
6916 }
6917 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6918 rc = shellDatabaseError(p->db);
6919 }
6920
6921 /* Pretty-print the contents of array azResult[] to the output */
6922 if( rc==0 && nRow>0 ){
6923 int len, maxlen = 0;
6924 int i, j;
6925 int nPrintCol, nPrintRow;
6926 for(i=0; i<nRow; i++){
6927 len = strlen30(azResult[i]);
6928 if( len>maxlen ) maxlen = len;
6929 }
6930 nPrintCol = 80/(maxlen+2);
6931 if( nPrintCol<1 ) nPrintCol = 1;
6932 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6933 for(i=0; i<nPrintRow; i++){
6934 for(j=i; j<nRow; j+=nPrintRow){
6935 char *zSp = j<nPrintRow ? "" : " ";
6936 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6937 azResult[j] ? azResult[j]:"");
6938 }
6939 raw_printf(p->out, "\n");
6940 }
6941 }
6942
6943 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6944 sqlite3_free(azResult);
6945 }else
6946
6947 /* Begin redirecting output to the file "testcase-out.txt" */
6948 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6949 output_reset(p);
6950 p->out = output_file_open("testcase-out.txt");
6951 if( p->out==0 ){
6952 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
6953 }
6954 if( nArg>=2 ){
6955 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6956 }else{
6957 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6958 }
6959 }else
6960
6961#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00006962 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00006963 static const struct {
6964 const char *zCtrlName; /* Name of a test-control option */
6965 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00006966 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00006967 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00006968 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
6969 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
6970 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
6971 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
6972 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
6973 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
6974 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
6975#ifdef SQLITE_N_KEYWORD
6976 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD, "IDENTIFIER" },
6977#endif
6978 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
6979 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
6980 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00006981#ifdef YYCOVERAGE
6982 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
6983#endif
drhef302e82017-11-15 19:14:08 +00006984 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
6985 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
6986 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
6987 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
6988 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00006989 };
6990 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00006991 int iCtrl = -1;
6992 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
6993 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00006994 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00006995 const char *zCmd = 0;
6996
drh2ce15c32017-07-11 13:34:40 +00006997 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00006998 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00006999
7000 /* The argument can optionally begin with "-" or "--" */
7001 if( zCmd[0]=='-' && zCmd[1] ){
7002 zCmd++;
7003 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
7004 }
7005
7006 /* --help lists all test-controls */
7007 if( strcmp(zCmd,"help")==0 ){
7008 utf8_printf(p->out, "Available test-controls:\n");
7009 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00007010 utf8_printf(p->out, " .testctrl %s %s\n",
7011 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00007012 }
7013 rc = 1;
7014 goto meta_command_exit;
7015 }
drh2ce15c32017-07-11 13:34:40 +00007016
7017 /* convert testctrl text option to value. allow any unique prefix
7018 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00007019 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00007020 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00007021 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007022 if( testctrl<0 ){
7023 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00007024 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00007025 }else{
drh35f51a42017-11-15 17:07:22 +00007026 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
7027 "Use \".testctrl --help\" for help\n", zCmd);
7028 rc = 1;
7029 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00007030 }
7031 }
7032 }
drhef302e82017-11-15 19:14:08 +00007033 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00007034 utf8_printf(stderr,"Error: unknown test-control: %s\n"
7035 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00007036 }else{
7037 switch(testctrl){
7038
7039 /* sqlite3_test_control(int, db, int) */
7040 case SQLITE_TESTCTRL_OPTIMIZATIONS:
7041 case SQLITE_TESTCTRL_RESERVE:
7042 if( nArg==3 ){
7043 int opt = (int)strtol(azArg[2], 0, 0);
7044 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00007045 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007046 }
7047 break;
7048
7049 /* sqlite3_test_control(int) */
7050 case SQLITE_TESTCTRL_PRNG_SAVE:
7051 case SQLITE_TESTCTRL_PRNG_RESTORE:
7052 case SQLITE_TESTCTRL_PRNG_RESET:
7053 case SQLITE_TESTCTRL_BYTEORDER:
7054 if( nArg==2 ){
7055 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00007056 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00007057 }
7058 break;
7059
7060 /* sqlite3_test_control(int, uint) */
7061 case SQLITE_TESTCTRL_PENDING_BYTE:
7062 if( nArg==3 ){
7063 unsigned int opt = (unsigned int)integerValue(azArg[2]);
7064 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007065 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007066 }
7067 break;
7068
7069 /* sqlite3_test_control(int, int) */
7070 case SQLITE_TESTCTRL_ASSERT:
7071 case SQLITE_TESTCTRL_ALWAYS:
drhef302e82017-11-15 19:14:08 +00007072 if( nArg==3 ){
7073 int opt = booleanValue(azArg[2]);
7074 rc2 = sqlite3_test_control(testctrl, opt);
7075 isOk = 1;
7076 }
7077 break;
7078
7079 /* sqlite3_test_control(int, int) */
7080 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00007081 case SQLITE_TESTCTRL_NEVER_CORRUPT:
7082 if( nArg==3 ){
7083 int opt = booleanValue(azArg[2]);
7084 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007085 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007086 }
7087 break;
7088
7089 /* sqlite3_test_control(int, char *) */
7090#ifdef SQLITE_N_KEYWORD
7091 case SQLITE_TESTCTRL_ISKEYWORD:
7092 if( nArg==3 ){
7093 const char *opt = azArg[2];
7094 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007095 isOk = 1;
drh2ce15c32017-07-11 13:34:40 +00007096 }
7097 break;
7098#endif
7099
7100 case SQLITE_TESTCTRL_IMPOSTER:
7101 if( nArg==5 ){
7102 rc2 = sqlite3_test_control(testctrl, p->db,
7103 azArg[2],
7104 integerValue(azArg[3]),
7105 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00007106 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007107 }
7108 break;
drh0d9de992017-12-26 18:04:23 +00007109
7110#ifdef YYCOVERAGE
7111 case SQLITE_TESTCTRL_PARSER_COVERAGE:
7112 if( nArg==2 ){
7113 sqlite3_test_control(testctrl, p->out);
7114 isOk = 3;
7115 }
7116#endif
drh2ce15c32017-07-11 13:34:40 +00007117 }
7118 }
drhef302e82017-11-15 19:14:08 +00007119 if( isOk==0 && iCtrl>=0 ){
7120 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
7121 rc = 1;
7122 }else if( isOk==1 ){
7123 raw_printf(p->out, "%d\n", rc2);
7124 }else if( isOk==2 ){
7125 raw_printf(p->out, "0x%08x\n", rc2);
7126 }
drh2ce15c32017-07-11 13:34:40 +00007127 }else
7128#endif /* !defined(SQLITE_UNTESTABLE) */
7129
7130 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
7131 open_db(p, 0);
7132 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
7133 }else
7134
7135 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7136 if( nArg==2 ){
7137 enableTimer = booleanValue(azArg[1]);
7138 if( enableTimer && !HAS_TIMER ){
7139 raw_printf(stderr, "Error: timer not available on this system.\n");
7140 enableTimer = 0;
7141 }
7142 }else{
7143 raw_printf(stderr, "Usage: .timer on|off\n");
7144 rc = 1;
7145 }
7146 }else
7147
7148 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
7149 open_db(p, 0);
7150 if( nArg!=2 ){
7151 raw_printf(stderr, "Usage: .trace FILE|off\n");
7152 rc = 1;
7153 goto meta_command_exit;
7154 }
7155 output_file_close(p->traceOut);
7156 p->traceOut = output_file_open(azArg[1]);
7157#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7158 if( p->traceOut==0 ){
7159 sqlite3_trace_v2(p->db, 0, 0, 0);
7160 }else{
7161 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
7162 }
7163#endif
7164 }else
7165
7166#if SQLITE_USER_AUTHENTICATION
7167 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7168 if( nArg<2 ){
7169 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
7170 rc = 1;
7171 goto meta_command_exit;
7172 }
7173 open_db(p, 0);
7174 if( strcmp(azArg[1],"login")==0 ){
7175 if( nArg!=4 ){
7176 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
7177 rc = 1;
7178 goto meta_command_exit;
7179 }
drhaf2770f2018-01-05 14:55:43 +00007180 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00007181 if( rc ){
7182 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
7183 rc = 1;
7184 }
7185 }else if( strcmp(azArg[1],"add")==0 ){
7186 if( nArg!=5 ){
7187 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
7188 rc = 1;
7189 goto meta_command_exit;
7190 }
drhaf2770f2018-01-05 14:55:43 +00007191 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007192 booleanValue(azArg[4]));
7193 if( rc ){
7194 raw_printf(stderr, "User-Add failed: %d\n", rc);
7195 rc = 1;
7196 }
7197 }else if( strcmp(azArg[1],"edit")==0 ){
7198 if( nArg!=5 ){
7199 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
7200 rc = 1;
7201 goto meta_command_exit;
7202 }
drhaf2770f2018-01-05 14:55:43 +00007203 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007204 booleanValue(azArg[4]));
7205 if( rc ){
7206 raw_printf(stderr, "User-Edit failed: %d\n", rc);
7207 rc = 1;
7208 }
7209 }else if( strcmp(azArg[1],"delete")==0 ){
7210 if( nArg!=3 ){
7211 raw_printf(stderr, "Usage: .user delete USER\n");
7212 rc = 1;
7213 goto meta_command_exit;
7214 }
7215 rc = sqlite3_user_delete(p->db, azArg[2]);
7216 if( rc ){
7217 raw_printf(stderr, "User-Delete failed: %d\n", rc);
7218 rc = 1;
7219 }
7220 }else{
7221 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
7222 rc = 1;
7223 goto meta_command_exit;
7224 }
7225 }else
7226#endif /* SQLITE_USER_AUTHENTICATION */
7227
7228 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
7229 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
7230 sqlite3_libversion(), sqlite3_sourceid());
7231 }else
7232
7233 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7234 const char *zDbName = nArg==2 ? azArg[1] : "main";
7235 sqlite3_vfs *pVfs = 0;
7236 if( p->db ){
7237 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7238 if( pVfs ){
7239 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7240 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7241 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7242 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7243 }
7244 }
7245 }else
7246
7247 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7248 sqlite3_vfs *pVfs;
7249 sqlite3_vfs *pCurrent = 0;
7250 if( p->db ){
7251 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7252 }
7253 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7254 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7255 pVfs==pCurrent ? " <--- CURRENT" : "");
7256 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7257 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7258 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7259 if( pVfs->pNext ){
7260 raw_printf(p->out, "-----------------------------------\n");
7261 }
7262 }
7263 }else
7264
7265 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7266 const char *zDbName = nArg==2 ? azArg[1] : "main";
7267 char *zVfsName = 0;
7268 if( p->db ){
7269 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7270 if( zVfsName ){
7271 utf8_printf(p->out, "%s\n", zVfsName);
7272 sqlite3_free(zVfsName);
7273 }
7274 }
7275 }else
7276
7277#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7278 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
7279 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
7280 }else
7281#endif
7282
7283 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
7284 int j;
7285 assert( nArg<=ArraySize(azArg) );
7286 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
7287 p->colWidth[j-1] = (int)integerValue(azArg[j]);
7288 }
7289 }else
7290
7291 {
7292 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
7293 " \"%s\". Enter \".help\" for help\n", azArg[0]);
7294 rc = 1;
7295 }
7296
7297meta_command_exit:
7298 if( p->outCount ){
7299 p->outCount--;
7300 if( p->outCount==0 ) output_reset(p);
7301 }
7302 return rc;
7303}
7304
7305/*
7306** Return TRUE if a semicolon occurs anywhere in the first N characters
7307** of string z[].
7308*/
7309static int line_contains_semicolon(const char *z, int N){
7310 int i;
7311 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
7312 return 0;
7313}
7314
7315/*
7316** Test to see if a line consists entirely of whitespace.
7317*/
7318static int _all_whitespace(const char *z){
7319 for(; *z; z++){
7320 if( IsSpace(z[0]) ) continue;
7321 if( *z=='/' && z[1]=='*' ){
7322 z += 2;
7323 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
7324 if( *z==0 ) return 0;
7325 z++;
7326 continue;
7327 }
7328 if( *z=='-' && z[1]=='-' ){
7329 z += 2;
7330 while( *z && *z!='\n' ){ z++; }
7331 if( *z==0 ) return 1;
7332 continue;
7333 }
7334 return 0;
7335 }
7336 return 1;
7337}
7338
7339/*
7340** Return TRUE if the line typed in is an SQL command terminator other
7341** than a semi-colon. The SQL Server style "go" command is understood
7342** as is the Oracle "/".
7343*/
7344static int line_is_command_terminator(const char *zLine){
7345 while( IsSpace(zLine[0]) ){ zLine++; };
7346 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
7347 return 1; /* Oracle */
7348 }
7349 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
7350 && _all_whitespace(&zLine[2]) ){
7351 return 1; /* SQL Server */
7352 }
7353 return 0;
7354}
7355
7356/*
7357** Return true if zSql is a complete SQL statement. Return false if it
7358** ends in the middle of a string literal or C-style comment.
7359*/
7360static int line_is_complete(char *zSql, int nSql){
7361 int rc;
7362 if( zSql==0 ) return 1;
7363 zSql[nSql] = ';';
7364 zSql[nSql+1] = 0;
7365 rc = sqlite3_complete(zSql);
7366 zSql[nSql] = 0;
7367 return rc;
7368}
7369
7370/*
7371** Run a single line of SQL
7372*/
7373static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
7374 int rc;
7375 char *zErrMsg = 0;
7376
7377 open_db(p, 0);
7378 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
7379 BEGIN_TIMER;
7380 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
7381 END_TIMER;
7382 if( rc || zErrMsg ){
7383 char zPrefix[100];
7384 if( in!=0 || !stdin_is_interactive ){
7385 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
7386 "Error: near line %d:", startline);
7387 }else{
7388 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
7389 }
7390 if( zErrMsg!=0 ){
7391 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
7392 sqlite3_free(zErrMsg);
7393 zErrMsg = 0;
7394 }else{
7395 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
7396 }
7397 return 1;
7398 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
7399 raw_printf(p->out, "changes: %3d total_changes: %d\n",
7400 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
7401 }
7402 return 0;
7403}
7404
7405
7406/*
7407** Read input from *in and process it. If *in==0 then input
7408** is interactive - the user is typing it it. Otherwise, input
7409** is coming from a file or device. A prompt is issued and history
7410** is saved only if input is interactive. An interrupt signal will
7411** cause this routine to exit immediately, unless input is interactive.
7412**
7413** Return the number of errors.
7414*/
7415static int process_input(ShellState *p, FILE *in){
7416 char *zLine = 0; /* A single input line */
7417 char *zSql = 0; /* Accumulated SQL text */
7418 int nLine; /* Length of current line */
7419 int nSql = 0; /* Bytes of zSql[] used */
7420 int nAlloc = 0; /* Allocated zSql[] space */
7421 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
7422 int rc; /* Error code */
7423 int errCnt = 0; /* Number of errors seen */
7424 int lineno = 0; /* Current line number */
7425 int startline = 0; /* Line number for start of current input */
7426
7427 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
7428 fflush(p->out);
7429 zLine = one_input_line(in, zLine, nSql>0);
7430 if( zLine==0 ){
7431 /* End of input */
7432 if( in==0 && stdin_is_interactive ) printf("\n");
7433 break;
7434 }
7435 if( seenInterrupt ){
7436 if( in!=0 ) break;
7437 seenInterrupt = 0;
7438 }
7439 lineno++;
7440 if( nSql==0 && _all_whitespace(zLine) ){
7441 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7442 continue;
7443 }
7444 if( zLine && zLine[0]=='.' && nSql==0 ){
7445 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7446 rc = do_meta_command(zLine, p);
7447 if( rc==2 ){ /* exit requested */
7448 break;
7449 }else if( rc ){
7450 errCnt++;
7451 }
7452 continue;
7453 }
7454 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
7455 memcpy(zLine,";",2);
7456 }
7457 nLine = strlen30(zLine);
7458 if( nSql+nLine+2>=nAlloc ){
7459 nAlloc = nSql+nLine+100;
7460 zSql = realloc(zSql, nAlloc);
7461 if( zSql==0 ){
7462 raw_printf(stderr, "Error: out of memory\n");
7463 exit(1);
7464 }
7465 }
7466 nSqlPrior = nSql;
7467 if( nSql==0 ){
7468 int i;
7469 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
7470 assert( nAlloc>0 && zSql!=0 );
7471 memcpy(zSql, zLine+i, nLine+1-i);
7472 startline = lineno;
7473 nSql = nLine-i;
7474 }else{
7475 zSql[nSql++] = '\n';
7476 memcpy(zSql+nSql, zLine, nLine+1);
7477 nSql += nLine;
7478 }
7479 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
7480 && sqlite3_complete(zSql) ){
7481 errCnt += runOneSqlLine(p, zSql, in, startline);
7482 nSql = 0;
7483 if( p->outCount ){
7484 output_reset(p);
7485 p->outCount = 0;
7486 }
7487 }else if( nSql && _all_whitespace(zSql) ){
7488 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
7489 nSql = 0;
7490 }
7491 }
7492 if( nSql && !_all_whitespace(zSql) ){
7493 runOneSqlLine(p, zSql, in, startline);
7494 }
7495 free(zSql);
7496 free(zLine);
7497 return errCnt>0;
7498}
7499
7500/*
7501** Return a pathname which is the user's home directory. A
7502** 0 return indicates an error of some kind.
7503*/
7504static char *find_home_dir(int clearFlag){
7505 static char *home_dir = NULL;
7506 if( clearFlag ){
7507 free(home_dir);
7508 home_dir = 0;
7509 return 0;
7510 }
7511 if( home_dir ) return home_dir;
7512
7513#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7514 && !defined(__RTP__) && !defined(_WRS_KERNEL)
7515 {
7516 struct passwd *pwent;
7517 uid_t uid = getuid();
7518 if( (pwent=getpwuid(uid)) != NULL) {
7519 home_dir = pwent->pw_dir;
7520 }
7521 }
7522#endif
7523
7524#if defined(_WIN32_WCE)
7525 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7526 */
7527 home_dir = "/";
7528#else
7529
7530#if defined(_WIN32) || defined(WIN32)
7531 if (!home_dir) {
7532 home_dir = getenv("USERPROFILE");
7533 }
7534#endif
7535
7536 if (!home_dir) {
7537 home_dir = getenv("HOME");
7538 }
7539
7540#if defined(_WIN32) || defined(WIN32)
7541 if (!home_dir) {
7542 char *zDrive, *zPath;
7543 int n;
7544 zDrive = getenv("HOMEDRIVE");
7545 zPath = getenv("HOMEPATH");
7546 if( zDrive && zPath ){
7547 n = strlen30(zDrive) + strlen30(zPath) + 1;
7548 home_dir = malloc( n );
7549 if( home_dir==0 ) return 0;
7550 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7551 return home_dir;
7552 }
7553 home_dir = "c:\\";
7554 }
7555#endif
7556
7557#endif /* !_WIN32_WCE */
7558
7559 if( home_dir ){
7560 int n = strlen30(home_dir) + 1;
7561 char *z = malloc( n );
7562 if( z ) memcpy(z, home_dir, n);
7563 home_dir = z;
7564 }
7565
7566 return home_dir;
7567}
7568
7569/*
7570** Read input from the file given by sqliterc_override. Or if that
7571** parameter is NULL, take input from ~/.sqliterc
7572**
7573** Returns the number of errors.
7574*/
7575static void process_sqliterc(
7576 ShellState *p, /* Configuration data */
7577 const char *sqliterc_override /* Name of config file. NULL to use default */
7578){
7579 char *home_dir = NULL;
7580 const char *sqliterc = sqliterc_override;
7581 char *zBuf = 0;
7582 FILE *in = NULL;
7583
7584 if (sqliterc == NULL) {
7585 home_dir = find_home_dir(0);
7586 if( home_dir==0 ){
7587 raw_printf(stderr, "-- warning: cannot find home directory;"
7588 " cannot read ~/.sqliterc\n");
7589 return;
7590 }
7591 sqlite3_initialize();
7592 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7593 sqliterc = zBuf;
7594 }
7595 in = fopen(sqliterc,"rb");
7596 if( in ){
7597 if( stdin_is_interactive ){
7598 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
7599 }
7600 process_input(p,in);
7601 fclose(in);
7602 }
7603 sqlite3_free(zBuf);
7604}
7605
7606/*
7607** Show available command line options
7608*/
7609static const char zOptions[] =
7610 " -ascii set output mode to 'ascii'\n"
7611 " -bail stop after hitting an error\n"
7612 " -batch force batch I/O\n"
7613 " -column set output mode to 'column'\n"
7614 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
7615 " -csv set output mode to 'csv'\n"
7616 " -echo print commands before execution\n"
7617 " -init FILENAME read/process named file\n"
7618 " -[no]header turn headers on or off\n"
7619#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7620 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7621#endif
7622 " -help show this message\n"
7623 " -html set output mode to HTML\n"
7624 " -interactive force interactive I/O\n"
7625 " -line set output mode to 'line'\n"
7626 " -list set output mode to 'list'\n"
7627 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
7628 " -mmap N default mmap size set to N\n"
7629#ifdef SQLITE_ENABLE_MULTIPLEX
7630 " -multiplex enable the multiplexor VFS\n"
7631#endif
7632 " -newline SEP set output row separator. Default: '\\n'\n"
7633 " -nullvalue TEXT set text string for NULL values. Default ''\n"
7634 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7635 " -quote set output mode to 'quote'\n"
drh2ce15c32017-07-11 13:34:40 +00007636 " -separator SEP set output column separator. Default: '|'\n"
7637 " -stats print memory stats before each finalize\n"
7638 " -version show SQLite version\n"
7639 " -vfs NAME use NAME as the default VFS\n"
7640#ifdef SQLITE_ENABLE_VFSTRACE
7641 " -vfstrace enable tracing of all VFS calls\n"
7642#endif
7643;
7644static void usage(int showDetail){
7645 utf8_printf(stderr,
7646 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
7647 "FILENAME is the name of an SQLite database. A new database is created\n"
7648 "if the file does not previously exist.\n", Argv0);
7649 if( showDetail ){
7650 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
7651 }else{
7652 raw_printf(stderr, "Use the -help option for additional information\n");
7653 }
7654 exit(1);
7655}
7656
7657/*
7658** Initialize the state information in data
7659*/
7660static void main_init(ShellState *data) {
7661 memset(data, 0, sizeof(*data));
7662 data->normalMode = data->cMode = data->mode = MODE_List;
7663 data->autoExplain = 1;
7664 memcpy(data->colSeparator,SEP_Column, 2);
7665 memcpy(data->rowSeparator,SEP_Row, 2);
7666 data->showHeader = 0;
7667 data->shellFlgs = SHFLG_Lookaside;
7668 sqlite3_config(SQLITE_CONFIG_URI, 1);
7669 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
7670 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
7671 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7672 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
7673}
7674
7675/*
7676** Output text to the console in a font that attracts extra attention.
7677*/
7678#ifdef _WIN32
7679static void printBold(const char *zText){
7680 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7681 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7682 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7683 SetConsoleTextAttribute(out,
7684 FOREGROUND_RED|FOREGROUND_INTENSITY
7685 );
7686 printf("%s", zText);
7687 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
7688}
7689#else
7690static void printBold(const char *zText){
7691 printf("\033[1m%s\033[0m", zText);
7692}
7693#endif
7694
7695/*
7696** Get the argument to an --option. Throw an error and die if no argument
7697** is available.
7698*/
7699static char *cmdline_option_value(int argc, char **argv, int i){
7700 if( i==argc ){
7701 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
7702 argv[0], argv[argc-1]);
7703 exit(1);
7704 }
7705 return argv[i];
7706}
7707
7708#ifndef SQLITE_SHELL_IS_UTF8
7709# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7710# define SQLITE_SHELL_IS_UTF8 (0)
7711# else
7712# define SQLITE_SHELL_IS_UTF8 (1)
7713# endif
7714#endif
7715
7716#if SQLITE_SHELL_IS_UTF8
7717int SQLITE_CDECL main(int argc, char **argv){
7718#else
7719int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
7720 char **argv;
7721#endif
7722 char *zErrMsg = 0;
7723 ShellState data;
7724 const char *zInitFile = 0;
7725 int i;
7726 int rc = 0;
7727 int warnInmemoryDb = 0;
7728 int readStdin = 1;
7729 int nCmd = 0;
7730 char **azCmd = 0;
7731
7732 setBinaryMode(stdin, 0);
7733 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
7734 stdin_is_interactive = isatty(0);
7735 stdout_is_console = isatty(1);
7736
7737#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00007738 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00007739 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
7740 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7741 exit(1);
7742 }
7743#endif
7744 main_init(&data);
7745#if !SQLITE_SHELL_IS_UTF8
7746 sqlite3_initialize();
7747 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7748 if( argv==0 ){
7749 raw_printf(stderr, "out of memory\n");
7750 exit(1);
7751 }
7752 for(i=0; i<argc; i++){
7753 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7754 if( argv[i]==0 ){
7755 raw_printf(stderr, "out of memory\n");
7756 exit(1);
7757 }
7758 }
7759#endif
7760 assert( argc>=1 && argv && argv[0] );
7761 Argv0 = argv[0];
7762
7763 /* Make sure we have a valid signal handler early, before anything
7764 ** else is done.
7765 */
7766#ifdef SIGINT
7767 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00007768#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
7769 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00007770#endif
7771
7772#ifdef SQLITE_SHELL_DBNAME_PROC
7773 {
7774 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7775 ** of a C-function that will provide the name of the database file. Use
7776 ** this compile-time option to embed this shell program in larger
7777 ** applications. */
7778 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7779 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7780 warnInmemoryDb = 0;
7781 }
7782#endif
7783
7784 /* Do an initial pass through the command-line argument to locate
7785 ** the name of the database file, the name of the initialization file,
7786 ** the size of the alternative malloc heap,
7787 ** and the first command to execute.
7788 */
7789 for(i=1; i<argc; i++){
7790 char *z;
7791 z = argv[i];
7792 if( z[0]!='-' ){
7793 if( data.zDbFilename==0 ){
7794 data.zDbFilename = z;
7795 }else{
7796 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7797 ** mean that nothing is read from stdin */
7798 readStdin = 0;
7799 nCmd++;
7800 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7801 if( azCmd==0 ){
7802 raw_printf(stderr, "out of memory\n");
7803 exit(1);
7804 }
7805 azCmd[nCmd-1] = z;
7806 }
7807 }
7808 if( z[1]=='-' ) z++;
7809 if( strcmp(z,"-separator")==0
7810 || strcmp(z,"-nullvalue")==0
7811 || strcmp(z,"-newline")==0
7812 || strcmp(z,"-cmd")==0
7813 ){
7814 (void)cmdline_option_value(argc, argv, ++i);
7815 }else if( strcmp(z,"-init")==0 ){
7816 zInitFile = cmdline_option_value(argc, argv, ++i);
7817 }else if( strcmp(z,"-batch")==0 ){
7818 /* Need to check for batch mode here to so we can avoid printing
7819 ** informational messages (like from process_sqliterc) before
7820 ** we do the actual processing of arguments later in a second pass.
7821 */
7822 stdin_is_interactive = 0;
7823 }else if( strcmp(z,"-heap")==0 ){
7824#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7825 const char *zSize;
7826 sqlite3_int64 szHeap;
7827
7828 zSize = cmdline_option_value(argc, argv, ++i);
7829 szHeap = integerValue(zSize);
7830 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
7831 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
7832#else
7833 (void)cmdline_option_value(argc, argv, ++i);
7834#endif
drh2ce15c32017-07-11 13:34:40 +00007835 }else if( strcmp(z,"-pagecache")==0 ){
7836 int n, sz;
7837 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7838 if( sz>70000 ) sz = 70000;
7839 if( sz<0 ) sz = 0;
7840 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7841 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7842 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
7843 data.shellFlgs |= SHFLG_Pagecache;
7844 }else if( strcmp(z,"-lookaside")==0 ){
7845 int n, sz;
7846 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7847 if( sz<0 ) sz = 0;
7848 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7849 if( n<0 ) n = 0;
7850 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7851 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
7852#ifdef SQLITE_ENABLE_VFSTRACE
7853 }else if( strcmp(z,"-vfstrace")==0 ){
7854 extern int vfstrace_register(
7855 const char *zTraceName,
7856 const char *zOldVfsName,
7857 int (*xOut)(const char*,void*),
7858 void *pOutArg,
7859 int makeDefault
7860 );
7861 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
7862#endif
7863#ifdef SQLITE_ENABLE_MULTIPLEX
7864 }else if( strcmp(z,"-multiplex")==0 ){
7865 extern int sqlite3_multiple_initialize(const char*,int);
7866 sqlite3_multiplex_initialize(0, 1);
7867#endif
7868 }else if( strcmp(z,"-mmap")==0 ){
7869 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7870 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
7871 }else if( strcmp(z,"-vfs")==0 ){
7872 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
7873 if( pVfs ){
7874 sqlite3_vfs_register(pVfs, 1);
7875 }else{
7876 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
7877 exit(1);
7878 }
7879 }
7880 }
7881 if( data.zDbFilename==0 ){
7882#ifndef SQLITE_OMIT_MEMORYDB
7883 data.zDbFilename = ":memory:";
7884 warnInmemoryDb = argc==1;
7885#else
7886 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
7887 return 1;
7888#endif
7889 }
7890 data.out = stdout;
7891
7892 /* Go ahead and open the database file if it already exists. If the
7893 ** file does not exist, delay opening it. This prevents empty database
7894 ** files from being created if a user mistypes the database name argument
7895 ** to the sqlite command-line tool.
7896 */
7897 if( access(data.zDbFilename, 0)==0 ){
7898 open_db(&data, 0);
7899 }
7900
7901 /* Process the initialization file if there is one. If no -init option
7902 ** is given on the command line, look for a file named ~/.sqliterc and
7903 ** try to process it.
7904 */
7905 process_sqliterc(&data,zInitFile);
7906
7907 /* Make a second pass through the command-line argument and set
7908 ** options. This second pass is delayed until after the initialization
7909 ** file is processed so that the command-line arguments will override
7910 ** settings in the initialization file.
7911 */
7912 for(i=1; i<argc; i++){
7913 char *z = argv[i];
7914 if( z[0]!='-' ) continue;
7915 if( z[1]=='-' ){ z++; }
7916 if( strcmp(z,"-init")==0 ){
7917 i++;
7918 }else if( strcmp(z,"-html")==0 ){
7919 data.mode = MODE_Html;
7920 }else if( strcmp(z,"-list")==0 ){
7921 data.mode = MODE_List;
7922 }else if( strcmp(z,"-quote")==0 ){
7923 data.mode = MODE_Quote;
7924 }else if( strcmp(z,"-line")==0 ){
7925 data.mode = MODE_Line;
7926 }else if( strcmp(z,"-column")==0 ){
7927 data.mode = MODE_Column;
7928 }else if( strcmp(z,"-csv")==0 ){
7929 data.mode = MODE_Csv;
7930 memcpy(data.colSeparator,",",2);
7931 }else if( strcmp(z,"-ascii")==0 ){
7932 data.mode = MODE_Ascii;
7933 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
7934 SEP_Unit);
7935 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
7936 SEP_Record);
7937 }else if( strcmp(z,"-separator")==0 ){
7938 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
7939 "%s",cmdline_option_value(argc,argv,++i));
7940 }else if( strcmp(z,"-newline")==0 ){
7941 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
7942 "%s",cmdline_option_value(argc,argv,++i));
7943 }else if( strcmp(z,"-nullvalue")==0 ){
7944 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
7945 "%s",cmdline_option_value(argc,argv,++i));
7946 }else if( strcmp(z,"-header")==0 ){
7947 data.showHeader = 1;
7948 }else if( strcmp(z,"-noheader")==0 ){
7949 data.showHeader = 0;
7950 }else if( strcmp(z,"-echo")==0 ){
7951 ShellSetFlag(&data, SHFLG_Echo);
7952 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +00007953 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +00007954 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +00007955 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +00007956 }else if( strcmp(z,"-stats")==0 ){
7957 data.statsOn = 1;
7958 }else if( strcmp(z,"-scanstats")==0 ){
7959 data.scanstatsOn = 1;
7960 }else if( strcmp(z,"-backslash")==0 ){
7961 /* Undocumented command-line option: -backslash
7962 ** Causes C-style backslash escapes to be evaluated in SQL statements
7963 ** prior to sending the SQL into SQLite. Useful for injecting
7964 ** crazy bytes in the middle of SQL statements for testing and debugging.
7965 */
7966 ShellSetFlag(&data, SHFLG_Backslash);
7967 }else if( strcmp(z,"-bail")==0 ){
7968 bail_on_error = 1;
7969 }else if( strcmp(z,"-version")==0 ){
7970 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
7971 return 0;
7972 }else if( strcmp(z,"-interactive")==0 ){
7973 stdin_is_interactive = 1;
7974 }else if( strcmp(z,"-batch")==0 ){
7975 stdin_is_interactive = 0;
7976 }else if( strcmp(z,"-heap")==0 ){
7977 i++;
drh2ce15c32017-07-11 13:34:40 +00007978 }else if( strcmp(z,"-pagecache")==0 ){
7979 i+=2;
7980 }else if( strcmp(z,"-lookaside")==0 ){
7981 i+=2;
7982 }else if( strcmp(z,"-mmap")==0 ){
7983 i++;
7984 }else if( strcmp(z,"-vfs")==0 ){
7985 i++;
7986#ifdef SQLITE_ENABLE_VFSTRACE
7987 }else if( strcmp(z,"-vfstrace")==0 ){
7988 i++;
7989#endif
7990#ifdef SQLITE_ENABLE_MULTIPLEX
7991 }else if( strcmp(z,"-multiplex")==0 ){
7992 i++;
7993#endif
7994 }else if( strcmp(z,"-help")==0 ){
7995 usage(1);
7996 }else if( strcmp(z,"-cmd")==0 ){
7997 /* Run commands that follow -cmd first and separately from commands
7998 ** that simply appear on the command-line. This seems goofy. It would
7999 ** be better if all commands ran in the order that they appear. But
8000 ** we retain the goofy behavior for historical compatibility. */
8001 if( i==argc-1 ) break;
8002 z = cmdline_option_value(argc,argv,++i);
8003 if( z[0]=='.' ){
8004 rc = do_meta_command(z, &data);
8005 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
8006 }else{
8007 open_db(&data, 0);
8008 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
8009 if( zErrMsg!=0 ){
8010 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8011 if( bail_on_error ) return rc!=0 ? rc : 1;
8012 }else if( rc!=0 ){
8013 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
8014 if( bail_on_error ) return rc;
8015 }
8016 }
8017 }else{
8018 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
8019 raw_printf(stderr,"Use -help for a list of options.\n");
8020 return 1;
8021 }
8022 data.cMode = data.mode;
8023 }
8024
8025 if( !readStdin ){
8026 /* Run all arguments that do not begin with '-' as if they were separate
8027 ** command-line inputs, except for the argToSkip argument which contains
8028 ** the database filename.
8029 */
8030 for(i=0; i<nCmd; i++){
8031 if( azCmd[i][0]=='.' ){
8032 rc = do_meta_command(azCmd[i], &data);
8033 if( rc ) return rc==2 ? 0 : rc;
8034 }else{
8035 open_db(&data, 0);
8036 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
8037 if( zErrMsg!=0 ){
8038 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8039 return rc!=0 ? rc : 1;
8040 }else if( rc!=0 ){
8041 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
8042 return rc;
8043 }
8044 }
8045 }
8046 free(azCmd);
8047 }else{
8048 /* Run commands received from standard input
8049 */
8050 if( stdin_is_interactive ){
8051 char *zHome;
8052 char *zHistory = 0;
8053 int nHistory;
8054 printf(
8055 "SQLite version %s %.19s\n" /*extra-version-info*/
8056 "Enter \".help\" for usage hints.\n",
8057 sqlite3_libversion(), sqlite3_sourceid()
8058 );
8059 if( warnInmemoryDb ){
8060 printf("Connected to a ");
8061 printBold("transient in-memory database");
8062 printf(".\nUse \".open FILENAME\" to reopen on a "
8063 "persistent database.\n");
8064 }
8065 zHome = find_home_dir(0);
8066 if( zHome ){
8067 nHistory = strlen30(zHome) + 20;
8068 if( (zHistory = malloc(nHistory))!=0 ){
8069 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8070 }
8071 }
8072 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +00008073#if HAVE_READLINE || HAVE_EDITLINE
8074 rl_attempted_completion_function = readline_completion;
8075#elif HAVE_LINENOISE
8076 linenoiseSetCompletionCallback(linenoise_completion);
8077#endif
drh2ce15c32017-07-11 13:34:40 +00008078 rc = process_input(&data, 0);
8079 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +00008080 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +00008081 shell_write_history(zHistory);
8082 free(zHistory);
8083 }
8084 }else{
8085 rc = process_input(&data, stdin);
8086 }
8087 }
8088 set_table_name(&data, 0);
8089 if( data.db ){
8090 session_close_all(&data);
8091 sqlite3_close(data.db);
8092 }
8093 sqlite3_free(data.zFreeOnClose);
8094 find_home_dir(1);
8095#if !SQLITE_SHELL_IS_UTF8
8096 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
8097 sqlite3_free(argv);
8098#endif
8099 return rc;
8100}