blob: bb4428fbc540f477ddd797728c125052e0f6351a [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/*
1415** This is the callback routine that the shell
1416** invokes for each row of a query result.
1417*/
1418static int shell_callback(
1419 void *pArg,
1420 int nArg, /* Number of result columns */
1421 char **azArg, /* Text of each result column */
1422 char **azCol, /* Column names */
1423 int *aiType /* Column types */
1424){
1425 int i;
1426 ShellState *p = (ShellState*)pArg;
1427
drhb3c45232017-08-28 14:33:27 +00001428 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001429 switch( p->cMode ){
1430 case MODE_Line: {
1431 int w = 5;
1432 if( azArg==0 ) break;
1433 for(i=0; i<nArg; i++){
1434 int len = strlen30(azCol[i] ? azCol[i] : "");
1435 if( len>w ) w = len;
1436 }
1437 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
1438 for(i=0; i<nArg; i++){
1439 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
1440 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
1441 }
1442 break;
1443 }
1444 case MODE_Explain:
1445 case MODE_Column: {
1446 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1447 const int *colWidth;
1448 int showHdr;
1449 char *rowSep;
1450 if( p->cMode==MODE_Column ){
1451 colWidth = p->colWidth;
1452 showHdr = p->showHeader;
1453 rowSep = p->rowSeparator;
1454 }else{
1455 colWidth = aExplainWidths;
1456 showHdr = 1;
1457 rowSep = SEP_Row;
1458 }
1459 if( p->cnt++==0 ){
1460 for(i=0; i<nArg; i++){
1461 int w, n;
1462 if( i<ArraySize(p->colWidth) ){
1463 w = colWidth[i];
1464 }else{
1465 w = 0;
1466 }
1467 if( w==0 ){
1468 w = strlenChar(azCol[i] ? azCol[i] : "");
1469 if( w<10 ) w = 10;
1470 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
1471 if( w<n ) w = n;
1472 }
1473 if( i<ArraySize(p->actualWidth) ){
1474 p->actualWidth[i] = w;
1475 }
1476 if( showHdr ){
1477 utf8_width_print(p->out, w, azCol[i]);
1478 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1479 }
1480 }
1481 if( showHdr ){
1482 for(i=0; i<nArg; i++){
1483 int w;
1484 if( i<ArraySize(p->actualWidth) ){
1485 w = p->actualWidth[i];
1486 if( w<0 ) w = -w;
1487 }else{
1488 w = 10;
1489 }
1490 utf8_printf(p->out,"%-*.*s%s",w,w,
1491 "----------------------------------------------------------"
1492 "----------------------------------------------------------",
1493 i==nArg-1 ? rowSep : " ");
1494 }
1495 }
1496 }
1497 if( azArg==0 ) break;
1498 for(i=0; i<nArg; i++){
1499 int w;
1500 if( i<ArraySize(p->actualWidth) ){
1501 w = p->actualWidth[i];
1502 }else{
1503 w = 10;
1504 }
1505 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1506 w = strlenChar(azArg[i]);
1507 }
1508 if( i==1 && p->aiIndent && p->pStmt ){
1509 if( p->iIndent<p->nIndent ){
1510 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1511 }
1512 p->iIndent++;
1513 }
1514 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1515 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
1516 }
1517 break;
1518 }
1519 case MODE_Semi: { /* .schema and .fullschema output */
1520 printSchemaLine(p->out, azArg[0], ";\n");
1521 break;
1522 }
1523 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1524 char *z;
1525 int j;
1526 int nParen = 0;
1527 char cEnd = 0;
1528 char c;
1529 int nLine = 0;
1530 assert( nArg==1 );
1531 if( azArg[0]==0 ) break;
1532 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1533 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1534 ){
1535 utf8_printf(p->out, "%s;\n", azArg[0]);
1536 break;
1537 }
1538 z = sqlite3_mprintf("%s", azArg[0]);
1539 j = 0;
1540 for(i=0; IsSpace(z[i]); i++){}
1541 for(; (c = z[i])!=0; i++){
1542 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00001543 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh2ce15c32017-07-11 13:34:40 +00001544 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1545 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1546 j--;
1547 }
1548 z[j++] = c;
1549 }
1550 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1551 z[j] = 0;
1552 if( strlen30(z)>=79 ){
1553 for(i=j=0; (c = z[i])!=0; i++){
1554 if( c==cEnd ){
1555 cEnd = 0;
1556 }else if( c=='"' || c=='\'' || c=='`' ){
1557 cEnd = c;
1558 }else if( c=='[' ){
1559 cEnd = ']';
1560 }else if( c=='(' ){
1561 nParen++;
1562 }else if( c==')' ){
1563 nParen--;
1564 if( nLine>0 && nParen==0 && j>0 ){
1565 printSchemaLineN(p->out, z, j, "\n");
1566 j = 0;
1567 }
1568 }
1569 z[j++] = c;
1570 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
1571 if( c=='\n' ) j--;
1572 printSchemaLineN(p->out, z, j, "\n ");
1573 j = 0;
1574 nLine++;
1575 while( IsSpace(z[i+1]) ){ i++; }
1576 }
1577 }
1578 z[j] = 0;
1579 }
1580 printSchemaLine(p->out, z, ";\n");
1581 sqlite3_free(z);
1582 break;
1583 }
1584 case MODE_List: {
1585 if( p->cnt++==0 && p->showHeader ){
1586 for(i=0; i<nArg; i++){
1587 utf8_printf(p->out,"%s%s",azCol[i],
1588 i==nArg-1 ? p->rowSeparator : p->colSeparator);
1589 }
1590 }
1591 if( azArg==0 ) break;
1592 for(i=0; i<nArg; i++){
1593 char *z = azArg[i];
1594 if( z==0 ) z = p->nullValue;
1595 utf8_printf(p->out, "%s", z);
1596 if( i<nArg-1 ){
1597 utf8_printf(p->out, "%s", p->colSeparator);
1598 }else{
1599 utf8_printf(p->out, "%s", p->rowSeparator);
1600 }
1601 }
1602 break;
1603 }
1604 case MODE_Html: {
1605 if( p->cnt++==0 && p->showHeader ){
1606 raw_printf(p->out,"<TR>");
1607 for(i=0; i<nArg; i++){
1608 raw_printf(p->out,"<TH>");
1609 output_html_string(p->out, azCol[i]);
1610 raw_printf(p->out,"</TH>\n");
1611 }
1612 raw_printf(p->out,"</TR>\n");
1613 }
1614 if( azArg==0 ) break;
1615 raw_printf(p->out,"<TR>");
1616 for(i=0; i<nArg; i++){
1617 raw_printf(p->out,"<TD>");
1618 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1619 raw_printf(p->out,"</TD>\n");
1620 }
1621 raw_printf(p->out,"</TR>\n");
1622 break;
1623 }
1624 case MODE_Tcl: {
1625 if( p->cnt++==0 && p->showHeader ){
1626 for(i=0; i<nArg; i++){
1627 output_c_string(p->out,azCol[i] ? azCol[i] : "");
1628 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1629 }
1630 utf8_printf(p->out, "%s", p->rowSeparator);
1631 }
1632 if( azArg==0 ) break;
1633 for(i=0; i<nArg; i++){
1634 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1635 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1636 }
1637 utf8_printf(p->out, "%s", p->rowSeparator);
1638 break;
1639 }
1640 case MODE_Csv: {
1641 setBinaryMode(p->out, 1);
1642 if( p->cnt++==0 && p->showHeader ){
1643 for(i=0; i<nArg; i++){
1644 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1645 }
1646 utf8_printf(p->out, "%s", p->rowSeparator);
1647 }
1648 if( nArg>0 ){
1649 for(i=0; i<nArg; i++){
1650 output_csv(p, azArg[i], i<nArg-1);
1651 }
1652 utf8_printf(p->out, "%s", p->rowSeparator);
1653 }
1654 setTextMode(p->out, 1);
1655 break;
1656 }
1657 case MODE_Insert: {
1658 if( azArg==0 ) break;
1659 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
1660 if( p->showHeader ){
1661 raw_printf(p->out,"(");
1662 for(i=0; i<nArg; i++){
1663 if( i>0 ) raw_printf(p->out, ",");
1664 if( quoteChar(azCol[i]) ){
1665 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
1666 utf8_printf(p->out, "%s", z);
1667 sqlite3_free(z);
1668 }else{
1669 raw_printf(p->out, "%s", azCol[i]);
1670 }
1671 }
1672 raw_printf(p->out,")");
1673 }
1674 p->cnt++;
1675 for(i=0; i<nArg; i++){
1676 raw_printf(p->out, i>0 ? "," : " VALUES(");
1677 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1678 utf8_printf(p->out,"NULL");
1679 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1680 if( ShellHasFlag(p, SHFLG_Newlines) ){
1681 output_quoted_string(p->out, azArg[i]);
1682 }else{
1683 output_quoted_escaped_string(p->out, azArg[i]);
1684 }
1685 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1686 utf8_printf(p->out,"%s", azArg[i]);
1687 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1688 char z[50];
1689 double r = sqlite3_column_double(p->pStmt, i);
1690 sqlite3_snprintf(50,z,"%!.20g", r);
1691 raw_printf(p->out, "%s", z);
1692 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1693 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1694 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1695 output_hex_blob(p->out, pBlob, nBlob);
1696 }else if( isNumber(azArg[i], 0) ){
1697 utf8_printf(p->out,"%s", azArg[i]);
1698 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
1699 output_quoted_string(p->out, azArg[i]);
1700 }else{
1701 output_quoted_escaped_string(p->out, azArg[i]);
1702 }
1703 }
1704 raw_printf(p->out,");\n");
1705 break;
1706 }
1707 case MODE_Quote: {
1708 if( azArg==0 ) break;
1709 if( p->cnt==0 && p->showHeader ){
1710 for(i=0; i<nArg; i++){
1711 if( i>0 ) raw_printf(p->out, ",");
1712 output_quoted_string(p->out, azCol[i]);
1713 }
1714 raw_printf(p->out,"\n");
1715 }
1716 p->cnt++;
1717 for(i=0; i<nArg; i++){
1718 if( i>0 ) raw_printf(p->out, ",");
1719 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1720 utf8_printf(p->out,"NULL");
1721 }else if( aiType && aiType[i]==SQLITE_TEXT ){
1722 output_quoted_string(p->out, azArg[i]);
1723 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
1724 utf8_printf(p->out,"%s", azArg[i]);
1725 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
1726 char z[50];
1727 double r = sqlite3_column_double(p->pStmt, i);
1728 sqlite3_snprintf(50,z,"%!.20g", r);
1729 raw_printf(p->out, "%s", z);
1730 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1731 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1732 int nBlob = sqlite3_column_bytes(p->pStmt, i);
1733 output_hex_blob(p->out, pBlob, nBlob);
1734 }else if( isNumber(azArg[i], 0) ){
1735 utf8_printf(p->out,"%s", azArg[i]);
1736 }else{
1737 output_quoted_string(p->out, azArg[i]);
1738 }
1739 }
1740 raw_printf(p->out,"\n");
1741 break;
1742 }
1743 case MODE_Ascii: {
1744 if( p->cnt++==0 && p->showHeader ){
1745 for(i=0; i<nArg; i++){
1746 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1747 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
1748 }
1749 utf8_printf(p->out, "%s", p->rowSeparator);
1750 }
1751 if( azArg==0 ) break;
1752 for(i=0; i<nArg; i++){
1753 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1754 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
1755 }
1756 utf8_printf(p->out, "%s", p->rowSeparator);
1757 break;
1758 }
1759 }
1760 return 0;
1761}
1762
1763/*
1764** This is the callback routine that the SQLite library
1765** invokes for each row of a query result.
1766*/
1767static int callback(void *pArg, int nArg, char **azArg, char **azCol){
1768 /* since we don't have type info, call the shell_callback with a NULL value */
1769 return shell_callback(pArg, nArg, azArg, azCol, NULL);
1770}
1771
1772/*
1773** This is the callback routine from sqlite3_exec() that appends all
1774** output onto the end of a ShellText object.
1775*/
1776static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
1777 ShellText *p = (ShellText*)pArg;
1778 int i;
1779 UNUSED_PARAMETER(az);
drhb3c45232017-08-28 14:33:27 +00001780 if( azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00001781 if( p->n ) appendText(p, "|", 0);
1782 for(i=0; i<nArg; i++){
1783 if( i ) appendText(p, ",", 0);
1784 if( azArg[i] ) appendText(p, azArg[i], 0);
1785 }
1786 return 0;
1787}
1788
1789/*
1790** Generate an appropriate SELFTEST table in the main database.
1791*/
1792static void createSelftestTable(ShellState *p){
1793 char *zErrMsg = 0;
1794 sqlite3_exec(p->db,
1795 "SAVEPOINT selftest_init;\n"
1796 "CREATE TABLE IF NOT EXISTS selftest(\n"
1797 " tno INTEGER PRIMARY KEY,\n" /* Test number */
1798 " op TEXT,\n" /* Operator: memo run */
1799 " cmd TEXT,\n" /* Command text */
1800 " ans TEXT\n" /* Desired answer */
1801 ");"
1802 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
1803 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
1804 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
1805 " 'memo','Tests generated by --init');\n"
1806 "INSERT INTO [_shell$self]\n"
1807 " SELECT 'run',\n"
1808 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
1809 "FROM sqlite_master ORDER BY 2'',224))',\n"
1810 " hex(sha3_query('SELECT type,name,tbl_name,sql "
1811 "FROM sqlite_master ORDER BY 2',224));\n"
1812 "INSERT INTO [_shell$self]\n"
1813 " SELECT 'run',"
1814 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
1815 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
1816 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
1817 " FROM (\n"
1818 " SELECT name FROM sqlite_master\n"
1819 " WHERE type='table'\n"
1820 " AND name<>'selftest'\n"
1821 " AND coalesce(rootpage,0)>0\n"
1822 " )\n"
1823 " ORDER BY name;\n"
1824 "INSERT INTO [_shell$self]\n"
1825 " VALUES('run','PRAGMA integrity_check','ok');\n"
1826 "INSERT INTO selftest(tno,op,cmd,ans)"
1827 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
1828 "DROP TABLE [_shell$self];"
1829 ,0,0,&zErrMsg);
1830 if( zErrMsg ){
1831 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
1832 sqlite3_free(zErrMsg);
1833 }
1834 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
1835}
1836
1837
1838/*
1839** Set the destination table field of the ShellState structure to
1840** the name of the table given. Escape any quote characters in the
1841** table name.
1842*/
1843static void set_table_name(ShellState *p, const char *zName){
1844 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00001845 char cQuote;
drh2ce15c32017-07-11 13:34:40 +00001846 char *z;
1847
1848 if( p->zDestTable ){
1849 free(p->zDestTable);
1850 p->zDestTable = 0;
1851 }
1852 if( zName==0 ) return;
1853 cQuote = quoteChar(zName);
1854 n = strlen30(zName);
1855 if( cQuote ) n += n+2;
1856 z = p->zDestTable = malloc( n+1 );
1857 if( z==0 ){
1858 raw_printf(stderr,"Error: out of memory\n");
1859 exit(1);
1860 }
1861 n = 0;
1862 if( cQuote ) z[n++] = cQuote;
1863 for(i=0; zName[i]; i++){
1864 z[n++] = zName[i];
1865 if( zName[i]==cQuote ) z[n++] = cQuote;
1866 }
1867 if( cQuote ) z[n++] = cQuote;
1868 z[n] = 0;
1869}
1870
1871
1872/*
1873** Execute a query statement that will generate SQL output. Print
1874** the result columns, comma-separated, on a line and then add a
1875** semicolon terminator to the end of that line.
1876**
1877** If the number of columns is 1 and that column contains text "--"
1878** then write the semicolon on a separate line. That way, if a
1879** "--" comment occurs at the end of the statement, the comment
1880** won't consume the semicolon terminator.
1881*/
1882static int run_table_dump_query(
1883 ShellState *p, /* Query context */
1884 const char *zSelect, /* SELECT statement to extract content */
1885 const char *zFirstRow /* Print before first row, if not NULL */
1886){
1887 sqlite3_stmt *pSelect;
1888 int rc;
1889 int nResult;
1890 int i;
1891 const char *z;
1892 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
1893 if( rc!=SQLITE_OK || !pSelect ){
1894 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1895 sqlite3_errmsg(p->db));
1896 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1897 return rc;
1898 }
1899 rc = sqlite3_step(pSelect);
1900 nResult = sqlite3_column_count(pSelect);
1901 while( rc==SQLITE_ROW ){
1902 if( zFirstRow ){
1903 utf8_printf(p->out, "%s", zFirstRow);
1904 zFirstRow = 0;
1905 }
1906 z = (const char*)sqlite3_column_text(pSelect, 0);
1907 utf8_printf(p->out, "%s", z);
1908 for(i=1; i<nResult; i++){
1909 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
1910 }
1911 if( z==0 ) z = "";
1912 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
1913 if( z[0] ){
1914 raw_printf(p->out, "\n;\n");
1915 }else{
1916 raw_printf(p->out, ";\n");
1917 }
1918 rc = sqlite3_step(pSelect);
1919 }
1920 rc = sqlite3_finalize(pSelect);
1921 if( rc!=SQLITE_OK ){
1922 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1923 sqlite3_errmsg(p->db));
1924 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1925 }
1926 return rc;
1927}
1928
1929/*
1930** Allocate space and save off current error string.
1931*/
1932static char *save_err_msg(
1933 sqlite3 *db /* Database to query */
1934){
1935 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
1936 char *zErrMsg = sqlite3_malloc64(nErrMsg);
1937 if( zErrMsg ){
1938 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
1939 }
1940 return zErrMsg;
1941}
1942
1943#ifdef __linux__
1944/*
1945** Attempt to display I/O stats on Linux using /proc/PID/io
1946*/
1947static void displayLinuxIoStats(FILE *out){
1948 FILE *in;
1949 char z[200];
1950 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
1951 in = fopen(z, "rb");
1952 if( in==0 ) return;
1953 while( fgets(z, sizeof(z), in)!=0 ){
1954 static const struct {
1955 const char *zPattern;
1956 const char *zDesc;
1957 } aTrans[] = {
1958 { "rchar: ", "Bytes received by read():" },
1959 { "wchar: ", "Bytes sent to write():" },
1960 { "syscr: ", "Read() system calls:" },
1961 { "syscw: ", "Write() system calls:" },
1962 { "read_bytes: ", "Bytes read from storage:" },
1963 { "write_bytes: ", "Bytes written to storage:" },
1964 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
1965 };
1966 int i;
1967 for(i=0; i<ArraySize(aTrans); i++){
drhaf2770f2018-01-05 14:55:43 +00001968 int n = strlen30(aTrans[i].zPattern);
drh2ce15c32017-07-11 13:34:40 +00001969 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
1970 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
1971 break;
1972 }
1973 }
1974 }
1975 fclose(in);
1976}
1977#endif
1978
1979/*
1980** Display a single line of status using 64-bit values.
1981*/
1982static void displayStatLine(
1983 ShellState *p, /* The shell context */
1984 char *zLabel, /* Label for this one line */
1985 char *zFormat, /* Format for the result */
1986 int iStatusCtrl, /* Which status to display */
1987 int bReset /* True to reset the stats */
1988){
1989 sqlite3_int64 iCur = -1;
1990 sqlite3_int64 iHiwtr = -1;
1991 int i, nPercent;
1992 char zLine[200];
1993 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
1994 for(i=0, nPercent=0; zFormat[i]; i++){
1995 if( zFormat[i]=='%' ) nPercent++;
1996 }
1997 if( nPercent>1 ){
1998 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
1999 }else{
2000 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2001 }
2002 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2003}
2004
2005/*
2006** Display memory stats.
2007*/
2008static int display_stats(
2009 sqlite3 *db, /* Database to query */
2010 ShellState *pArg, /* Pointer to ShellState */
2011 int bReset /* True to reset the stats */
2012){
2013 int iCur;
2014 int iHiwtr;
2015
2016 if( pArg && pArg->out ){
2017 displayStatLine(pArg, "Memory Used:",
2018 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2019 displayStatLine(pArg, "Number of Outstanding Allocations:",
2020 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
2021 if( pArg->shellFlgs & SHFLG_Pagecache ){
2022 displayStatLine(pArg, "Number of Pcache Pages Used:",
2023 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
2024 }
2025 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2026 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
drh2ce15c32017-07-11 13:34:40 +00002027 displayStatLine(pArg, "Largest Allocation:",
2028 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2029 displayStatLine(pArg, "Largest Pcache Allocation:",
2030 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
drh2ce15c32017-07-11 13:34:40 +00002031#ifdef YYTRACKMAXSTACKDEPTH
2032 displayStatLine(pArg, "Deepest Parser Stack:",
2033 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
2034#endif
2035 }
2036
2037 if( pArg && pArg->out && db ){
2038 if( pArg->shellFlgs & SHFLG_Lookaside ){
2039 iHiwtr = iCur = -1;
2040 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2041 &iCur, &iHiwtr, bReset);
2042 raw_printf(pArg->out,
2043 "Lookaside Slots Used: %d (max %d)\n",
2044 iCur, iHiwtr);
2045 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2046 &iCur, &iHiwtr, bReset);
2047 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2048 iHiwtr);
2049 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2050 &iCur, &iHiwtr, bReset);
2051 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2052 iHiwtr);
2053 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2054 &iCur, &iHiwtr, bReset);
2055 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2056 iHiwtr);
2057 }
2058 iHiwtr = iCur = -1;
2059 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2060 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2061 iCur);
2062 iHiwtr = iCur = -1;
2063 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2064 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2065 iHiwtr = iCur = -1;
2066 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2067 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2068 iHiwtr = iCur = -1;
2069 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2070 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2071 iHiwtr = iCur = -1;
2072 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2073 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2074 iCur);
2075 iHiwtr = iCur = -1;
2076 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2077 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2078 iCur);
2079 }
2080
2081 if( pArg && pArg->out && db && pArg->pStmt ){
2082 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2083 bReset);
2084 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2085 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2086 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2087 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2088 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2089 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2090 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2091 }
2092
2093#ifdef __linux__
2094 displayLinuxIoStats(pArg->out);
2095#endif
2096
2097 /* Do not remove this machine readable comment: extra-stats-output-here */
2098
2099 return 0;
2100}
2101
2102/*
2103** Display scan stats.
2104*/
2105static void display_scanstats(
2106 sqlite3 *db, /* Database to query */
2107 ShellState *pArg /* Pointer to ShellState */
2108){
2109#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2110 UNUSED_PARAMETER(db);
2111 UNUSED_PARAMETER(pArg);
2112#else
2113 int i, k, n, mx;
2114 raw_printf(pArg->out, "-------- scanstats --------\n");
2115 mx = 0;
2116 for(k=0; k<=mx; k++){
2117 double rEstLoop = 1.0;
2118 for(i=n=0; 1; i++){
2119 sqlite3_stmt *p = pArg->pStmt;
2120 sqlite3_int64 nLoop, nVisit;
2121 double rEst;
2122 int iSid;
2123 const char *zExplain;
2124 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2125 break;
2126 }
2127 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
2128 if( iSid>mx ) mx = iSid;
2129 if( iSid!=k ) continue;
2130 if( n==0 ){
2131 rEstLoop = (double)nLoop;
2132 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2133 }
2134 n++;
2135 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2136 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2137 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2138 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2139 rEstLoop *= rEst;
2140 raw_printf(pArg->out,
2141 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2142 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
2143 );
2144 }
2145 }
2146 raw_printf(pArg->out, "---------------------------\n");
2147#endif
2148}
2149
2150/*
2151** Parameter azArray points to a zero-terminated array of strings. zStr
2152** points to a single nul-terminated string. Return non-zero if zStr
2153** is equal, according to strcmp(), to any of the strings in the array.
2154** Otherwise, return zero.
2155*/
2156static int str_in_array(const char *zStr, const char **azArray){
2157 int i;
2158 for(i=0; azArray[i]; i++){
2159 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2160 }
2161 return 0;
2162}
2163
2164/*
2165** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2166** and populate the ShellState.aiIndent[] array with the number of
2167** spaces each opcode should be indented before it is output.
2168**
2169** The indenting rules are:
2170**
2171** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2172** all opcodes that occur between the p2 jump destination and the opcode
2173** itself by 2 spaces.
2174**
2175** * For each "Goto", if the jump destination is earlier in the program
2176** and ends on one of:
2177** Yield SeekGt SeekLt RowSetRead Rewind
2178** or if the P1 parameter is one instead of zero,
2179** then indent all opcodes between the earlier instruction
2180** and "Goto" by 2 spaces.
2181*/
2182static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2183 const char *zSql; /* The text of the SQL statement */
2184 const char *z; /* Used to check if this is an EXPLAIN */
2185 int *abYield = 0; /* True if op is an OP_Yield */
2186 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
2187 int iOp; /* Index of operation in p->aiIndent[] */
2188
2189 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2190 "NextIfOpen", "PrevIfOpen", 0 };
2191 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2192 "Rewind", 0 };
2193 const char *azGoto[] = { "Goto", 0 };
2194
2195 /* Try to figure out if this is really an EXPLAIN statement. If this
2196 ** cannot be verified, return early. */
2197 if( sqlite3_column_count(pSql)!=8 ){
2198 p->cMode = p->mode;
2199 return;
2200 }
2201 zSql = sqlite3_sql(pSql);
2202 if( zSql==0 ) return;
2203 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2204 if( sqlite3_strnicmp(z, "explain", 7) ){
2205 p->cMode = p->mode;
2206 return;
2207 }
2208
2209 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2210 int i;
2211 int iAddr = sqlite3_column_int(pSql, 0);
2212 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
2213
2214 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2215 ** p2 is an instruction address, set variable p2op to the index of that
2216 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2217 ** the current instruction is part of a sub-program generated by an
2218 ** SQL trigger or foreign key. */
2219 int p2 = sqlite3_column_int(pSql, 3);
2220 int p2op = (p2 + (iOp-iAddr));
2221
2222 /* Grow the p->aiIndent array as required */
2223 if( iOp>=nAlloc ){
2224 if( iOp==0 ){
2225 /* Do further verfication that this is explain output. Abort if
2226 ** it is not */
2227 static const char *explainCols[] = {
2228 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2229 int jj;
2230 for(jj=0; jj<ArraySize(explainCols); jj++){
2231 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2232 p->cMode = p->mode;
2233 sqlite3_reset(pSql);
2234 return;
2235 }
2236 }
2237 }
2238 nAlloc += 100;
2239 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2240 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2241 }
2242 abYield[iOp] = str_in_array(zOp, azYield);
2243 p->aiIndent[iOp] = 0;
2244 p->nIndent = iOp+1;
2245
2246 if( str_in_array(zOp, azNext) ){
2247 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2248 }
2249 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2250 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2251 ){
2252 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2253 }
2254 }
2255
2256 p->iIndent = 0;
2257 sqlite3_free(abYield);
2258 sqlite3_reset(pSql);
2259}
2260
2261/*
2262** Free the array allocated by explain_data_prepare().
2263*/
2264static void explain_data_delete(ShellState *p){
2265 sqlite3_free(p->aiIndent);
2266 p->aiIndent = 0;
2267 p->nIndent = 0;
2268 p->iIndent = 0;
2269}
2270
2271/*
2272** Disable and restore .wheretrace and .selecttrace settings.
2273*/
2274#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2275extern int sqlite3SelectTrace;
2276static int savedSelectTrace;
2277#endif
2278#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2279extern int sqlite3WhereTrace;
2280static int savedWhereTrace;
2281#endif
2282static void disable_debug_trace_modes(void){
2283#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2284 savedSelectTrace = sqlite3SelectTrace;
2285 sqlite3SelectTrace = 0;
2286#endif
2287#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2288 savedWhereTrace = sqlite3WhereTrace;
2289 sqlite3WhereTrace = 0;
2290#endif
2291}
2292static void restore_debug_trace_modes(void){
2293#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2294 sqlite3SelectTrace = savedSelectTrace;
2295#endif
2296#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2297 sqlite3WhereTrace = savedWhereTrace;
2298#endif
2299}
2300
2301/*
2302** Run a prepared statement
2303*/
2304static void exec_prepared_stmt(
2305 ShellState *pArg, /* Pointer to ShellState */
2306 sqlite3_stmt *pStmt, /* Statment to run */
2307 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2308){
2309 int rc;
2310
2311 /* perform the first step. this will tell us if we
2312 ** have a result set or not and how wide it is.
2313 */
2314 rc = sqlite3_step(pStmt);
2315 /* if we have a result set... */
2316 if( SQLITE_ROW == rc ){
2317 /* if we have a callback... */
2318 if( xCallback ){
2319 /* allocate space for col name ptr, value ptr, and type */
2320 int nCol = sqlite3_column_count(pStmt);
2321 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2322 if( !pData ){
2323 rc = SQLITE_NOMEM;
2324 }else{
2325 char **azCols = (char **)pData; /* Names of result columns */
2326 char **azVals = &azCols[nCol]; /* Results */
2327 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2328 int i, x;
2329 assert(sizeof(int) <= sizeof(char *));
2330 /* save off ptrs to column names */
2331 for(i=0; i<nCol; i++){
2332 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2333 }
2334 do{
2335 /* extract the data and data types */
2336 for(i=0; i<nCol; i++){
2337 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2338 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2339 azVals[i] = "";
2340 }else{
2341 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2342 }
2343 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2344 rc = SQLITE_NOMEM;
2345 break; /* from for */
2346 }
2347 } /* end for */
2348
2349 /* if data and types extracted successfully... */
2350 if( SQLITE_ROW == rc ){
2351 /* call the supplied callback with the result row data */
2352 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2353 rc = SQLITE_ABORT;
2354 }else{
2355 rc = sqlite3_step(pStmt);
2356 }
2357 }
2358 } while( SQLITE_ROW == rc );
2359 sqlite3_free(pData);
2360 }
2361 }else{
2362 do{
2363 rc = sqlite3_step(pStmt);
2364 } while( rc == SQLITE_ROW );
2365 }
2366 }
2367}
2368
2369/*
dan43efc182017-12-19 17:42:13 +00002370** This function is called to process SQL if the previous shell command
2371** was ".expert". It passes the SQL in the second argument directly to
2372** the sqlite3expert object.
2373**
2374** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2375** code. In this case, (*pzErr) may be set to point to a buffer containing
2376** an English language error message. It is the responsibility of the
2377** caller to eventually free this buffer using sqlite3_free().
2378*/
2379static int expertHandleSQL(
2380 ShellState *pState,
2381 const char *zSql,
2382 char **pzErr
2383){
2384 assert( pState->expert.pExpert );
2385 assert( pzErr==0 || *pzErr==0 );
2386 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
2387}
2388
2389/*
2390** This function is called either to silently clean up the object
2391** created by the ".expert" command (if bCancel==1), or to generate a
2392** report from it and then clean it up (if bCancel==0).
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 expertFinish(
2400 ShellState *pState,
2401 int bCancel,
2402 char **pzErr
2403){
2404 int rc = SQLITE_OK;
2405 sqlite3expert *p = pState->expert.pExpert;
2406 assert( p );
2407 assert( bCancel || pzErr==0 || *pzErr==0 );
2408 if( bCancel==0 ){
2409 FILE *out = pState->out;
2410 int bVerbose = pState->expert.bVerbose;
2411
2412 rc = sqlite3_expert_analyze(p, pzErr);
2413 if( rc==SQLITE_OK ){
2414 int nQuery = sqlite3_expert_count(p);
2415 int i;
2416
2417 if( bVerbose ){
2418 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
2419 raw_printf(out, "-- Candidates -----------------------------\n");
2420 raw_printf(out, "%s\n", zCand);
2421 }
2422 for(i=0; i<nQuery; i++){
2423 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
2424 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
2425 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
2426 if( zIdx==0 ) zIdx = "(no new indexes)\n";
2427 if( bVerbose ){
2428 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
2429 raw_printf(out, "%s\n\n", zSql);
2430 }
2431 raw_printf(out, "%s\n", zIdx);
2432 raw_printf(out, "%s\n", zEQP);
2433 }
2434 }
2435 }
2436 sqlite3_expert_destroy(p);
2437 pState->expert.pExpert = 0;
2438 return rc;
2439}
2440
2441
2442/*
drh2ce15c32017-07-11 13:34:40 +00002443** Execute a statement or set of statements. Print
2444** any result rows/columns depending on the current mode
2445** set via the supplied callback.
2446**
2447** This is very similar to SQLite's built-in sqlite3_exec()
2448** function except it takes a slightly different callback
2449** and callback data argument.
2450*/
2451static int shell_exec(
2452 sqlite3 *db, /* An open database */
2453 const char *zSql, /* SQL to be evaluated */
2454 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
2455 /* (not the same as sqlite3_exec) */
2456 ShellState *pArg, /* Pointer to ShellState */
2457 char **pzErrMsg /* Error msg written here */
2458){
2459 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2460 int rc = SQLITE_OK; /* Return Code */
2461 int rc2;
2462 const char *zLeftover; /* Tail of unprocessed SQL */
2463
2464 if( pzErrMsg ){
2465 *pzErrMsg = NULL;
2466 }
2467
dan43efc182017-12-19 17:42:13 +00002468 if( pArg->expert.pExpert ){
2469 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
2470 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
2471 }
2472
drh2ce15c32017-07-11 13:34:40 +00002473 while( zSql[0] && (SQLITE_OK == rc) ){
2474 static const char *zStmtSql;
2475 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2476 if( SQLITE_OK != rc ){
2477 if( pzErrMsg ){
2478 *pzErrMsg = save_err_msg(db);
2479 }
2480 }else{
2481 if( !pStmt ){
2482 /* this happens for a comment or white-space */
2483 zSql = zLeftover;
2484 while( IsSpace(zSql[0]) ) zSql++;
2485 continue;
2486 }
2487 zStmtSql = sqlite3_sql(pStmt);
2488 if( zStmtSql==0 ) zStmtSql = "";
2489 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2490
2491 /* save off the prepared statment handle and reset row count */
2492 if( pArg ){
2493 pArg->pStmt = pStmt;
2494 pArg->cnt = 0;
2495 }
2496
2497 /* echo the sql statement if echo on */
2498 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
2499 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2500 }
2501
2502 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2503 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2504 sqlite3_stmt *pExplain;
2505 char *zEQP;
drhada70452017-12-21 21:02:27 +00002506 int triggerEQP = 0;
drh2ce15c32017-07-11 13:34:40 +00002507 disable_debug_trace_modes();
drhada70452017-12-21 21:02:27 +00002508 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
2509 if( pArg->autoEQP>=AUTOEQP_trigger ){
2510 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
2511 }
drh2ce15c32017-07-11 13:34:40 +00002512 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2513 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2514 if( rc==SQLITE_OK ){
2515 while( sqlite3_step(pExplain)==SQLITE_ROW ){
2516 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2517 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2518 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
2519 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2520 }
2521 }
2522 sqlite3_finalize(pExplain);
2523 sqlite3_free(zEQP);
drhada70452017-12-21 21:02:27 +00002524 if( pArg->autoEQP>=AUTOEQP_full ){
drh2ce15c32017-07-11 13:34:40 +00002525 /* Also do an EXPLAIN for ".eqp full" mode */
2526 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2527 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2528 if( rc==SQLITE_OK ){
2529 pArg->cMode = MODE_Explain;
2530 explain_data_prepare(pArg, pExplain);
2531 exec_prepared_stmt(pArg, pExplain, xCallback);
2532 explain_data_delete(pArg);
2533 }
2534 sqlite3_finalize(pExplain);
2535 sqlite3_free(zEQP);
2536 }
drhada70452017-12-21 21:02:27 +00002537 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, triggerEQP, 0);
drh2ce15c32017-07-11 13:34:40 +00002538 restore_debug_trace_modes();
2539 }
2540
2541 if( pArg ){
2542 pArg->cMode = pArg->mode;
2543 if( pArg->autoExplain
2544 && sqlite3_column_count(pStmt)==8
2545 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2546 ){
2547 pArg->cMode = MODE_Explain;
2548 }
2549
2550 /* If the shell is currently in ".explain" mode, gather the extra
2551 ** data required to add indents to the output.*/
2552 if( pArg->cMode==MODE_Explain ){
2553 explain_data_prepare(pArg, pStmt);
2554 }
2555 }
2556
2557 exec_prepared_stmt(pArg, pStmt, xCallback);
2558 explain_data_delete(pArg);
2559
2560 /* print usage stats if stats on */
2561 if( pArg && pArg->statsOn ){
2562 display_stats(db, pArg, 0);
2563 }
2564
2565 /* print loop-counters if required */
2566 if( pArg && pArg->scanstatsOn ){
2567 display_scanstats(db, pArg);
2568 }
2569
2570 /* Finalize the statement just executed. If this fails, save a
2571 ** copy of the error message. Otherwise, set zSql to point to the
2572 ** next statement to execute. */
2573 rc2 = sqlite3_finalize(pStmt);
2574 if( rc!=SQLITE_NOMEM ) rc = rc2;
2575 if( rc==SQLITE_OK ){
2576 zSql = zLeftover;
2577 while( IsSpace(zSql[0]) ) zSql++;
2578 }else if( pzErrMsg ){
2579 *pzErrMsg = save_err_msg(db);
2580 }
2581
2582 /* clear saved stmt handle */
2583 if( pArg ){
2584 pArg->pStmt = NULL;
2585 }
2586 }
2587 } /* end while */
2588
2589 return rc;
2590}
2591
2592/*
2593** Release memory previously allocated by tableColumnList().
2594*/
2595static void freeColumnList(char **azCol){
2596 int i;
2597 for(i=1; azCol[i]; i++){
2598 sqlite3_free(azCol[i]);
2599 }
2600 /* azCol[0] is a static string */
2601 sqlite3_free(azCol);
2602}
2603
2604/*
2605** Return a list of pointers to strings which are the names of all
2606** columns in table zTab. The memory to hold the names is dynamically
2607** allocated and must be released by the caller using a subsequent call
2608** to freeColumnList().
2609**
2610** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2611** value that needs to be preserved, then azCol[0] is filled in with the
2612** name of the rowid column.
2613**
2614** The first regular column in the table is azCol[1]. The list is terminated
2615** by an entry with azCol[i]==0.
2616*/
2617static char **tableColumnList(ShellState *p, const char *zTab){
2618 char **azCol = 0;
2619 sqlite3_stmt *pStmt;
2620 char *zSql;
2621 int nCol = 0;
2622 int nAlloc = 0;
2623 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2624 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
2625 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
2626 int rc;
2627
2628 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2629 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2630 sqlite3_free(zSql);
2631 if( rc ) return 0;
2632 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2633 if( nCol>=nAlloc-2 ){
2634 nAlloc = nAlloc*2 + nCol + 10;
2635 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2636 if( azCol==0 ){
2637 raw_printf(stderr, "Error: out of memory\n");
2638 exit(1);
2639 }
2640 }
2641 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2642 if( sqlite3_column_int(pStmt, 5) ){
2643 nPK++;
2644 if( nPK==1
2645 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2646 "INTEGER")==0
2647 ){
2648 isIPK = 1;
2649 }else{
2650 isIPK = 0;
2651 }
2652 }
2653 }
2654 sqlite3_finalize(pStmt);
drh4c6cddc2017-10-12 10:28:30 +00002655 if( azCol==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002656 azCol[0] = 0;
2657 azCol[nCol+1] = 0;
2658
2659 /* The decision of whether or not a rowid really needs to be preserved
2660 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2661 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2662 ** rowids on tables where the rowid is inaccessible because there are other
2663 ** columns in the table named "rowid", "_rowid_", and "oid".
2664 */
2665 if( preserveRowid && isIPK ){
2666 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2667 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2668 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2669 ** ROWID aliases. To distinguish these cases, check to see if
2670 ** there is a "pk" entry in "PRAGMA index_list". There will be
2671 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2672 */
2673 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2674 " WHERE origin='pk'", zTab);
2675 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2676 sqlite3_free(zSql);
2677 if( rc ){
2678 freeColumnList(azCol);
2679 return 0;
2680 }
2681 rc = sqlite3_step(pStmt);
2682 sqlite3_finalize(pStmt);
2683 preserveRowid = rc==SQLITE_ROW;
2684 }
2685 if( preserveRowid ){
2686 /* Only preserve the rowid if we can find a name to use for the
2687 ** rowid */
2688 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2689 int i, j;
2690 for(j=0; j<3; j++){
2691 for(i=1; i<=nCol; i++){
2692 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2693 }
2694 if( i>nCol ){
2695 /* At this point, we know that azRowid[j] is not the name of any
2696 ** ordinary column in the table. Verify that azRowid[j] is a valid
2697 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2698 ** tables will fail this last check */
2699 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2700 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2701 break;
2702 }
2703 }
2704 }
2705 return azCol;
2706}
2707
2708/*
2709** Toggle the reverse_unordered_selects setting.
2710*/
2711static void toggleSelectOrder(sqlite3 *db){
2712 sqlite3_stmt *pStmt = 0;
2713 int iSetting = 0;
2714 char zStmt[100];
2715 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2716 if( sqlite3_step(pStmt)==SQLITE_ROW ){
2717 iSetting = sqlite3_column_int(pStmt, 0);
2718 }
2719 sqlite3_finalize(pStmt);
2720 sqlite3_snprintf(sizeof(zStmt), zStmt,
2721 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2722 sqlite3_exec(db, zStmt, 0, 0, 0);
2723}
2724
2725/*
2726** This is a different callback routine used for dumping the database.
2727** Each row received by this callback consists of a table name,
2728** the table type ("index" or "table") and SQL to create the table.
2729** This routine should print text sufficient to recreate the table.
2730*/
2731static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
2732 int rc;
2733 const char *zTable;
2734 const char *zType;
2735 const char *zSql;
2736 ShellState *p = (ShellState *)pArg;
2737
2738 UNUSED_PARAMETER(azNotUsed);
drhb3c45232017-08-28 14:33:27 +00002739 if( nArg!=3 || azArg==0 ) return 0;
drh2ce15c32017-07-11 13:34:40 +00002740 zTable = azArg[0];
2741 zType = azArg[1];
2742 zSql = azArg[2];
2743
2744 if( strcmp(zTable, "sqlite_sequence")==0 ){
2745 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
2746 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2747 raw_printf(p->out, "ANALYZE sqlite_master;\n");
2748 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2749 return 0;
2750 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2751 char *zIns;
2752 if( !p->writableSchema ){
2753 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2754 p->writableSchema = 1;
2755 }
2756 zIns = sqlite3_mprintf(
2757 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2758 "VALUES('table','%q','%q',0,'%q');",
2759 zTable, zTable, zSql);
2760 utf8_printf(p->out, "%s\n", zIns);
2761 sqlite3_free(zIns);
2762 return 0;
2763 }else{
2764 printSchemaLine(p->out, zSql, ";\n");
2765 }
2766
2767 if( strcmp(zType, "table")==0 ){
2768 ShellText sSelect;
2769 ShellText sTable;
2770 char **azCol;
2771 int i;
2772 char *savedDestTable;
2773 int savedMode;
2774
2775 azCol = tableColumnList(p, zTable);
2776 if( azCol==0 ){
2777 p->nErr++;
2778 return 0;
2779 }
2780
2781 /* Always quote the table name, even if it appears to be pure ascii,
2782 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2783 initText(&sTable);
2784 appendText(&sTable, zTable, quoteChar(zTable));
2785 /* If preserving the rowid, add a column list after the table name.
2786 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2787 ** instead of the usual "INSERT INTO tab VALUES(...)".
2788 */
2789 if( azCol[0] ){
2790 appendText(&sTable, "(", 0);
2791 appendText(&sTable, azCol[0], 0);
2792 for(i=1; azCol[i]; i++){
2793 appendText(&sTable, ",", 0);
2794 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
2795 }
2796 appendText(&sTable, ")", 0);
2797 }
2798
2799 /* Build an appropriate SELECT statement */
2800 initText(&sSelect);
2801 appendText(&sSelect, "SELECT ", 0);
2802 if( azCol[0] ){
2803 appendText(&sSelect, azCol[0], 0);
2804 appendText(&sSelect, ",", 0);
2805 }
2806 for(i=1; azCol[i]; i++){
2807 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
2808 if( azCol[i+1] ){
2809 appendText(&sSelect, ",", 0);
2810 }
2811 }
2812 freeColumnList(azCol);
2813 appendText(&sSelect, " FROM ", 0);
2814 appendText(&sSelect, zTable, quoteChar(zTable));
2815
2816 savedDestTable = p->zDestTable;
2817 savedMode = p->mode;
2818 p->zDestTable = sTable.z;
2819 p->mode = p->cMode = MODE_Insert;
2820 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2821 if( (rc&0xff)==SQLITE_CORRUPT ){
2822 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2823 toggleSelectOrder(p->db);
2824 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
2825 toggleSelectOrder(p->db);
2826 }
2827 p->zDestTable = savedDestTable;
2828 p->mode = savedMode;
2829 freeText(&sTable);
2830 freeText(&sSelect);
2831 if( rc ) p->nErr++;
2832 }
2833 return 0;
2834}
2835
2836/*
2837** Run zQuery. Use dump_callback() as the callback routine so that
2838** the contents of the query are output as SQL statements.
2839**
2840** If we get a SQLITE_CORRUPT error, rerun the query after appending
2841** "ORDER BY rowid DESC" to the end.
2842*/
2843static int run_schema_dump_query(
2844 ShellState *p,
2845 const char *zQuery
2846){
2847 int rc;
2848 char *zErr = 0;
2849 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
2850 if( rc==SQLITE_CORRUPT ){
2851 char *zQ2;
2852 int len = strlen30(zQuery);
2853 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2854 if( zErr ){
2855 utf8_printf(p->out, "/****** %s ******/\n", zErr);
2856 sqlite3_free(zErr);
2857 zErr = 0;
2858 }
2859 zQ2 = malloc( len+100 );
2860 if( zQ2==0 ) return rc;
2861 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
2862 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
2863 if( rc ){
2864 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
2865 }else{
2866 rc = SQLITE_CORRUPT;
2867 }
2868 sqlite3_free(zErr);
2869 free(zQ2);
2870 }
2871 return rc;
2872}
2873
2874/*
2875** Text of a help message
2876*/
2877static char zHelp[] =
2878#ifndef SQLITE_OMIT_AUTHORIZATION
2879 ".auth ON|OFF Show authorizer callbacks\n"
2880#endif
2881 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
2882 ".bail on|off Stop after hitting an error. Default OFF\n"
2883 ".binary on|off Turn binary output on or off. Default OFF\n"
2884 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
2885 ".changes on|off Show number of rows changed by SQL\n"
2886 ".check GLOB Fail if output since .testcase does not match\n"
2887 ".clone NEWDB Clone data into NEWDB from the existing database\n"
2888 ".databases List names and files of attached databases\n"
2889 ".dbinfo ?DB? Show status information about the database\n"
2890 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
2891 " If TABLE specified, only dump tables matching\n"
2892 " LIKE pattern TABLE.\n"
2893 ".echo on|off Turn command echo on or off\n"
2894 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
2895 ".exit Exit this program\n"
dan2e1ea572017-12-21 18:55:24 +00002896 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
drh2ce15c32017-07-11 13:34:40 +00002897/* Because explain mode comes on automatically now, the ".explain" mode
2898** is removed from the help screen. It is still supported for legacy, however */
2899/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
2900 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
2901 ".headers on|off Turn display of headers on or off\n"
2902 ".help Show this message\n"
2903 ".import FILE TABLE Import data from FILE into TABLE\n"
2904#ifndef SQLITE_OMIT_TEST_CONTROL
2905 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
2906#endif
2907 ".indexes ?TABLE? Show names of all indexes\n"
2908 " If TABLE specified, only show indexes for tables\n"
2909 " matching LIKE pattern TABLE.\n"
2910#ifdef SQLITE_ENABLE_IOTRACE
2911 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
2912#endif
2913 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
2914 ".lint OPTIONS Report potential schema issues. Options:\n"
2915 " fkey-indexes Find missing foreign key indexes\n"
2916#ifndef SQLITE_OMIT_LOAD_EXTENSION
2917 ".load FILE ?ENTRY? Load an extension library\n"
2918#endif
2919 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
2920 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
2921 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
2922 " csv Comma-separated values\n"
2923 " column Left-aligned columns. (See .width)\n"
2924 " html HTML <table> code\n"
2925 " insert SQL insert statements for TABLE\n"
2926 " line One value per line\n"
2927 " list Values delimited by \"|\"\n"
2928 " quote Escape answers as for SQL\n"
2929 " tabs Tab-separated values\n"
2930 " tcl TCL list elements\n"
2931 ".nullvalue STRING Use STRING in place of NULL values\n"
2932 ".once FILENAME Output for the next SQL command only to FILENAME\n"
2933 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
2934 " The --new option starts with an empty file\n"
2935 ".output ?FILENAME? Send output to FILENAME or stdout\n"
2936 ".print STRING... Print literal STRING\n"
2937 ".prompt MAIN CONTINUE Replace the standard prompts\n"
2938 ".quit Exit this program\n"
2939 ".read FILENAME Execute SQL in FILENAME\n"
2940 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
2941 ".save FILE Write in-memory database into FILE\n"
2942 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
2943 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
2944 " Add --indent for pretty-printing\n"
2945 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
2946 ".separator COL ?ROW? Change the column separator and optionally the row\n"
2947 " separator for both the output mode and .import\n"
2948#if defined(SQLITE_ENABLE_SESSION)
2949 ".session CMD ... Create or control sessions\n"
2950#endif
2951 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
2952 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
2953 ".show Show the current values for various settings\n"
2954 ".stats ?on|off? Show stats or turn stats on or off\n"
2955 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
2956 ".tables ?TABLE? List names of tables\n"
2957 " If TABLE specified, only list tables matching\n"
2958 " LIKE pattern TABLE.\n"
2959 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
2960 ".timeout MS Try opening locked tables for MS milliseconds\n"
2961 ".timer on|off Turn SQL timer on or off\n"
2962 ".trace FILE|off Output each SQL statement as it is run\n"
2963 ".vfsinfo ?AUX? Information about the top-level VFS\n"
2964 ".vfslist List all available VFSes\n"
2965 ".vfsname ?AUX? Print the name of the VFS stack\n"
2966 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
2967 " Negative values right-justify\n"
2968;
2969
2970#if defined(SQLITE_ENABLE_SESSION)
2971/*
2972** Print help information for the ".sessions" command
2973*/
2974void session_help(ShellState *p){
2975 raw_printf(p->out,
2976 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
2977 "If ?NAME? is omitted, the first defined session is used.\n"
2978 "Subcommands:\n"
2979 " attach TABLE Attach TABLE\n"
2980 " changeset FILE Write a changeset into FILE\n"
2981 " close Close one session\n"
2982 " enable ?BOOLEAN? Set or query the enable bit\n"
2983 " filter GLOB... Reject tables matching GLOBs\n"
2984 " indirect ?BOOLEAN? Mark or query the indirect status\n"
2985 " isempty Query whether the session is empty\n"
2986 " list List currently open session names\n"
2987 " open DB NAME Open a new session on DB\n"
2988 " patchset FILE Write a patchset into FILE\n"
2989 );
2990}
2991#endif
2992
2993
2994/* Forward reference */
2995static int process_input(ShellState *p, FILE *in);
2996
2997/*
2998** Read the content of file zName into memory obtained from sqlite3_malloc64()
2999** and return a pointer to the buffer. The caller is responsible for freeing
3000** the memory.
3001**
3002** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3003** read.
3004**
3005** For convenience, a nul-terminator byte is always appended to the data read
3006** from the file before the buffer is returned. This byte is not included in
3007** the final value of (*pnByte), if applicable.
3008**
3009** NULL is returned if any error is encountered. The final value of *pnByte
3010** is undefined in this case.
3011*/
3012static char *readFile(const char *zName, int *pnByte){
3013 FILE *in = fopen(zName, "rb");
3014 long nIn;
3015 size_t nRead;
3016 char *pBuf;
3017 if( in==0 ) return 0;
3018 fseek(in, 0, SEEK_END);
3019 nIn = ftell(in);
3020 rewind(in);
3021 pBuf = sqlite3_malloc64( nIn+1 );
3022 if( pBuf==0 ) return 0;
3023 nRead = fread(pBuf, nIn, 1, in);
3024 fclose(in);
3025 if( nRead!=1 ){
3026 sqlite3_free(pBuf);
3027 return 0;
3028 }
3029 pBuf[nIn] = 0;
3030 if( pnByte ) *pnByte = nIn;
3031 return pBuf;
3032}
3033
3034#if defined(SQLITE_ENABLE_SESSION)
3035/*
3036** Close a single OpenSession object and release all of its associated
3037** resources.
3038*/
3039static void session_close(OpenSession *pSession){
3040 int i;
3041 sqlite3session_delete(pSession->p);
3042 sqlite3_free(pSession->zName);
3043 for(i=0; i<pSession->nFilter; i++){
3044 sqlite3_free(pSession->azFilter[i]);
3045 }
3046 sqlite3_free(pSession->azFilter);
3047 memset(pSession, 0, sizeof(OpenSession));
3048}
3049#endif
3050
3051/*
3052** Close all OpenSession objects and release all associated resources.
3053*/
3054#if defined(SQLITE_ENABLE_SESSION)
3055static void session_close_all(ShellState *p){
3056 int i;
3057 for(i=0; i<p->nSession; i++){
3058 session_close(&p->aSession[i]);
3059 }
3060 p->nSession = 0;
3061}
3062#else
3063# define session_close_all(X)
3064#endif
3065
3066/*
3067** Implementation of the xFilter function for an open session. Omit
3068** any tables named by ".session filter" but let all other table through.
3069*/
3070#if defined(SQLITE_ENABLE_SESSION)
3071static int session_filter(void *pCtx, const char *zTab){
3072 OpenSession *pSession = (OpenSession*)pCtx;
3073 int i;
3074 for(i=0; i<pSession->nFilter; i++){
3075 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3076 }
3077 return 1;
3078}
3079#endif
3080
3081/*
3082** Make sure the database is open. If it is not, then open it. If
3083** the database fails to open, print an error message and exit.
3084*/
3085static void open_db(ShellState *p, int keepAlive){
3086 if( p->db==0 ){
3087 sqlite3_initialize();
3088 sqlite3_open(p->zDbFilename, &p->db);
3089 globalDb = p->db;
3090 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
3091 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
3092 p->zDbFilename, sqlite3_errmsg(p->db));
3093 if( keepAlive ) return;
3094 exit(1);
3095 }
3096#ifndef SQLITE_OMIT_LOAD_EXTENSION
3097 sqlite3_enable_load_extension(p->db, 1);
3098#endif
3099 sqlite3_fileio_init(p->db, 0, 0);
3100 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00003101 sqlite3_completion_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003102#ifdef SQLITE_HAVE_ZLIB
dan9ebfaad2017-12-26 20:39:58 +00003103 sqlite3_zipfile_init(p->db, 0, 0);
dand1b51d42017-12-16 19:11:26 +00003104 sqlite3_sqlar_init(p->db, 0, 0);
dan72afc3c2017-12-05 18:32:40 +00003105#endif
drhceba7922018-01-01 21:28:25 +00003106 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
drh2ce15c32017-07-11 13:34:40 +00003107 shellAddSchemaName, 0, 0);
drh667a2a22018-01-02 00:04:37 +00003108 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
3109 shellModuleSchema, 0, 0);
drh2ce15c32017-07-11 13:34:40 +00003110 }
3111}
3112
drh56eb09b2017-07-11 13:59:07 +00003113#if HAVE_READLINE || HAVE_EDITLINE
3114/*
3115** Readline completion callbacks
3116*/
3117static char *readline_completion_generator(const char *text, int state){
3118 static sqlite3_stmt *pStmt = 0;
3119 char *zRet;
3120 if( state==0 ){
3121 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00003122 sqlite3_finalize(pStmt);
3123 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3124 " FROM completion(%Q) ORDER BY 1", text);
3125 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3126 sqlite3_free(zSql);
3127 }
3128 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00003129 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00003130 }else{
3131 sqlite3_finalize(pStmt);
3132 pStmt = 0;
3133 zRet = 0;
3134 }
3135 return zRet;
3136}
3137static char **readline_completion(const char *zText, int iStart, int iEnd){
3138 rl_attempted_completion_over = 1;
3139 return rl_completion_matches(zText, readline_completion_generator);
3140}
3141
3142#elif HAVE_LINENOISE
3143/*
3144** Linenoise completion callback
3145*/
3146static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
drhaf2770f2018-01-05 14:55:43 +00003147 int nLine = strlen30(zLine);
drh56eb09b2017-07-11 13:59:07 +00003148 int i, iStart;
3149 sqlite3_stmt *pStmt = 0;
3150 char *zSql;
3151 char zBuf[1000];
3152
3153 if( nLine>sizeof(zBuf)-30 ) return;
3154 if( zLine[0]=='.' ) return;
3155 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
3156 if( i==nLine-1 ) return;
3157 iStart = i+1;
3158 memcpy(zBuf, zLine, iStart);
3159 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3160 " FROM completion(%Q,%Q) ORDER BY 1",
3161 &zLine[iStart], zLine);
3162 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
3163 sqlite3_free(zSql);
3164 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3165 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3166 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
3167 int nCompletion = sqlite3_column_bytes(pStmt, 0);
3168 if( iStart+nCompletion < sizeof(zBuf)-1 ){
3169 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
3170 linenoiseAddCompletion(lc, zBuf);
3171 }
3172 }
3173 sqlite3_finalize(pStmt);
3174}
3175#endif
3176
drh2ce15c32017-07-11 13:34:40 +00003177/*
3178** Do C-language style dequoting.
3179**
3180** \a -> alarm
3181** \b -> backspace
3182** \t -> tab
3183** \n -> newline
3184** \v -> vertical tab
3185** \f -> form feed
3186** \r -> carriage return
3187** \s -> space
3188** \" -> "
3189** \' -> '
3190** \\ -> backslash
3191** \NNN -> ascii character NNN in octal
3192*/
3193static void resolve_backslashes(char *z){
3194 int i, j;
3195 char c;
3196 while( *z && *z!='\\' ) z++;
3197 for(i=j=0; (c = z[i])!=0; i++, j++){
3198 if( c=='\\' && z[i+1]!=0 ){
3199 c = z[++i];
3200 if( c=='a' ){
3201 c = '\a';
3202 }else if( c=='b' ){
3203 c = '\b';
3204 }else if( c=='t' ){
3205 c = '\t';
3206 }else if( c=='n' ){
3207 c = '\n';
3208 }else if( c=='v' ){
3209 c = '\v';
3210 }else if( c=='f' ){
3211 c = '\f';
3212 }else if( c=='r' ){
3213 c = '\r';
3214 }else if( c=='"' ){
3215 c = '"';
3216 }else if( c=='\'' ){
3217 c = '\'';
3218 }else if( c=='\\' ){
3219 c = '\\';
3220 }else if( c>='0' && c<='7' ){
3221 c -= '0';
3222 if( z[i+1]>='0' && z[i+1]<='7' ){
3223 i++;
3224 c = (c<<3) + z[i] - '0';
3225 if( z[i+1]>='0' && z[i+1]<='7' ){
3226 i++;
3227 c = (c<<3) + z[i] - '0';
3228 }
3229 }
3230 }
3231 }
3232 z[j] = c;
3233 }
3234 if( j<i ) z[j] = 0;
3235}
3236
3237/*
3238** Return the value of a hexadecimal digit. Return -1 if the input
3239** is not a hex digit.
3240*/
3241static int hexDigitValue(char c){
3242 if( c>='0' && c<='9' ) return c - '0';
3243 if( c>='a' && c<='f' ) return c - 'a' + 10;
3244 if( c>='A' && c<='F' ) return c - 'A' + 10;
3245 return -1;
3246}
3247
3248/*
3249** Interpret zArg as an integer value, possibly with suffixes.
3250*/
3251static sqlite3_int64 integerValue(const char *zArg){
3252 sqlite3_int64 v = 0;
3253 static const struct { char *zSuffix; int iMult; } aMult[] = {
3254 { "KiB", 1024 },
3255 { "MiB", 1024*1024 },
3256 { "GiB", 1024*1024*1024 },
3257 { "KB", 1000 },
3258 { "MB", 1000000 },
3259 { "GB", 1000000000 },
3260 { "K", 1000 },
3261 { "M", 1000000 },
3262 { "G", 1000000000 },
3263 };
3264 int i;
3265 int isNeg = 0;
3266 if( zArg[0]=='-' ){
3267 isNeg = 1;
3268 zArg++;
3269 }else if( zArg[0]=='+' ){
3270 zArg++;
3271 }
3272 if( zArg[0]=='0' && zArg[1]=='x' ){
3273 int x;
3274 zArg += 2;
3275 while( (x = hexDigitValue(zArg[0]))>=0 ){
3276 v = (v<<4) + x;
3277 zArg++;
3278 }
3279 }else{
3280 while( IsDigit(zArg[0]) ){
3281 v = v*10 + zArg[0] - '0';
3282 zArg++;
3283 }
3284 }
3285 for(i=0; i<ArraySize(aMult); i++){
3286 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3287 v *= aMult[i].iMult;
3288 break;
3289 }
3290 }
3291 return isNeg? -v : v;
3292}
3293
3294/*
3295** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3296** for TRUE and FALSE. Return the integer value if appropriate.
3297*/
3298static int booleanValue(const char *zArg){
3299 int i;
3300 if( zArg[0]=='0' && zArg[1]=='x' ){
3301 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3302 }else{
3303 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3304 }
3305 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3306 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3307 return 1;
3308 }
3309 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3310 return 0;
3311 }
3312 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3313 zArg);
3314 return 0;
3315}
3316
3317/*
3318** Set or clear a shell flag according to a boolean value.
3319*/
3320static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3321 if( booleanValue(zArg) ){
3322 ShellSetFlag(p, mFlag);
3323 }else{
3324 ShellClearFlag(p, mFlag);
3325 }
3326}
3327
3328/*
3329** Close an output file, assuming it is not stderr or stdout
3330*/
3331static void output_file_close(FILE *f){
3332 if( f && f!=stdout && f!=stderr ) fclose(f);
3333}
3334
3335/*
3336** Try to open an output file. The names "stdout" and "stderr" are
3337** recognized and do the right thing. NULL is returned if the output
3338** filename is "off".
3339*/
3340static FILE *output_file_open(const char *zFile){
3341 FILE *f;
3342 if( strcmp(zFile,"stdout")==0 ){
3343 f = stdout;
3344 }else if( strcmp(zFile, "stderr")==0 ){
3345 f = stderr;
3346 }else if( strcmp(zFile, "off")==0 ){
3347 f = 0;
3348 }else{
3349 f = fopen(zFile, "wb");
3350 if( f==0 ){
3351 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3352 }
3353 }
3354 return f;
3355}
3356
3357#if !defined(SQLITE_UNTESTABLE)
3358#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3359/*
3360** A routine for handling output from sqlite3_trace().
3361*/
3362static int sql_trace_callback(
3363 unsigned mType,
3364 void *pArg,
3365 void *pP,
3366 void *pX
3367){
3368 FILE *f = (FILE*)pArg;
3369 UNUSED_PARAMETER(mType);
3370 UNUSED_PARAMETER(pP);
3371 if( f ){
3372 const char *z = (const char*)pX;
drhaf2770f2018-01-05 14:55:43 +00003373 int i = strlen30(z);
drh2ce15c32017-07-11 13:34:40 +00003374 while( i>0 && z[i-1]==';' ){ i--; }
3375 utf8_printf(f, "%.*s;\n", i, z);
3376 }
3377 return 0;
3378}
3379#endif
3380#endif
3381
3382/*
3383** A no-op routine that runs with the ".breakpoint" doc-command. This is
3384** a useful spot to set a debugger breakpoint.
3385*/
3386static void test_breakpoint(void){
3387 static int nCall = 0;
3388 nCall++;
3389}
3390
3391/*
3392** An object used to read a CSV and other files for import.
3393*/
3394typedef struct ImportCtx ImportCtx;
3395struct ImportCtx {
3396 const char *zFile; /* Name of the input file */
3397 FILE *in; /* Read the CSV text from this input stream */
3398 char *z; /* Accumulated text for a field */
3399 int n; /* Number of bytes in z */
3400 int nAlloc; /* Space allocated for z[] */
3401 int nLine; /* Current line number */
3402 int bNotFirst; /* True if one or more bytes already read */
3403 int cTerm; /* Character that terminated the most recent field */
3404 int cColSep; /* The column separator character. (Usually ",") */
3405 int cRowSep; /* The row separator character. (Usually "\n") */
3406};
3407
3408/* Append a single byte to z[] */
3409static void import_append_char(ImportCtx *p, int c){
3410 if( p->n+1>=p->nAlloc ){
3411 p->nAlloc += p->nAlloc + 100;
3412 p->z = sqlite3_realloc64(p->z, p->nAlloc);
3413 if( p->z==0 ){
3414 raw_printf(stderr, "out of memory\n");
3415 exit(1);
3416 }
3417 }
3418 p->z[p->n++] = (char)c;
3419}
3420
3421/* Read a single field of CSV text. Compatible with rfc4180 and extended
3422** with the option of having a separator other than ",".
3423**
3424** + Input comes from p->in.
3425** + Store results in p->z of length p->n. Space to hold p->z comes
3426** from sqlite3_malloc64().
3427** + Use p->cSep as the column separator. The default is ",".
3428** + Use p->rSep as the row separator. The default is "\n".
3429** + Keep track of the line number in p->nLine.
3430** + Store the character that terminates the field in p->cTerm. Store
3431** EOF on end-of-file.
3432** + Report syntax errors on stderr
3433*/
3434static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
3435 int c;
3436 int cSep = p->cColSep;
3437 int rSep = p->cRowSep;
3438 p->n = 0;
3439 c = fgetc(p->in);
3440 if( c==EOF || seenInterrupt ){
3441 p->cTerm = EOF;
3442 return 0;
3443 }
3444 if( c=='"' ){
3445 int pc, ppc;
3446 int startLine = p->nLine;
3447 int cQuote = c;
3448 pc = ppc = 0;
3449 while( 1 ){
3450 c = fgetc(p->in);
3451 if( c==rSep ) p->nLine++;
3452 if( c==cQuote ){
3453 if( pc==cQuote ){
3454 pc = 0;
3455 continue;
3456 }
3457 }
3458 if( (c==cSep && pc==cQuote)
3459 || (c==rSep && pc==cQuote)
3460 || (c==rSep && pc=='\r' && ppc==cQuote)
3461 || (c==EOF && pc==cQuote)
3462 ){
3463 do{ p->n--; }while( p->z[p->n]!=cQuote );
3464 p->cTerm = c;
3465 break;
3466 }
3467 if( pc==cQuote && c!='\r' ){
3468 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
3469 p->zFile, p->nLine, cQuote);
3470 }
3471 if( c==EOF ){
3472 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
3473 p->zFile, startLine, cQuote);
3474 p->cTerm = c;
3475 break;
3476 }
3477 import_append_char(p, c);
3478 ppc = pc;
3479 pc = c;
3480 }
3481 }else{
3482 /* If this is the first field being parsed and it begins with the
3483 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3484 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3485 import_append_char(p, c);
3486 c = fgetc(p->in);
3487 if( (c&0xff)==0xbb ){
3488 import_append_char(p, c);
3489 c = fgetc(p->in);
3490 if( (c&0xff)==0xbf ){
3491 p->bNotFirst = 1;
3492 p->n = 0;
3493 return csv_read_one_field(p);
3494 }
3495 }
3496 }
3497 while( c!=EOF && c!=cSep && c!=rSep ){
3498 import_append_char(p, c);
3499 c = fgetc(p->in);
3500 }
3501 if( c==rSep ){
3502 p->nLine++;
3503 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
3504 }
3505 p->cTerm = c;
3506 }
3507 if( p->z ) p->z[p->n] = 0;
3508 p->bNotFirst = 1;
3509 return p->z;
3510}
3511
3512/* Read a single field of ASCII delimited text.
3513**
3514** + Input comes from p->in.
3515** + Store results in p->z of length p->n. Space to hold p->z comes
3516** from sqlite3_malloc64().
3517** + Use p->cSep as the column separator. The default is "\x1F".
3518** + Use p->rSep as the row separator. The default is "\x1E".
3519** + Keep track of the row number in p->nLine.
3520** + Store the character that terminates the field in p->cTerm. Store
3521** EOF on end-of-file.
3522** + Report syntax errors on stderr
3523*/
3524static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
3525 int c;
3526 int cSep = p->cColSep;
3527 int rSep = p->cRowSep;
3528 p->n = 0;
3529 c = fgetc(p->in);
3530 if( c==EOF || seenInterrupt ){
3531 p->cTerm = EOF;
3532 return 0;
3533 }
3534 while( c!=EOF && c!=cSep && c!=rSep ){
3535 import_append_char(p, c);
3536 c = fgetc(p->in);
3537 }
3538 if( c==rSep ){
3539 p->nLine++;
3540 }
3541 p->cTerm = c;
3542 if( p->z ) p->z[p->n] = 0;
3543 return p->z;
3544}
3545
3546/*
3547** Try to transfer data for table zTable. If an error is seen while
3548** moving forward, try to go backwards. The backwards movement won't
3549** work for WITHOUT ROWID tables.
3550*/
3551static void tryToCloneData(
3552 ShellState *p,
3553 sqlite3 *newDb,
3554 const char *zTable
3555){
3556 sqlite3_stmt *pQuery = 0;
3557 sqlite3_stmt *pInsert = 0;
3558 char *zQuery = 0;
3559 char *zInsert = 0;
3560 int rc;
3561 int i, j, n;
drhaf2770f2018-01-05 14:55:43 +00003562 int nTable = strlen30(zTable);
drh2ce15c32017-07-11 13:34:40 +00003563 int k = 0;
3564 int cnt = 0;
3565 const int spinRate = 10000;
3566
3567 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3568 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3569 if( rc ){
3570 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3571 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3572 zQuery);
3573 goto end_data_xfer;
3574 }
3575 n = sqlite3_column_count(pQuery);
3576 zInsert = sqlite3_malloc64(200 + nTable + n*3);
3577 if( zInsert==0 ){
3578 raw_printf(stderr, "out of memory\n");
3579 goto end_data_xfer;
3580 }
3581 sqlite3_snprintf(200+nTable,zInsert,
3582 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
drhaf2770f2018-01-05 14:55:43 +00003583 i = strlen30(zInsert);
drh2ce15c32017-07-11 13:34:40 +00003584 for(j=1; j<n; j++){
3585 memcpy(zInsert+i, ",?", 2);
3586 i += 2;
3587 }
3588 memcpy(zInsert+i, ");", 3);
3589 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3590 if( rc ){
3591 utf8_printf(stderr, "Error %d: %s on [%s]\n",
3592 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3593 zQuery);
3594 goto end_data_xfer;
3595 }
3596 for(k=0; k<2; k++){
3597 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3598 for(i=0; i<n; i++){
3599 switch( sqlite3_column_type(pQuery, i) ){
3600 case SQLITE_NULL: {
3601 sqlite3_bind_null(pInsert, i+1);
3602 break;
3603 }
3604 case SQLITE_INTEGER: {
3605 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3606 break;
3607 }
3608 case SQLITE_FLOAT: {
3609 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3610 break;
3611 }
3612 case SQLITE_TEXT: {
3613 sqlite3_bind_text(pInsert, i+1,
3614 (const char*)sqlite3_column_text(pQuery,i),
3615 -1, SQLITE_STATIC);
3616 break;
3617 }
3618 case SQLITE_BLOB: {
3619 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3620 sqlite3_column_bytes(pQuery,i),
3621 SQLITE_STATIC);
3622 break;
3623 }
3624 }
3625 } /* End for */
3626 rc = sqlite3_step(pInsert);
3627 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
3628 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
3629 sqlite3_errmsg(newDb));
3630 }
3631 sqlite3_reset(pInsert);
3632 cnt++;
3633 if( (cnt%spinRate)==0 ){
3634 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3635 fflush(stdout);
3636 }
3637 } /* End while */
3638 if( rc==SQLITE_DONE ) break;
3639 sqlite3_finalize(pQuery);
3640 sqlite3_free(zQuery);
3641 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3642 zTable);
3643 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3644 if( rc ){
3645 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
3646 break;
3647 }
3648 } /* End for(k=0...) */
3649
3650end_data_xfer:
3651 sqlite3_finalize(pQuery);
3652 sqlite3_finalize(pInsert);
3653 sqlite3_free(zQuery);
3654 sqlite3_free(zInsert);
3655}
3656
3657
3658/*
3659** Try to transfer all rows of the schema that match zWhere. For
3660** each row, invoke xForEach() on the object defined by that row.
3661** If an error is encountered while moving forward through the
3662** sqlite_master table, try again moving backwards.
3663*/
3664static void tryToCloneSchema(
3665 ShellState *p,
3666 sqlite3 *newDb,
3667 const char *zWhere,
3668 void (*xForEach)(ShellState*,sqlite3*,const char*)
3669){
3670 sqlite3_stmt *pQuery = 0;
3671 char *zQuery = 0;
3672 int rc;
3673 const unsigned char *zName;
3674 const unsigned char *zSql;
3675 char *zErrMsg = 0;
3676
3677 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3678 " WHERE %s", zWhere);
3679 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3680 if( rc ){
3681 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3682 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3683 zQuery);
3684 goto end_schema_xfer;
3685 }
3686 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3687 zName = sqlite3_column_text(pQuery, 0);
3688 zSql = sqlite3_column_text(pQuery, 1);
3689 printf("%s... ", zName); fflush(stdout);
3690 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3691 if( zErrMsg ){
3692 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3693 sqlite3_free(zErrMsg);
3694 zErrMsg = 0;
3695 }
3696 if( xForEach ){
3697 xForEach(p, newDb, (const char*)zName);
3698 }
3699 printf("done\n");
3700 }
3701 if( rc!=SQLITE_DONE ){
3702 sqlite3_finalize(pQuery);
3703 sqlite3_free(zQuery);
3704 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3705 " WHERE %s ORDER BY rowid DESC", zWhere);
3706 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3707 if( rc ){
3708 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
3709 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3710 zQuery);
3711 goto end_schema_xfer;
3712 }
3713 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3714 zName = sqlite3_column_text(pQuery, 0);
3715 zSql = sqlite3_column_text(pQuery, 1);
3716 printf("%s... ", zName); fflush(stdout);
3717 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3718 if( zErrMsg ){
3719 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
3720 sqlite3_free(zErrMsg);
3721 zErrMsg = 0;
3722 }
3723 if( xForEach ){
3724 xForEach(p, newDb, (const char*)zName);
3725 }
3726 printf("done\n");
3727 }
3728 }
3729end_schema_xfer:
3730 sqlite3_finalize(pQuery);
3731 sqlite3_free(zQuery);
3732}
3733
3734/*
3735** Open a new database file named "zNewDb". Try to recover as much information
3736** as possible out of the main database (which might be corrupt) and write it
3737** into zNewDb.
3738*/
3739static void tryToClone(ShellState *p, const char *zNewDb){
3740 int rc;
3741 sqlite3 *newDb = 0;
3742 if( access(zNewDb,0)==0 ){
3743 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
3744 return;
3745 }
3746 rc = sqlite3_open(zNewDb, &newDb);
3747 if( rc ){
3748 utf8_printf(stderr, "Cannot create output database: %s\n",
3749 sqlite3_errmsg(newDb));
3750 }else{
3751 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
3752 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
3753 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3754 tryToCloneSchema(p, newDb, "type!='table'", 0);
3755 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
3756 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3757 }
3758 sqlite3_close(newDb);
3759}
3760
3761/*
3762** Change the output file back to stdout
3763*/
3764static void output_reset(ShellState *p){
3765 if( p->outfile[0]=='|' ){
3766#ifndef SQLITE_OMIT_POPEN
3767 pclose(p->out);
3768#endif
3769 }else{
3770 output_file_close(p->out);
3771 }
3772 p->outfile[0] = 0;
3773 p->out = stdout;
3774}
3775
3776/*
3777** Run an SQL command and return the single integer result.
3778*/
3779static int db_int(ShellState *p, const char *zSql){
3780 sqlite3_stmt *pStmt;
3781 int res = 0;
3782 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3783 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3784 res = sqlite3_column_int(pStmt,0);
3785 }
3786 sqlite3_finalize(pStmt);
3787 return res;
3788}
3789
3790/*
3791** Convert a 2-byte or 4-byte big-endian integer into a native integer
3792*/
3793static unsigned int get2byteInt(unsigned char *a){
3794 return (a[0]<<8) + a[1];
3795}
3796static unsigned int get4byteInt(unsigned char *a){
3797 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
3798}
3799
3800/*
3801** Implementation of the ".info" command.
3802**
3803** Return 1 on error, 2 to exit, and 0 otherwise.
3804*/
3805static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
3806 static const struct { const char *zName; int ofst; } aField[] = {
3807 { "file change counter:", 24 },
3808 { "database page count:", 28 },
3809 { "freelist page count:", 36 },
3810 { "schema cookie:", 40 },
3811 { "schema format:", 44 },
3812 { "default cache size:", 48 },
3813 { "autovacuum top root:", 52 },
3814 { "incremental vacuum:", 64 },
3815 { "text encoding:", 56 },
3816 { "user version:", 60 },
3817 { "application id:", 68 },
3818 { "software version:", 96 },
3819 };
3820 static const struct { const char *zName; const char *zSql; } aQuery[] = {
3821 { "number of tables:",
3822 "SELECT count(*) FROM %s WHERE type='table'" },
3823 { "number of indexes:",
3824 "SELECT count(*) FROM %s WHERE type='index'" },
3825 { "number of triggers:",
3826 "SELECT count(*) FROM %s WHERE type='trigger'" },
3827 { "number of views:",
3828 "SELECT count(*) FROM %s WHERE type='view'" },
3829 { "schema size:",
3830 "SELECT total(length(sql)) FROM %s" },
3831 };
drh2ce15c32017-07-11 13:34:40 +00003832 int i;
3833 char *zSchemaTab;
3834 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00003835 sqlite3_stmt *pStmt = 0;
drh2ce15c32017-07-11 13:34:40 +00003836 unsigned char aHdr[100];
3837 open_db(p, 0);
3838 if( p->db==0 ) return 1;
drh512e6c32017-10-11 17:51:08 +00003839 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
3840 -1, &pStmt, 0);
3841 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
3842 if( sqlite3_step(pStmt)==SQLITE_ROW
3843 && sqlite3_column_bytes(pStmt,0)>100
3844 ){
3845 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
3846 sqlite3_finalize(pStmt);
3847 }else{
drh2ce15c32017-07-11 13:34:40 +00003848 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00003849 sqlite3_finalize(pStmt);
drh2ce15c32017-07-11 13:34:40 +00003850 return 1;
3851 }
3852 i = get2byteInt(aHdr+16);
3853 if( i==1 ) i = 65536;
3854 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
3855 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
3856 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
3857 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
3858 for(i=0; i<ArraySize(aField); i++){
3859 int ofst = aField[i].ofst;
3860 unsigned int val = get4byteInt(aHdr + ofst);
3861 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
3862 switch( ofst ){
3863 case 56: {
3864 if( val==1 ) raw_printf(p->out, " (utf8)");
3865 if( val==2 ) raw_printf(p->out, " (utf16le)");
3866 if( val==3 ) raw_printf(p->out, " (utf16be)");
3867 }
3868 }
3869 raw_printf(p->out, "\n");
3870 }
3871 if( zDb==0 ){
3872 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
3873 }else if( strcmp(zDb,"temp")==0 ){
3874 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
3875 }else{
3876 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
3877 }
3878 for(i=0; i<ArraySize(aQuery); i++){
3879 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
3880 int val = db_int(p, zSql);
3881 sqlite3_free(zSql);
3882 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
3883 }
3884 sqlite3_free(zSchemaTab);
3885 return 0;
3886}
3887
3888/*
3889** Print the current sqlite3_errmsg() value to stderr and return 1.
3890*/
3891static int shellDatabaseError(sqlite3 *db){
3892 const char *zErr = sqlite3_errmsg(db);
3893 utf8_printf(stderr, "Error: %s\n", zErr);
3894 return 1;
3895}
3896
3897/*
3898** Print an out-of-memory message to stderr and return 1.
3899*/
3900static int shellNomemError(void){
3901 raw_printf(stderr, "Error: out of memory\n");
3902 return 1;
3903}
3904
3905/*
3906** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
3907** if they match and FALSE (0) if they do not match.
3908**
3909** Globbing rules:
3910**
3911** '*' Matches any sequence of zero or more characters.
3912**
3913** '?' Matches exactly one character.
3914**
3915** [...] Matches one character from the enclosed list of
3916** characters.
3917**
3918** [^...] Matches one character not in the enclosed list.
3919**
3920** '#' Matches any sequence of one or more digits with an
3921** optional + or - sign in front
3922**
3923** ' ' Any span of whitespace matches any other span of
3924** whitespace.
3925**
3926** Extra whitespace at the end of z[] is ignored.
3927*/
3928static int testcase_glob(const char *zGlob, const char *z){
3929 int c, c2;
3930 int invert;
3931 int seen;
3932
3933 while( (c = (*(zGlob++)))!=0 ){
3934 if( IsSpace(c) ){
3935 if( !IsSpace(*z) ) return 0;
3936 while( IsSpace(*zGlob) ) zGlob++;
3937 while( IsSpace(*z) ) z++;
3938 }else if( c=='*' ){
3939 while( (c=(*(zGlob++))) == '*' || c=='?' ){
3940 if( c=='?' && (*(z++))==0 ) return 0;
3941 }
3942 if( c==0 ){
3943 return 1;
3944 }else if( c=='[' ){
3945 while( *z && testcase_glob(zGlob-1,z)==0 ){
3946 z++;
3947 }
3948 return (*z)!=0;
3949 }
3950 while( (c2 = (*(z++)))!=0 ){
3951 while( c2!=c ){
3952 c2 = *(z++);
3953 if( c2==0 ) return 0;
3954 }
3955 if( testcase_glob(zGlob,z) ) return 1;
3956 }
3957 return 0;
3958 }else if( c=='?' ){
3959 if( (*(z++))==0 ) return 0;
3960 }else if( c=='[' ){
3961 int prior_c = 0;
3962 seen = 0;
3963 invert = 0;
3964 c = *(z++);
3965 if( c==0 ) return 0;
3966 c2 = *(zGlob++);
3967 if( c2=='^' ){
3968 invert = 1;
3969 c2 = *(zGlob++);
3970 }
3971 if( c2==']' ){
3972 if( c==']' ) seen = 1;
3973 c2 = *(zGlob++);
3974 }
3975 while( c2 && c2!=']' ){
3976 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
3977 c2 = *(zGlob++);
3978 if( c>=prior_c && c<=c2 ) seen = 1;
3979 prior_c = 0;
3980 }else{
3981 if( c==c2 ){
3982 seen = 1;
3983 }
3984 prior_c = c2;
3985 }
3986 c2 = *(zGlob++);
3987 }
3988 if( c2==0 || (seen ^ invert)==0 ) return 0;
3989 }else if( c=='#' ){
3990 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
3991 if( !IsDigit(z[0]) ) return 0;
3992 z++;
3993 while( IsDigit(z[0]) ){ z++; }
3994 }else{
3995 if( c!=(*(z++)) ) return 0;
3996 }
3997 }
3998 while( IsSpace(*z) ){ z++; }
3999 return *z==0;
4000}
4001
4002
4003/*
4004** Compare the string as a command-line option with either one or two
4005** initial "-" characters.
4006*/
4007static int optionMatch(const char *zStr, const char *zOpt){
4008 if( zStr[0]!='-' ) return 0;
4009 zStr++;
4010 if( zStr[0]=='-' ) zStr++;
4011 return strcmp(zStr, zOpt)==0;
4012}
4013
4014/*
4015** Delete a file.
4016*/
4017int shellDeleteFile(const char *zFilename){
4018 int rc;
4019#ifdef _WIN32
4020 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
4021 rc = _wunlink(z);
4022 sqlite3_free(z);
4023#else
4024 rc = unlink(zFilename);
4025#endif
4026 return rc;
4027}
4028
4029
4030/*
4031** The implementation of SQL scalar function fkey_collate_clause(), used
4032** by the ".lint fkey-indexes" command. This scalar function is always
4033** called with four arguments - the parent table name, the parent column name,
4034** the child table name and the child column name.
4035**
4036** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4037**
4038** If either of the named tables or columns do not exist, this function
4039** returns an empty string. An empty string is also returned if both tables
4040** and columns exist but have the same default collation sequence. Or,
4041** if both exist but the default collation sequences are different, this
4042** function returns the string " COLLATE <parent-collation>", where
4043** <parent-collation> is the default collation sequence of the parent column.
4044*/
4045static void shellFkeyCollateClause(
4046 sqlite3_context *pCtx,
4047 int nVal,
4048 sqlite3_value **apVal
4049){
4050 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4051 const char *zParent;
4052 const char *zParentCol;
4053 const char *zParentSeq;
4054 const char *zChild;
4055 const char *zChildCol;
4056 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
4057 int rc;
4058
4059 assert( nVal==4 );
4060 zParent = (const char*)sqlite3_value_text(apVal[0]);
4061 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4062 zChild = (const char*)sqlite3_value_text(apVal[2]);
4063 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4064
4065 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4066 rc = sqlite3_table_column_metadata(
4067 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4068 );
4069 if( rc==SQLITE_OK ){
4070 rc = sqlite3_table_column_metadata(
4071 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4072 );
4073 }
4074
4075 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4076 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4077 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4078 sqlite3_free(z);
4079 }
4080}
4081
4082
4083/*
4084** The implementation of dot-command ".lint fkey-indexes".
4085*/
4086static int lintFkeyIndexes(
4087 ShellState *pState, /* Current shell tool state */
4088 char **azArg, /* Array of arguments passed to dot command */
4089 int nArg /* Number of entries in azArg[] */
4090){
4091 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4092 FILE *out = pState->out; /* Stream to write non-error output to */
4093 int bVerbose = 0; /* If -verbose is present */
4094 int bGroupByParent = 0; /* If -groupbyparent is present */
4095 int i; /* To iterate through azArg[] */
4096 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4097 int rc; /* Return code */
4098 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
4099
4100 /*
4101 ** This SELECT statement returns one row for each foreign key constraint
4102 ** in the schema of the main database. The column values are:
4103 **
4104 ** 0. The text of an SQL statement similar to:
4105 **
danf9679312017-12-01 18:40:18 +00004106 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
drh2ce15c32017-07-11 13:34:40 +00004107 **
danf9679312017-12-01 18:40:18 +00004108 ** This SELECT is similar to the one that the foreign keys implementation
4109 ** needs to run internally on child tables. If there is an index that can
drh2ce15c32017-07-11 13:34:40 +00004110 ** be used to optimize this query, then it can also be used by the FK
4111 ** implementation to optimize DELETE or UPDATE statements on the parent
4112 ** table.
4113 **
4114 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4115 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4116 ** contains an index that can be used to optimize the query.
4117 **
4118 ** 2. Human readable text that describes the child table and columns. e.g.
4119 **
4120 ** "child_table(child_key1, child_key2)"
4121 **
4122 ** 3. Human readable text that describes the parent table and columns. e.g.
4123 **
4124 ** "parent_table(parent_key1, parent_key2)"
4125 **
4126 ** 4. A full CREATE INDEX statement for an index that could be used to
4127 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4128 **
4129 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4130 **
4131 ** 5. The name of the parent table.
4132 **
4133 ** These six values are used by the C logic below to generate the report.
4134 */
4135 const char *zSql =
4136 "SELECT "
danf9679312017-12-01 18:40:18 +00004137 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
drh2ce15c32017-07-11 13:34:40 +00004138 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4139 " || fkey_collate_clause("
4140 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4141 ", "
4142 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4143 " || group_concat('*=?', ' AND ') || ')'"
4144 ", "
4145 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4146 ", "
4147 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4148 ", "
4149 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4150 " || ' ON ' || quote(s.name) || '('"
4151 " || group_concat(quote(f.[from]) ||"
4152 " fkey_collate_clause("
4153 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4154 " || ');'"
4155 ", "
4156 " f.[table] "
4157 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4158 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4159 "GROUP BY s.name, f.id "
4160 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4161 ;
4162 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4163
4164 for(i=2; i<nArg; i++){
drhaf2770f2018-01-05 14:55:43 +00004165 int n = strlen30(azArg[i]);
drh2ce15c32017-07-11 13:34:40 +00004166 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4167 bVerbose = 1;
4168 }
4169 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4170 bGroupByParent = 1;
4171 zIndent = " ";
4172 }
4173 else{
4174 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4175 azArg[0], azArg[1]
4176 );
4177 return SQLITE_ERROR;
4178 }
4179 }
4180
4181 /* Register the fkey_collate_clause() SQL function */
4182 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4183 0, shellFkeyCollateClause, 0, 0
4184 );
4185
4186
4187 if( rc==SQLITE_OK ){
4188 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4189 }
4190 if( rc==SQLITE_OK ){
4191 sqlite3_bind_int(pSql, 1, bGroupByParent);
4192 }
4193
4194 if( rc==SQLITE_OK ){
4195 int rc2;
4196 char *zPrev = 0;
4197 while( SQLITE_ROW==sqlite3_step(pSql) ){
4198 int res = -1;
4199 sqlite3_stmt *pExplain = 0;
4200 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4201 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4202 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4203 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4204 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
4205 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
4206
4207 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4208 if( rc!=SQLITE_OK ) break;
4209 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4210 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4211 res = (
4212 0==sqlite3_strglob(zGlob, zPlan)
4213 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4214 );
4215 }
4216 rc = sqlite3_finalize(pExplain);
4217 if( rc!=SQLITE_OK ) break;
4218
4219 if( res<0 ){
4220 raw_printf(stderr, "Error: internal error");
4221 break;
4222 }else{
4223 if( bGroupByParent
4224 && (bVerbose || res==0)
4225 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4226 ){
4227 raw_printf(out, "-- Parent table %s\n", zParent);
4228 sqlite3_free(zPrev);
4229 zPrev = sqlite3_mprintf("%s", zParent);
4230 }
4231
4232 if( res==0 ){
4233 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4234 }else if( bVerbose ){
4235 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4236 zIndent, zFrom, zTarget
4237 );
4238 }
4239 }
4240 }
4241 sqlite3_free(zPrev);
4242
4243 if( rc!=SQLITE_OK ){
4244 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4245 }
4246
4247 rc2 = sqlite3_finalize(pSql);
4248 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4249 rc = rc2;
4250 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4251 }
4252 }else{
4253 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4254 }
4255
4256 return rc;
4257}
4258
4259/*
4260** Implementation of ".lint" dot command.
4261*/
4262static int lintDotCommand(
4263 ShellState *pState, /* Current shell tool state */
4264 char **azArg, /* Array of arguments passed to dot command */
4265 int nArg /* Number of entries in azArg[] */
4266){
4267 int n;
drhaf2770f2018-01-05 14:55:43 +00004268 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
drh2ce15c32017-07-11 13:34:40 +00004269 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4270 return lintFkeyIndexes(pState, azArg, nArg);
4271
4272 usage:
4273 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4274 raw_printf(stderr, "Where sub-commands are:\n");
4275 raw_printf(stderr, " fkey-indexes\n");
4276 return SQLITE_ERROR;
4277}
4278
danfd0245d2017-12-07 15:44:29 +00004279static void shellPrepare(
dand4b56e52017-12-12 20:04:59 +00004280 sqlite3 *db,
danfd0245d2017-12-07 15:44:29 +00004281 int *pRc,
4282 const char *zSql,
4283 sqlite3_stmt **ppStmt
4284){
4285 *ppStmt = 0;
4286 if( *pRc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004287 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
danfd0245d2017-12-07 15:44:29 +00004288 if( rc!=SQLITE_OK ){
4289 raw_printf(stderr, "sql error: %s (%d)\n",
dand4b56e52017-12-12 20:04:59 +00004290 sqlite3_errmsg(db), sqlite3_errcode(db)
danfd0245d2017-12-07 15:44:29 +00004291 );
4292 *pRc = rc;
4293 }
4294 }
4295}
4296
danac15e2d2017-12-14 19:15:07 +00004297static void shellPreparePrintf(
dan3f67ddf2017-12-13 20:04:53 +00004298 sqlite3 *db,
4299 int *pRc,
danac15e2d2017-12-14 19:15:07 +00004300 sqlite3_stmt **ppStmt,
4301 const char *zFmt,
4302 ...
dan3f67ddf2017-12-13 20:04:53 +00004303){
danac15e2d2017-12-14 19:15:07 +00004304 *ppStmt = 0;
4305 if( *pRc==SQLITE_OK ){
4306 va_list ap;
4307 char *z;
4308 va_start(ap, zFmt);
4309 z = sqlite3_vmprintf(zFmt, ap);
dan3f67ddf2017-12-13 20:04:53 +00004310 if( z==0 ){
4311 *pRc = SQLITE_NOMEM;
4312 }else{
4313 shellPrepare(db, pRc, z, ppStmt);
4314 sqlite3_free(z);
4315 }
dan3f67ddf2017-12-13 20:04:53 +00004316 }
4317}
4318
danfd0245d2017-12-07 15:44:29 +00004319static void shellFinalize(
4320 int *pRc,
4321 sqlite3_stmt *pStmt
4322){
dan25c12182017-12-07 21:03:33 +00004323 if( pStmt ){
4324 sqlite3 *db = sqlite3_db_handle(pStmt);
4325 int rc = sqlite3_finalize(pStmt);
4326 if( *pRc==SQLITE_OK ){
4327 if( rc!=SQLITE_OK ){
4328 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4329 }
4330 *pRc = rc;
4331 }
4332 }
danfd0245d2017-12-07 15:44:29 +00004333}
4334
4335static void shellReset(
4336 int *pRc,
4337 sqlite3_stmt *pStmt
4338){
4339 int rc = sqlite3_reset(pStmt);
dan5a78b812017-12-27 18:54:11 +00004340 if( *pRc==SQLITE_OK ){
4341 if( rc!=SQLITE_OK ){
4342 sqlite3 *db = sqlite3_db_handle(pStmt);
4343 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
4344 }
4345 *pRc = rc;
4346 }
danfd0245d2017-12-07 15:44:29 +00004347}
4348
dan88be0202017-12-09 17:58:02 +00004349/*
4350** Structure representing a single ".ar" command.
4351*/
4352typedef struct ArCommand ArCommand;
4353struct ArCommand {
4354 int eCmd; /* An AR_CMD_* value */
4355 const char *zFile; /* --file argument, or NULL */
4356 const char *zDir; /* --directory argument, or NULL */
4357 int bVerbose; /* True if --verbose */
dan5a78b812017-12-27 18:54:11 +00004358 int bZip; /* True if --zip */
dan88be0202017-12-09 17:58:02 +00004359 int nArg; /* Number of command arguments */
4360 char **azArg; /* Array of command arguments */
4361};
4362
4363/*
4364** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4365*/
dan0d0547f2017-12-14 15:40:42 +00004366static int arUsage(FILE *f){
4367 raw_printf(f,
4368"\n"
4369"Usage: .ar [OPTION...] [FILE...]\n"
4370"The .ar command manages sqlar archives.\n"
4371"\n"
4372"Examples:\n"
4373" .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4374" .ar -tf archive.sar # List members of archive.sar\n"
4375" .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4376"\n"
4377"Each command line must feature exactly one command option:\n"
4378" -c, --create Create a new archive\n"
4379" -u, --update Update or add files to an existing archive\n"
4380" -t, --list List contents of archive\n"
4381" -x, --extract Extract files from archive\n"
4382"\n"
4383"And zero or more optional options:\n"
4384" -v, --verbose Print each filename as it is processed\n"
4385" -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
4386" -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
4387"\n"
4388"See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4389"\n"
4390);
4391 return SQLITE_ERROR;
4392}
4393
4394/*
4395** Print an error message for the .ar command to stderr and return
4396** SQLITE_ERROR.
4397*/
4398static int arErrorMsg(const char *zFmt, ...){
4399 va_list ap;
4400 char *z;
4401 va_start(ap, zFmt);
4402 z = sqlite3_vmprintf(zFmt, ap);
4403 va_end(ap);
4404 raw_printf(stderr, "Error: %s (try \".ar --help\")\n", z);
4405 sqlite3_free(z);
dan88be0202017-12-09 17:58:02 +00004406 return SQLITE_ERROR;
4407}
4408
4409/*
4410** Values for ArCommand.eCmd.
4411*/
dand4b56e52017-12-12 20:04:59 +00004412#define AR_CMD_CREATE 1
4413#define AR_CMD_EXTRACT 2
4414#define AR_CMD_LIST 3
4415#define AR_CMD_UPDATE 4
dan0d0547f2017-12-14 15:40:42 +00004416#define AR_CMD_HELP 5
dand4b56e52017-12-12 20:04:59 +00004417
4418/*
4419** Other (non-command) switches.
4420*/
dan0d0547f2017-12-14 15:40:42 +00004421#define AR_SWITCH_VERBOSE 6
4422#define AR_SWITCH_FILE 7
4423#define AR_SWITCH_DIRECTORY 8
dan5a78b812017-12-27 18:54:11 +00004424#define AR_SWITCH_ZIP 9
dand4b56e52017-12-12 20:04:59 +00004425
4426static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
4427 switch( eSwitch ){
4428 case AR_CMD_CREATE:
4429 case AR_CMD_EXTRACT:
4430 case AR_CMD_LIST:
4431 case AR_CMD_UPDATE:
dan0d0547f2017-12-14 15:40:42 +00004432 case AR_CMD_HELP:
4433 if( pAr->eCmd ){
4434 return arErrorMsg("multiple command options");
4435 }
dand4b56e52017-12-12 20:04:59 +00004436 pAr->eCmd = eSwitch;
4437 break;
4438
4439 case AR_SWITCH_VERBOSE:
4440 pAr->bVerbose = 1;
4441 break;
dan5a78b812017-12-27 18:54:11 +00004442 case AR_SWITCH_ZIP:
4443 pAr->bZip = 1;
4444 break;
dand4b56e52017-12-12 20:04:59 +00004445
4446 case AR_SWITCH_FILE:
4447 pAr->zFile = zArg;
4448 break;
4449 case AR_SWITCH_DIRECTORY:
4450 pAr->zDir = zArg;
4451 break;
4452 }
4453
4454 return SQLITE_OK;
4455}
dan88be0202017-12-09 17:58:02 +00004456
4457/*
4458** Parse the command line for an ".ar" command. The results are written into
4459** structure (*pAr). SQLITE_OK is returned if the command line is parsed
4460** successfully, otherwise an error message is written to stderr and
4461** SQLITE_ERROR returned.
4462*/
4463static int arParseCommand(
4464 char **azArg, /* Array of arguments passed to dot command */
4465 int nArg, /* Number of entries in azArg[] */
4466 ArCommand *pAr /* Populate this object */
4467){
dand4b56e52017-12-12 20:04:59 +00004468 struct ArSwitch {
4469 char cShort;
4470 const char *zLong;
4471 int eSwitch;
4472 int bArg;
4473 } aSwitch[] = {
4474 { 'c', "create", AR_CMD_CREATE, 0 },
4475 { 'x', "extract", AR_CMD_EXTRACT, 0 },
4476 { 't', "list", AR_CMD_LIST, 0 },
4477 { 'u', "update", AR_CMD_UPDATE, 0 },
dan0d0547f2017-12-14 15:40:42 +00004478 { 'h', "help", AR_CMD_HELP, 0 },
dand4b56e52017-12-12 20:04:59 +00004479 { 'v', "verbose", AR_SWITCH_VERBOSE, 0 },
4480 { 'f', "file", AR_SWITCH_FILE, 1 },
dan5a78b812017-12-27 18:54:11 +00004481 { 'C', "directory", AR_SWITCH_DIRECTORY, 1 },
4482 { 'z', "zip", AR_SWITCH_ZIP, 0 }
dand4b56e52017-12-12 20:04:59 +00004483 };
4484 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
4485 struct ArSwitch *pEnd = &aSwitch[nSwitch];
4486
dan88be0202017-12-09 17:58:02 +00004487 if( nArg<=1 ){
dan0d0547f2017-12-14 15:40:42 +00004488 return arUsage(stderr);
dan88be0202017-12-09 17:58:02 +00004489 }else{
4490 char *z = azArg[1];
4491 memset(pAr, 0, sizeof(ArCommand));
4492
4493 if( z[0]!='-' ){
4494 /* Traditional style [tar] invocation */
4495 int i;
4496 int iArg = 2;
4497 for(i=0; z[i]; i++){
dand4b56e52017-12-12 20:04:59 +00004498 const char *zArg = 0;
4499 struct ArSwitch *pOpt;
4500 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4501 if( z[i]==pOpt->cShort ) break;
dan88be0202017-12-09 17:58:02 +00004502 }
dan0d0547f2017-12-14 15:40:42 +00004503 if( pOpt==pEnd ){
4504 return arErrorMsg("unrecognized option: %c", z[i]);
4505 }
dand4b56e52017-12-12 20:04:59 +00004506 if( pOpt->bArg ){
dan0d0547f2017-12-14 15:40:42 +00004507 if( iArg>=nArg ){
4508 return arErrorMsg("option requires an argument: %c",z[i]);
4509 }
dand4b56e52017-12-12 20:04:59 +00004510 zArg = azArg[iArg++];
4511 }
4512 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
dan88be0202017-12-09 17:58:02 +00004513 }
dan88be0202017-12-09 17:58:02 +00004514 pAr->nArg = nArg-iArg;
4515 if( pAr->nArg>0 ){
4516 pAr->azArg = &azArg[iArg];
4517 }
dand4b56e52017-12-12 20:04:59 +00004518 }else{
4519 /* Non-traditional invocation */
4520 int iArg;
4521 for(iArg=1; iArg<nArg; iArg++){
4522 int n;
4523 z = azArg[iArg];
4524 if( z[0]!='-' ){
4525 /* All remaining command line words are command arguments. */
4526 pAr->azArg = &azArg[iArg];
4527 pAr->nArg = nArg-iArg;
4528 break;
4529 }
drhaf2770f2018-01-05 14:55:43 +00004530 n = strlen30(z);
dand4b56e52017-12-12 20:04:59 +00004531
4532 if( z[1]!='-' ){
4533 int i;
4534 /* One or more short options */
4535 for(i=1; i<n; i++){
4536 const char *zArg = 0;
4537 struct ArSwitch *pOpt;
4538 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4539 if( z[i]==pOpt->cShort ) break;
4540 }
dan0d0547f2017-12-14 15:40:42 +00004541 if( pOpt==pEnd ){
4542 return arErrorMsg("unrecognized option: %c\n", z[i]);
4543 }
dand4b56e52017-12-12 20:04:59 +00004544 if( pOpt->bArg ){
4545 if( i<(n-1) ){
4546 zArg = &z[i+1];
4547 i = n;
4548 }else{
dan0d0547f2017-12-14 15:40:42 +00004549 if( iArg>=(nArg-1) ){
4550 return arErrorMsg("option requires an argument: %c\n",z[i]);
4551 }
dand4b56e52017-12-12 20:04:59 +00004552 zArg = azArg[++iArg];
4553 }
4554 }
4555 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
4556 }
4557 }else if( z[2]=='\0' ){
4558 /* A -- option, indicating that all remaining command line words
4559 ** are command arguments. */
4560 pAr->azArg = &azArg[iArg+1];
4561 pAr->nArg = nArg-iArg-1;
4562 break;
4563 }else{
4564 /* A long option */
4565 const char *zArg = 0; /* Argument for option, if any */
4566 struct ArSwitch *pMatch = 0; /* Matching option */
4567 struct ArSwitch *pOpt; /* Iterator */
4568 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
4569 const char *zLong = pOpt->zLong;
drhaf2770f2018-01-05 14:55:43 +00004570 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
dand4b56e52017-12-12 20:04:59 +00004571 if( pMatch ){
dan0d0547f2017-12-14 15:40:42 +00004572 return arErrorMsg("ambiguous option: %s",z);
dand4b56e52017-12-12 20:04:59 +00004573 }else{
4574 pMatch = pOpt;
4575 }
4576 }
4577 }
4578
4579 if( pMatch==0 ){
dan0d0547f2017-12-14 15:40:42 +00004580 return arErrorMsg("unrecognized option: %s", z);
dand4b56e52017-12-12 20:04:59 +00004581 }
4582 if( pMatch->bArg ){
dan0d0547f2017-12-14 15:40:42 +00004583 if( iArg>=(nArg-1) ){
4584 return arErrorMsg("option requires an argument: %s", z);
4585 }
dand4b56e52017-12-12 20:04:59 +00004586 zArg = azArg[++iArg];
4587 }
4588 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
4589 }
4590 }
dan88be0202017-12-09 17:58:02 +00004591 }
4592 }
4593
4594 return SQLITE_OK;
4595}
4596
4597/*
dan3f67ddf2017-12-13 20:04:53 +00004598** This function assumes that all arguments within the ArCommand.azArg[]
4599** array refer to archive members, as for the --extract or --list commands.
4600** It checks that each of them are present. If any specified file is not
4601** present in the archive, an error is printed to stderr and an error
4602** code returned. Otherwise, if all specified arguments are present in
4603** the archive, SQLITE_OK is returned.
4604**
4605** This function strips any trailing '/' characters from each argument.
4606** This is consistent with the way the [tar] command seems to work on
4607** Linux.
4608*/
4609static int arCheckEntries(sqlite3 *db, ArCommand *pAr){
4610 int rc = SQLITE_OK;
4611 if( pAr->nArg ){
4612 int i;
4613 sqlite3_stmt *pTest = 0;
4614
dan5a78b812017-12-27 18:54:11 +00004615 shellPreparePrintf(db, &rc, &pTest, "SELECT name FROM %s WHERE name=?1",
4616 pAr->bZip ? "zipfile(?2)" : "sqlar"
4617 );
4618 if( rc==SQLITE_OK && pAr->bZip ){
4619 sqlite3_bind_text(pTest, 2, pAr->zFile, -1, SQLITE_TRANSIENT);
4620 }
dan3f67ddf2017-12-13 20:04:53 +00004621 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
4622 char *z = pAr->azArg[i];
drhaf2770f2018-01-05 14:55:43 +00004623 int n = strlen30(z);
dan3f67ddf2017-12-13 20:04:53 +00004624 int bOk = 0;
4625 while( n>0 && z[n-1]=='/' ) n--;
4626 z[n] = '\0';
4627 sqlite3_bind_text(pTest, 1, z, -1, SQLITE_STATIC);
4628 if( SQLITE_ROW==sqlite3_step(pTest) ){
4629 bOk = 1;
4630 }
4631 shellReset(&rc, pTest);
4632 if( rc==SQLITE_OK && bOk==0 ){
4633 raw_printf(stderr, "not found in archive: %s\n", z);
4634 rc = SQLITE_ERROR;
4635 }
4636 }
4637 shellFinalize(&rc, pTest);
4638 }
4639
4640 return rc;
4641}
4642
4643/*
4644** Format a WHERE clause that can be used against the "sqlar" table to
4645** identify all archive members that match the command arguments held
4646** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
4647** The caller is responsible for eventually calling sqlite3_free() on
4648** any non-NULL (*pzWhere) value.
4649*/
4650static void arWhereClause(
4651 int *pRc,
4652 ArCommand *pAr,
danac15e2d2017-12-14 19:15:07 +00004653 char **pzWhere /* OUT: New WHERE clause */
dan3f67ddf2017-12-13 20:04:53 +00004654){
4655 char *zWhere = 0;
4656 if( *pRc==SQLITE_OK ){
danac15e2d2017-12-14 19:15:07 +00004657 if( pAr->nArg==0 ){
4658 zWhere = sqlite3_mprintf("1");
4659 }else{
4660 int i;
4661 const char *zSep = "";
4662 for(i=0; i<pAr->nArg; i++){
4663 const char *z = pAr->azArg[i];
4664 zWhere = sqlite3_mprintf(
4665 "%z%s name = '%q' OR name BETWEEN '%q/' AND '%q0'",
4666 zWhere, zSep, z, z, z
4667 );
4668 if( zWhere==0 ){
4669 *pRc = SQLITE_NOMEM;
4670 break;
4671 }
4672 zSep = " OR ";
dan3f67ddf2017-12-13 20:04:53 +00004673 }
dan3f67ddf2017-12-13 20:04:53 +00004674 }
4675 }
4676 *pzWhere = zWhere;
4677}
4678
4679/*
danb5090e42017-12-27 21:13:21 +00004680** Argument zMode must point to a buffer at least 11 bytes in size. This
4681** function populates this buffer with the string interpretation of
4682** the unix file mode passed as the second argument (e.g. "drwxr-xr-x").
4683*/
4684static void shellModeToString(char *zMode, int mode){
4685 int i;
4686
4687 /* Magic numbers copied from [man 2 stat] */
4688 if( mode & 0040000 ){
4689 zMode[0] = 'd';
4690 }else if( (mode & 0120000)==0120000 ){
4691 zMode[0] = 'l';
4692 }else{
4693 zMode[0] = '-';
4694 }
4695
4696 for(i=0; i<3; i++){
4697 int m = (mode >> ((2-i)*3));
4698 char *a = &zMode[1 + i*3];
4699 a[0] = (m & 0x4) ? 'r' : '-';
4700 a[1] = (m & 0x2) ? 'w' : '-';
4701 a[2] = (m & 0x1) ? 'x' : '-';
4702 }
4703 zMode[10] = '\0';
4704}
4705
4706/*
dan88be0202017-12-09 17:58:02 +00004707** Implementation of .ar "lisT" command.
4708*/
dand4b56e52017-12-12 20:04:59 +00004709static int arListCommand(ShellState *p, sqlite3 *db, ArCommand *pAr){
danb5090e42017-12-27 21:13:21 +00004710 const char *zSql = "SELECT %s FROM %s WHERE %s";
dan5a78b812017-12-27 18:54:11 +00004711 const char *zTbl = (pAr->bZip ? "zipfile(?)" : "sqlar");
danb5090e42017-12-27 21:13:21 +00004712 const char *azCols[] = {
4713 "name",
4714 "mode, sz, datetime(mtime, 'unixepoch'), name"
4715 };
dan5a78b812017-12-27 18:54:11 +00004716
dan3f67ddf2017-12-13 20:04:53 +00004717 char *zWhere = 0;
4718 sqlite3_stmt *pSql = 0;
4719 int rc;
4720
4721 rc = arCheckEntries(db, pAr);
4722 arWhereClause(&rc, pAr, &zWhere);
4723
danb5090e42017-12-27 21:13:21 +00004724 shellPreparePrintf(db, &rc, &pSql, zSql, azCols[pAr->bVerbose], zTbl, zWhere);
dan5a78b812017-12-27 18:54:11 +00004725 if( rc==SQLITE_OK && pAr->bZip ){
4726 sqlite3_bind_text(pSql, 1, pAr->zFile, -1, SQLITE_TRANSIENT);
4727 }
dan3f67ddf2017-12-13 20:04:53 +00004728 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
danb5090e42017-12-27 21:13:21 +00004729 if( pAr->bVerbose ){
4730 char zMode[11];
4731 shellModeToString(zMode, sqlite3_column_int(pSql, 0));
4732
4733 raw_printf(p->out, "%s % 10d %s %s\n", zMode,
4734 sqlite3_column_int(pSql, 1),
4735 sqlite3_column_text(pSql, 2),
4736 sqlite3_column_text(pSql, 3)
4737 );
4738 }else{
4739 raw_printf(p->out, "%s\n", sqlite3_column_text(pSql, 0));
4740 }
dan3f67ddf2017-12-13 20:04:53 +00004741 }
dan5a78b812017-12-27 18:54:11 +00004742
4743 shellFinalize(&rc, pSql);
dan3f67ddf2017-12-13 20:04:53 +00004744 return rc;
dan88be0202017-12-09 17:58:02 +00004745}
4746
4747
danfd0245d2017-12-07 15:44:29 +00004748/*
4749** Implementation of .ar "eXtract" command.
4750*/
dand4b56e52017-12-12 20:04:59 +00004751static int arExtractCommand(ShellState *p, sqlite3 *db, ArCommand *pAr){
dan25c12182017-12-07 21:03:33 +00004752 const char *zSql1 =
dand1b51d42017-12-16 19:11:26 +00004753 "SELECT "
4754 " :1 || name, "
dan5a78b812017-12-27 18:54:11 +00004755 " writefile(?1 || name, %s, mode, mtime) "
4756 "FROM %s WHERE (%s) AND (data IS NULL OR ?2 = 0)";
4757
4758 const char *azExtraArg[] = {
4759 "sqlar_uncompress(data, sz)",
4760 "zipfile_uncompress(data, sz, method)"
4761 };
4762 const char *azSource[] = {
4763 "sqlar", "zipfile(?3)"
4764 };
4765
4766
dan25c12182017-12-07 21:03:33 +00004767
danfd0245d2017-12-07 15:44:29 +00004768 sqlite3_stmt *pSql = 0;
4769 int rc = SQLITE_OK;
dan2ad09492017-12-09 18:28:22 +00004770 char *zDir = 0;
dan3f67ddf2017-12-13 20:04:53 +00004771 char *zWhere = 0;
danac15e2d2017-12-14 19:15:07 +00004772 int i;
dan2ad09492017-12-09 18:28:22 +00004773
dan3f67ddf2017-12-13 20:04:53 +00004774 /* If arguments are specified, check that they actually exist within
4775 ** the archive before proceeding. And formulate a WHERE clause to
4776 ** match them. */
4777 rc = arCheckEntries(db, pAr);
4778 arWhereClause(&rc, pAr, &zWhere);
4779
4780 if( rc==SQLITE_OK ){
4781 if( pAr->zDir ){
4782 zDir = sqlite3_mprintf("%s/", pAr->zDir);
4783 }else{
4784 zDir = sqlite3_mprintf("");
4785 }
4786 if( zDir==0 ) rc = SQLITE_NOMEM;
dan2ad09492017-12-09 18:28:22 +00004787 }
danfd0245d2017-12-07 15:44:29 +00004788
dan5a78b812017-12-27 18:54:11 +00004789 shellPreparePrintf(db, &rc, &pSql, zSql1,
4790 azExtraArg[pAr->bZip], azSource[pAr->bZip], zWhere
4791 );
4792
dan2ad09492017-12-09 18:28:22 +00004793 if( rc==SQLITE_OK ){
4794 sqlite3_bind_text(pSql, 1, zDir, -1, SQLITE_STATIC);
dan5a78b812017-12-27 18:54:11 +00004795 if( pAr->bZip ){
4796 sqlite3_bind_text(pSql, 3, pAr->zFile, -1, SQLITE_STATIC);
4797 }
dan25c12182017-12-07 21:03:33 +00004798
danac15e2d2017-12-14 19:15:07 +00004799 /* Run the SELECT statement twice. The first time, writefile() is called
4800 ** for all archive members that should be extracted. The second time,
4801 ** only for the directories. This is because the timestamps for
4802 ** extracted directories must be reset after they are populated (as
4803 ** populating them changes the timestamp). */
4804 for(i=0; i<2; i++){
4805 sqlite3_bind_int(pSql, 2, i);
4806 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
4807 if( i==0 && pAr->bVerbose ){
4808 raw_printf(p->out, "%s\n", sqlite3_column_text(pSql, 0));
4809 }
4810 }
4811 shellReset(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00004812 }
danac15e2d2017-12-14 19:15:07 +00004813 shellFinalize(&rc, pSql);
dan25c12182017-12-07 21:03:33 +00004814 }
dan25c12182017-12-07 21:03:33 +00004815
dan2ad09492017-12-09 18:28:22 +00004816 sqlite3_free(zDir);
dan3f67ddf2017-12-13 20:04:53 +00004817 sqlite3_free(zWhere);
danfd0245d2017-12-07 15:44:29 +00004818 return rc;
4819}
4820
dan1ad3f612017-12-11 20:22:02 +00004821
danfd0245d2017-12-07 15:44:29 +00004822/*
dan06741a32017-12-13 20:17:18 +00004823** Implementation of .ar "create" and "update" commands.
danfd0245d2017-12-07 15:44:29 +00004824**
4825** Create the "sqlar" table in the database if it does not already exist.
4826** Then add each file in the azFile[] array to the archive. Directories
4827** are added recursively. If argument bVerbose is non-zero, a message is
4828** printed on stdout for each file archived.
dan06741a32017-12-13 20:17:18 +00004829**
4830** The create command is the same as update, except that it drops
4831** any existing "sqlar" table before beginning.
danfd0245d2017-12-07 15:44:29 +00004832*/
dan06741a32017-12-13 20:17:18 +00004833static int arCreateUpdate(
danfd0245d2017-12-07 15:44:29 +00004834 ShellState *p, /* Shell state pointer */
dand4b56e52017-12-12 20:04:59 +00004835 sqlite3 *db,
dan06741a32017-12-13 20:17:18 +00004836 ArCommand *pAr, /* Command arguments and options */
4837 int bUpdate
danfd0245d2017-12-07 15:44:29 +00004838){
dand4b56e52017-12-12 20:04:59 +00004839 const char *zSql = "SELECT name, mode, mtime, data FROM fsdir(?, ?)";
4840 const char *zCreate =
danfd0245d2017-12-07 15:44:29 +00004841 "CREATE TABLE IF NOT EXISTS sqlar("
4842 "name TEXT PRIMARY KEY, -- name of the file\n"
4843 "mode INT, -- access permissions\n"
4844 "mtime INT, -- last modification time\n"
4845 "sz INT, -- original file size\n"
4846 "data BLOB -- compressed content\n"
dand4b56e52017-12-12 20:04:59 +00004847 ")";
4848 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
dand1b51d42017-12-16 19:11:26 +00004849 const char *zInsert = "REPLACE INTO sqlar VALUES(?,?,?,?,sqlar_compress(?))";
danfd0245d2017-12-07 15:44:29 +00004850
4851 sqlite3_stmt *pStmt = 0; /* Directory traverser */
4852 sqlite3_stmt *pInsert = 0; /* Compilation of zInsert */
4853 int i; /* For iterating through azFile[] */
4854 int rc; /* Return code */
4855
dan5a78b812017-12-27 18:54:11 +00004856 assert( pAr->bZip==0 );
4857
dand4b56e52017-12-12 20:04:59 +00004858 rc = sqlite3_exec(db, "SAVEPOINT ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00004859 if( rc!=SQLITE_OK ) return rc;
4860
dan06741a32017-12-13 20:17:18 +00004861 if( bUpdate==0 ){
4862 rc = sqlite3_exec(db, zDrop, 0, 0, 0);
4863 if( rc!=SQLITE_OK ) return rc;
4864 }
dand4b56e52017-12-12 20:04:59 +00004865
4866 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
4867 shellPrepare(db, &rc, zInsert, &pInsert);
4868 shellPrepare(db, &rc, zSql, &pStmt);
dan1ad3f612017-12-11 20:22:02 +00004869 sqlite3_bind_text(pStmt, 2, pAr->zDir, -1, SQLITE_STATIC);
danfd0245d2017-12-07 15:44:29 +00004870
dan88be0202017-12-09 17:58:02 +00004871 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
4872 sqlite3_bind_text(pStmt, 1, pAr->azArg[i], -1, SQLITE_STATIC);
danfd0245d2017-12-07 15:44:29 +00004873 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
4874 int sz;
4875 const char *zName = (const char*)sqlite3_column_text(pStmt, 0);
4876 int mode = sqlite3_column_int(pStmt, 1);
4877 unsigned int mtime = sqlite3_column_int(pStmt, 2);
4878
dan88be0202017-12-09 17:58:02 +00004879 if( pAr->bVerbose ){
dan0d0547f2017-12-14 15:40:42 +00004880 raw_printf(p->out, "%s\n", zName);
danfd0245d2017-12-07 15:44:29 +00004881 }
4882
4883 sqlite3_bind_text(pInsert, 1, zName, -1, SQLITE_STATIC);
4884 sqlite3_bind_int(pInsert, 2, mode);
4885 sqlite3_bind_int64(pInsert, 3, (sqlite3_int64)mtime);
4886
4887 if( S_ISDIR(mode) ){
4888 sz = 0;
4889 sqlite3_bind_null(pInsert, 5);
danfd0245d2017-12-07 15:44:29 +00004890 }else{
dand1b51d42017-12-16 19:11:26 +00004891 sqlite3_bind_value(pInsert, 5, sqlite3_column_value(pStmt, 3));
4892 if( S_ISLNK(mode) ){
4893 sz = -1;
danfd0245d2017-12-07 15:44:29 +00004894 }else{
dand1b51d42017-12-16 19:11:26 +00004895 sz = sqlite3_column_bytes(pStmt, 3);
danfd0245d2017-12-07 15:44:29 +00004896 }
4897 }
4898
dand1b51d42017-12-16 19:11:26 +00004899 sqlite3_bind_int(pInsert, 4, sz);
4900 sqlite3_step(pInsert);
4901 rc = sqlite3_reset(pInsert);
danfd0245d2017-12-07 15:44:29 +00004902 }
4903 shellReset(&rc, pStmt);
4904 }
4905
4906 if( rc!=SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004907 sqlite3_exec(db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00004908 }else{
dand4b56e52017-12-12 20:04:59 +00004909 rc = sqlite3_exec(db, "RELEASE ar;", 0, 0, 0);
danfd0245d2017-12-07 15:44:29 +00004910 }
4911 shellFinalize(&rc, pStmt);
4912 shellFinalize(&rc, pInsert);
danfd0245d2017-12-07 15:44:29 +00004913 return rc;
4914}
4915
4916/*
dan06741a32017-12-13 20:17:18 +00004917** Implementation of .ar "Create" command.
4918**
4919** Create the "sqlar" table in the database if it does not already exist.
4920** Then add each file in the azFile[] array to the archive. Directories
4921** are added recursively. If argument bVerbose is non-zero, a message is
4922** printed on stdout for each file archived.
4923*/
4924static int arCreateCommand(
4925 ShellState *p, /* Shell state pointer */
4926 sqlite3 *db,
4927 ArCommand *pAr /* Command arguments and options */
4928){
4929 return arCreateUpdate(p, db, pAr, 0);
4930}
4931
4932/*
4933** Implementation of .ar "Update" command.
4934*/
4935static int arUpdateCmd(ShellState *p, sqlite3 *db, ArCommand *pAr){
4936 return arCreateUpdate(p, db, pAr, 1);
4937}
4938
4939
4940/*
danfd0245d2017-12-07 15:44:29 +00004941** Implementation of ".ar" dot command.
4942*/
4943static int arDotCommand(
4944 ShellState *pState, /* Current shell tool state */
4945 char **azArg, /* Array of arguments passed to dot command */
4946 int nArg /* Number of entries in azArg[] */
4947){
dan88be0202017-12-09 17:58:02 +00004948 ArCommand cmd;
4949 int rc;
4950 rc = arParseCommand(azArg, nArg, &cmd);
4951 if( rc==SQLITE_OK ){
dand4b56e52017-12-12 20:04:59 +00004952 sqlite3 *db = 0; /* Database handle to use as archive */
4953
dan5a78b812017-12-27 18:54:11 +00004954 if( cmd.bZip ){
4955 if( cmd.zFile==0 ){
4956 raw_printf(stderr, "zip format requires a --file switch\n");
4957 return SQLITE_ERROR;
4958 }else
4959 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
4960 raw_printf(stderr, "zip archives are read-only\n");
4961 return SQLITE_ERROR;
4962 }
4963 db = pState->db;
4964 }else if( cmd.zFile ){
dand4b56e52017-12-12 20:04:59 +00004965 int flags;
4966 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
4967 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
4968 }else{
4969 flags = SQLITE_OPEN_READONLY;
4970 }
4971 rc = sqlite3_open_v2(cmd.zFile, &db, flags, 0);
4972 if( rc!=SQLITE_OK ){
4973 raw_printf(stderr, "cannot open file: %s (%s)\n",
4974 cmd.zFile, sqlite3_errmsg(db)
4975 );
4976 sqlite3_close(db);
4977 return rc;
4978 }
danece4b0c2017-12-12 20:28:36 +00004979 sqlite3_fileio_init(db, 0, 0);
mistachkin3acaf4c2018-01-05 00:53:03 +00004980#ifdef SQLITE_HAVE_ZLIB
dand1b51d42017-12-16 19:11:26 +00004981 sqlite3_sqlar_init(db, 0, 0);
mistachkin3acaf4c2018-01-05 00:53:03 +00004982#endif
dand4b56e52017-12-12 20:04:59 +00004983 }else{
4984 db = pState->db;
4985 }
4986
dan88be0202017-12-09 17:58:02 +00004987 switch( cmd.eCmd ){
4988 case AR_CMD_CREATE:
dand4b56e52017-12-12 20:04:59 +00004989 rc = arCreateCommand(pState, db, &cmd);
dan88be0202017-12-09 17:58:02 +00004990 break;
danfd0245d2017-12-07 15:44:29 +00004991
dan88be0202017-12-09 17:58:02 +00004992 case AR_CMD_EXTRACT:
dand4b56e52017-12-12 20:04:59 +00004993 rc = arExtractCommand(pState, db, &cmd);
dan88be0202017-12-09 17:58:02 +00004994 break;
4995
4996 case AR_CMD_LIST:
dand4b56e52017-12-12 20:04:59 +00004997 rc = arListCommand(pState, db, &cmd);
dan88be0202017-12-09 17:58:02 +00004998 break;
4999
dan0d0547f2017-12-14 15:40:42 +00005000 case AR_CMD_HELP:
5001 arUsage(pState->out);
5002 break;
5003
dan88be0202017-12-09 17:58:02 +00005004 default:
5005 assert( cmd.eCmd==AR_CMD_UPDATE );
dand4b56e52017-12-12 20:04:59 +00005006 rc = arUpdateCmd(pState, db, &cmd);
dan88be0202017-12-09 17:58:02 +00005007 break;
danfd0245d2017-12-07 15:44:29 +00005008 }
dand4b56e52017-12-12 20:04:59 +00005009
5010 if( cmd.zFile ){
5011 sqlite3_close(db);
5012 }
danfd0245d2017-12-07 15:44:29 +00005013 }
5014
dan88be0202017-12-09 17:58:02 +00005015 return rc;
danfd0245d2017-12-07 15:44:29 +00005016}
5017
dan43efc182017-12-19 17:42:13 +00005018/*
5019** Implementation of ".expert" dot command.
5020*/
5021static int expertDotCommand(
5022 ShellState *pState, /* Current shell tool state */
5023 char **azArg, /* Array of arguments passed to dot command */
5024 int nArg /* Number of entries in azArg[] */
5025){
5026 int rc = SQLITE_OK;
5027 char *zErr = 0;
5028 int i;
5029 int iSample = 0;
5030
5031 assert( pState->expert.pExpert==0 );
5032 memset(&pState->expert, 0, sizeof(ExpertInfo));
5033
5034 for(i=1; rc==SQLITE_OK && i<nArg; i++){
5035 char *z = azArg[i];
5036 int n;
5037 if( z[0]=='-' && z[1]=='-' ) z++;
drhaf2770f2018-01-05 14:55:43 +00005038 n = strlen30(z);
dan43efc182017-12-19 17:42:13 +00005039 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
5040 pState->expert.bVerbose = 1;
5041 }
5042 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
5043 if( i==(nArg-1) ){
5044 raw_printf(stderr, "option requires an argument: %s\n", z);
5045 rc = SQLITE_ERROR;
5046 }else{
5047 iSample = (int)integerValue(azArg[++i]);
5048 if( iSample<0 || iSample>100 ){
5049 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
5050 rc = SQLITE_ERROR;
5051 }
5052 }
5053 }
5054 else{
5055 raw_printf(stderr, "unknown option: %s\n", z);
5056 rc = SQLITE_ERROR;
5057 }
5058 }
5059
5060 if( rc==SQLITE_OK ){
5061 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
5062 if( pState->expert.pExpert==0 ){
5063 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
5064 rc = SQLITE_ERROR;
5065 }else{
5066 sqlite3_expert_config(
5067 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
5068 );
5069 }
5070 }
5071
5072 return rc;
5073}
5074
drh2ce15c32017-07-11 13:34:40 +00005075
5076/*
5077** If an input line begins with "." then invoke this routine to
5078** process that line.
5079**
5080** Return 1 on error, 2 to exit, and 0 otherwise.
5081*/
5082static int do_meta_command(char *zLine, ShellState *p){
5083 int h = 1;
5084 int nArg = 0;
5085 int n, c;
5086 int rc = 0;
5087 char *azArg[50];
5088
dan43efc182017-12-19 17:42:13 +00005089 if( p->expert.pExpert ){
5090 expertFinish(p, 1, 0);
5091 }
5092
drh2ce15c32017-07-11 13:34:40 +00005093 /* Parse the input line into tokens.
5094 */
5095 while( zLine[h] && nArg<ArraySize(azArg) ){
5096 while( IsSpace(zLine[h]) ){ h++; }
5097 if( zLine[h]==0 ) break;
5098 if( zLine[h]=='\'' || zLine[h]=='"' ){
5099 int delim = zLine[h++];
5100 azArg[nArg++] = &zLine[h];
5101 while( zLine[h] && zLine[h]!=delim ){
5102 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
5103 h++;
5104 }
5105 if( zLine[h]==delim ){
5106 zLine[h++] = 0;
5107 }
5108 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
5109 }else{
5110 azArg[nArg++] = &zLine[h];
5111 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5112 if( zLine[h] ) zLine[h++] = 0;
5113 resolve_backslashes(azArg[nArg-1]);
5114 }
5115 }
5116
5117 /* Process the input line.
5118 */
5119 if( nArg==0 ) return 0; /* no tokens, no error */
5120 n = strlen30(azArg[0]);
5121 c = azArg[0][0];
5122
5123#ifndef SQLITE_OMIT_AUTHORIZATION
5124 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5125 if( nArg!=2 ){
5126 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5127 rc = 1;
5128 goto meta_command_exit;
5129 }
5130 open_db(p, 0);
5131 if( booleanValue(azArg[1]) ){
5132 sqlite3_set_authorizer(p->db, shellAuth, p);
5133 }else{
5134 sqlite3_set_authorizer(p->db, 0, 0);
5135 }
5136 }else
5137#endif
5138
danfd0245d2017-12-07 15:44:29 +00005139#ifndef SQLITE_OMIT_VIRTUALTABLE
5140 if( c=='a' && strncmp(azArg[0], "ar", n)==0 ){
5141 open_db(p, 0);
5142 rc = arDotCommand(p, azArg, nArg);
5143 }else
5144#endif
5145
drh2ce15c32017-07-11 13:34:40 +00005146 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5147 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5148 ){
5149 const char *zDestFile = 0;
5150 const char *zDb = 0;
5151 sqlite3 *pDest;
5152 sqlite3_backup *pBackup;
5153 int j;
5154 for(j=1; j<nArg; j++){
5155 const char *z = azArg[j];
5156 if( z[0]=='-' ){
5157 while( z[0]=='-' ) z++;
5158 /* No options to process at this time */
5159 {
5160 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
5161 return 1;
5162 }
5163 }else if( zDestFile==0 ){
5164 zDestFile = azArg[j];
5165 }else if( zDb==0 ){
5166 zDb = zDestFile;
5167 zDestFile = azArg[j];
5168 }else{
5169 raw_printf(stderr, "too many arguments to .backup\n");
5170 return 1;
5171 }
5172 }
5173 if( zDestFile==0 ){
5174 raw_printf(stderr, "missing FILENAME argument on .backup\n");
5175 return 1;
5176 }
5177 if( zDb==0 ) zDb = "main";
5178 rc = sqlite3_open(zDestFile, &pDest);
5179 if( rc!=SQLITE_OK ){
5180 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
5181 sqlite3_close(pDest);
5182 return 1;
5183 }
5184 open_db(p, 0);
5185 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5186 if( pBackup==0 ){
5187 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5188 sqlite3_close(pDest);
5189 return 1;
5190 }
5191 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5192 sqlite3_backup_finish(pBackup);
5193 if( rc==SQLITE_DONE ){
5194 rc = 0;
5195 }else{
5196 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
5197 rc = 1;
5198 }
5199 sqlite3_close(pDest);
5200 }else
5201
5202 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5203 if( nArg==2 ){
5204 bail_on_error = booleanValue(azArg[1]);
5205 }else{
5206 raw_printf(stderr, "Usage: .bail on|off\n");
5207 rc = 1;
5208 }
5209 }else
5210
5211 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5212 if( nArg==2 ){
5213 if( booleanValue(azArg[1]) ){
5214 setBinaryMode(p->out, 1);
5215 }else{
5216 setTextMode(p->out, 1);
5217 }
5218 }else{
5219 raw_printf(stderr, "Usage: .binary on|off\n");
5220 rc = 1;
5221 }
5222 }else
5223
5224 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5225 if( nArg==2 ){
5226#if defined(_WIN32) || defined(WIN32)
5227 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5228 rc = !SetCurrentDirectoryW(z);
5229 sqlite3_free(z);
5230#else
5231 rc = chdir(azArg[1]);
5232#endif
5233 if( rc ){
5234 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5235 rc = 1;
5236 }
5237 }else{
5238 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5239 rc = 1;
5240 }
5241 }else
5242
5243 /* The undocumented ".breakpoint" command causes a call to the no-op
5244 ** routine named test_breakpoint().
5245 */
5246 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5247 test_breakpoint();
5248 }else
5249
5250 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5251 if( nArg==2 ){
5252 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
5253 }else{
5254 raw_printf(stderr, "Usage: .changes on|off\n");
5255 rc = 1;
5256 }
5257 }else
5258
5259 /* Cancel output redirection, if it is currently set (by .testcase)
5260 ** Then read the content of the testcase-out.txt file and compare against
5261 ** azArg[1]. If there are differences, report an error and exit.
5262 */
5263 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5264 char *zRes = 0;
5265 output_reset(p);
5266 if( nArg!=2 ){
5267 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
5268 rc = 2;
5269 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
5270 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5271 rc = 2;
5272 }else if( testcase_glob(azArg[1],zRes)==0 ){
5273 utf8_printf(stderr,
5274 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5275 p->zTestcase, azArg[1], zRes);
drhf30d3452017-10-17 13:44:46 +00005276 rc = 1;
drh2ce15c32017-07-11 13:34:40 +00005277 }else{
5278 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
5279 p->nCheck++;
5280 }
5281 sqlite3_free(zRes);
5282 }else
5283
5284 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5285 if( nArg==2 ){
5286 tryToClone(p, azArg[1]);
5287 }else{
5288 raw_printf(stderr, "Usage: .clone FILENAME\n");
5289 rc = 1;
5290 }
5291 }else
5292
5293 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
5294 ShellState data;
5295 char *zErrMsg = 0;
5296 open_db(p, 0);
5297 memcpy(&data, p, sizeof(data));
5298 data.showHeader = 0;
5299 data.cMode = data.mode = MODE_List;
5300 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
5301 data.cnt = 0;
5302 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5303 callback, &data, &zErrMsg);
5304 if( zErrMsg ){
5305 utf8_printf(stderr,"Error: %s\n", zErrMsg);
5306 sqlite3_free(zErrMsg);
5307 rc = 1;
5308 }
5309 }else
5310
5311 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
5312 rc = shell_dbinfo_command(p, nArg, azArg);
5313 }else
5314
5315 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
5316 const char *zLike = 0;
5317 int i;
5318 int savedShowHeader = p->showHeader;
5319 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
5320 for(i=1; i<nArg; i++){
5321 if( azArg[i][0]=='-' ){
5322 const char *z = azArg[i]+1;
5323 if( z[0]=='-' ) z++;
5324 if( strcmp(z,"preserve-rowids")==0 ){
5325#ifdef SQLITE_OMIT_VIRTUALTABLE
5326 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5327 " with SQLITE_OMIT_VIRTUALTABLE\n");
5328 rc = 1;
5329 goto meta_command_exit;
5330#else
5331 ShellSetFlag(p, SHFLG_PreserveRowid);
5332#endif
5333 }else
5334 if( strcmp(z,"newlines")==0 ){
5335 ShellSetFlag(p, SHFLG_Newlines);
5336 }else
5337 {
5338 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
5339 rc = 1;
5340 goto meta_command_exit;
5341 }
5342 }else if( zLike ){
5343 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
5344 "?--newlines? ?LIKE-PATTERN?\n");
5345 rc = 1;
5346 goto meta_command_exit;
5347 }else{
5348 zLike = azArg[i];
5349 }
5350 }
5351 open_db(p, 0);
5352 /* When playing back a "dump", the content might appear in an order
5353 ** which causes immediate foreign key constraints to be violated.
5354 ** So disable foreign-key constraint enforcement to prevent problems. */
5355 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
5356 raw_printf(p->out, "BEGIN TRANSACTION;\n");
5357 p->writableSchema = 0;
5358 p->showHeader = 0;
5359 /* Set writable_schema=ON since doing so forces SQLite to initialize
5360 ** as much of the schema as it can even if the sqlite_master table is
5361 ** corrupt. */
5362 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5363 p->nErr = 0;
5364 if( zLike==0 ){
5365 run_schema_dump_query(p,
5366 "SELECT name, type, sql FROM sqlite_master "
5367 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5368 );
5369 run_schema_dump_query(p,
5370 "SELECT name, type, sql FROM sqlite_master "
5371 "WHERE name=='sqlite_sequence'"
5372 );
5373 run_table_dump_query(p,
5374 "SELECT sql FROM sqlite_master "
5375 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5376 );
5377 }else{
5378 char *zSql;
5379 zSql = sqlite3_mprintf(
5380 "SELECT name, type, sql FROM sqlite_master "
5381 "WHERE tbl_name LIKE %Q AND type=='table'"
5382 " AND sql NOT NULL", zLike);
5383 run_schema_dump_query(p,zSql);
5384 sqlite3_free(zSql);
5385 zSql = sqlite3_mprintf(
5386 "SELECT sql FROM sqlite_master "
5387 "WHERE sql NOT NULL"
5388 " AND type IN ('index','trigger','view')"
5389 " AND tbl_name LIKE %Q", zLike);
5390 run_table_dump_query(p, zSql, 0);
5391 sqlite3_free(zSql);
5392 }
5393 if( p->writableSchema ){
5394 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
5395 p->writableSchema = 0;
5396 }
5397 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5398 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
5399 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5400 p->showHeader = savedShowHeader;
5401 }else
5402
5403 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5404 if( nArg==2 ){
5405 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
5406 }else{
5407 raw_printf(stderr, "Usage: .echo on|off\n");
5408 rc = 1;
5409 }
5410 }else
5411
5412 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5413 if( nArg==2 ){
5414 if( strcmp(azArg[1],"full")==0 ){
drhada70452017-12-21 21:02:27 +00005415 p->autoEQP = AUTOEQP_full;
5416 }else if( strcmp(azArg[1],"trigger")==0 ){
5417 p->autoEQP = AUTOEQP_trigger;
drh2ce15c32017-07-11 13:34:40 +00005418 }else{
5419 p->autoEQP = booleanValue(azArg[1]);
5420 }
5421 }else{
drhada70452017-12-21 21:02:27 +00005422 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
drh2ce15c32017-07-11 13:34:40 +00005423 rc = 1;
5424 }
5425 }else
5426
5427 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
5428 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
5429 rc = 2;
5430 }else
5431
5432 /* The ".explain" command is automatic now. It is largely pointless. It
5433 ** retained purely for backwards compatibility */
5434 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
5435 int val = 1;
5436 if( nArg>=2 ){
5437 if( strcmp(azArg[1],"auto")==0 ){
5438 val = 99;
5439 }else{
5440 val = booleanValue(azArg[1]);
5441 }
5442 }
5443 if( val==1 && p->mode!=MODE_Explain ){
5444 p->normalMode = p->mode;
5445 p->mode = MODE_Explain;
5446 p->autoExplain = 0;
5447 }else if( val==0 ){
5448 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5449 p->autoExplain = 0;
5450 }else if( val==99 ){
5451 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5452 p->autoExplain = 1;
5453 }
5454 }else
5455
dan43efc182017-12-19 17:42:13 +00005456 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
5457 open_db(p, 0);
5458 expertDotCommand(p, azArg, nArg);
5459 }else
5460
drh2ce15c32017-07-11 13:34:40 +00005461 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
5462 ShellState data;
5463 char *zErrMsg = 0;
5464 int doStats = 0;
5465 memcpy(&data, p, sizeof(data));
5466 data.showHeader = 0;
5467 data.cMode = data.mode = MODE_Semi;
5468 if( nArg==2 && optionMatch(azArg[1], "indent") ){
5469 data.cMode = data.mode = MODE_Pretty;
5470 nArg = 1;
5471 }
5472 if( nArg!=1 ){
5473 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
5474 rc = 1;
5475 goto meta_command_exit;
5476 }
5477 open_db(p, 0);
5478 rc = sqlite3_exec(p->db,
5479 "SELECT sql FROM"
5480 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5481 " FROM sqlite_master UNION ALL"
5482 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5483 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
5484 "ORDER BY rowid",
5485 callback, &data, &zErrMsg
5486 );
5487 if( rc==SQLITE_OK ){
5488 sqlite3_stmt *pStmt;
5489 rc = sqlite3_prepare_v2(p->db,
5490 "SELECT rowid FROM sqlite_master"
5491 " WHERE name GLOB 'sqlite_stat[134]'",
5492 -1, &pStmt, 0);
5493 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5494 sqlite3_finalize(pStmt);
5495 }
5496 if( doStats==0 ){
5497 raw_printf(p->out, "/* No STAT tables available */\n");
5498 }else{
5499 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5500 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5501 callback, &data, &zErrMsg);
5502 data.cMode = data.mode = MODE_Insert;
5503 data.zDestTable = "sqlite_stat1";
5504 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5505 shell_callback, &data,&zErrMsg);
5506 data.zDestTable = "sqlite_stat3";
5507 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5508 shell_callback, &data,&zErrMsg);
5509 data.zDestTable = "sqlite_stat4";
5510 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5511 shell_callback, &data, &zErrMsg);
5512 raw_printf(p->out, "ANALYZE sqlite_master;\n");
5513 }
5514 }else
5515
5516 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5517 if( nArg==2 ){
5518 p->showHeader = booleanValue(azArg[1]);
5519 }else{
5520 raw_printf(stderr, "Usage: .headers on|off\n");
5521 rc = 1;
5522 }
5523 }else
5524
5525 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
5526 utf8_printf(p->out, "%s", zHelp);
5527 }else
5528
5529 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
5530 char *zTable; /* Insert data into this table */
5531 char *zFile; /* Name of file to extra content from */
5532 sqlite3_stmt *pStmt = NULL; /* A statement */
5533 int nCol; /* Number of columns in the table */
5534 int nByte; /* Number of bytes in an SQL string */
5535 int i, j; /* Loop counters */
5536 int needCommit; /* True to COMMIT or ROLLBACK at end */
5537 int nSep; /* Number of bytes in p->colSeparator[] */
5538 char *zSql; /* An SQL statement */
5539 ImportCtx sCtx; /* Reader context */
5540 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5541 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
5542
5543 if( nArg!=3 ){
5544 raw_printf(stderr, "Usage: .import FILE TABLE\n");
5545 goto meta_command_exit;
5546 }
5547 zFile = azArg[1];
5548 zTable = azArg[2];
5549 seenInterrupt = 0;
5550 memset(&sCtx, 0, sizeof(sCtx));
5551 open_db(p, 0);
5552 nSep = strlen30(p->colSeparator);
5553 if( nSep==0 ){
5554 raw_printf(stderr,
5555 "Error: non-null column separator required for import\n");
5556 return 1;
5557 }
5558 if( nSep>1 ){
5559 raw_printf(stderr, "Error: multi-character column separators not allowed"
5560 " for import\n");
5561 return 1;
5562 }
5563 nSep = strlen30(p->rowSeparator);
5564 if( nSep==0 ){
5565 raw_printf(stderr, "Error: non-null row separator required for import\n");
5566 return 1;
5567 }
5568 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5569 /* When importing CSV (only), if the row separator is set to the
5570 ** default output row separator, change it to the default input
5571 ** row separator. This avoids having to maintain different input
5572 ** and output row separators. */
5573 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5574 nSep = strlen30(p->rowSeparator);
5575 }
5576 if( nSep>1 ){
5577 raw_printf(stderr, "Error: multi-character row separators not allowed"
5578 " for import\n");
5579 return 1;
5580 }
5581 sCtx.zFile = zFile;
5582 sCtx.nLine = 1;
5583 if( sCtx.zFile[0]=='|' ){
5584#ifdef SQLITE_OMIT_POPEN
5585 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
5586 return 1;
5587#else
5588 sCtx.in = popen(sCtx.zFile+1, "r");
5589 sCtx.zFile = "<pipe>";
5590 xCloser = pclose;
5591#endif
5592 }else{
5593 sCtx.in = fopen(sCtx.zFile, "rb");
5594 xCloser = fclose;
5595 }
5596 if( p->mode==MODE_Ascii ){
5597 xRead = ascii_read_one_field;
5598 }else{
5599 xRead = csv_read_one_field;
5600 }
5601 if( sCtx.in==0 ){
5602 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
5603 return 1;
5604 }
5605 sCtx.cColSep = p->colSeparator[0];
5606 sCtx.cRowSep = p->rowSeparator[0];
5607 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
5608 if( zSql==0 ){
5609 raw_printf(stderr, "Error: out of memory\n");
5610 xCloser(sCtx.in);
5611 return 1;
5612 }
5613 nByte = strlen30(zSql);
5614 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5615 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
5616 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
5617 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5618 char cSep = '(';
5619 while( xRead(&sCtx) ){
5620 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
5621 cSep = ',';
5622 if( sCtx.cTerm!=sCtx.cColSep ) break;
5623 }
5624 if( cSep=='(' ){
5625 sqlite3_free(zCreate);
5626 sqlite3_free(sCtx.z);
5627 xCloser(sCtx.in);
5628 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
5629 return 1;
5630 }
5631 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5632 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5633 sqlite3_free(zCreate);
5634 if( rc ){
5635 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
5636 sqlite3_errmsg(p->db));
5637 sqlite3_free(sCtx.z);
5638 xCloser(sCtx.in);
5639 return 1;
5640 }
5641 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5642 }
5643 sqlite3_free(zSql);
5644 if( rc ){
5645 if (pStmt) sqlite3_finalize(pStmt);
5646 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
5647 xCloser(sCtx.in);
5648 return 1;
5649 }
5650 nCol = sqlite3_column_count(pStmt);
5651 sqlite3_finalize(pStmt);
5652 pStmt = 0;
5653 if( nCol==0 ) return 0; /* no columns, no error */
5654 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
5655 if( zSql==0 ){
5656 raw_printf(stderr, "Error: out of memory\n");
5657 xCloser(sCtx.in);
5658 return 1;
5659 }
5660 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
5661 j = strlen30(zSql);
5662 for(i=1; i<nCol; i++){
5663 zSql[j++] = ',';
5664 zSql[j++] = '?';
5665 }
5666 zSql[j++] = ')';
5667 zSql[j] = 0;
5668 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5669 sqlite3_free(zSql);
5670 if( rc ){
5671 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
5672 if (pStmt) sqlite3_finalize(pStmt);
5673 xCloser(sCtx.in);
5674 return 1;
5675 }
5676 needCommit = sqlite3_get_autocommit(p->db);
5677 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
5678 do{
5679 int startLine = sCtx.nLine;
5680 for(i=0; i<nCol; i++){
5681 char *z = xRead(&sCtx);
5682 /*
5683 ** Did we reach end-of-file before finding any columns?
5684 ** If so, stop instead of NULL filling the remaining columns.
5685 */
5686 if( z==0 && i==0 ) break;
5687 /*
5688 ** Did we reach end-of-file OR end-of-line before finding any
5689 ** columns in ASCII mode? If so, stop instead of NULL filling
5690 ** the remaining columns.
5691 */
5692 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
5693 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
5694 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
5695 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5696 "filling the rest with NULL\n",
5697 sCtx.zFile, startLine, nCol, i+1);
5698 i += 2;
5699 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
5700 }
5701 }
5702 if( sCtx.cTerm==sCtx.cColSep ){
5703 do{
5704 xRead(&sCtx);
5705 i++;
5706 }while( sCtx.cTerm==sCtx.cColSep );
5707 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
5708 "extras ignored\n",
5709 sCtx.zFile, startLine, nCol, i);
5710 }
5711 if( i>=nCol ){
5712 sqlite3_step(pStmt);
5713 rc = sqlite3_reset(pStmt);
5714 if( rc!=SQLITE_OK ){
5715 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5716 startLine, sqlite3_errmsg(p->db));
5717 }
5718 }
5719 }while( sCtx.cTerm!=EOF );
5720
5721 xCloser(sCtx.in);
5722 sqlite3_free(sCtx.z);
5723 sqlite3_finalize(pStmt);
5724 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
5725 }else
5726
5727#ifndef SQLITE_UNTESTABLE
5728 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5729 char *zSql;
5730 char *zCollist = 0;
5731 sqlite3_stmt *pStmt;
5732 int tnum = 0;
5733 int i;
5734 if( nArg!=3 ){
5735 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5736 rc = 1;
5737 goto meta_command_exit;
5738 }
5739 open_db(p, 0);
5740 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5741 " WHERE name='%q' AND type='index'", azArg[1]);
5742 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5743 sqlite3_free(zSql);
5744 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5745 tnum = sqlite3_column_int(pStmt, 0);
5746 }
5747 sqlite3_finalize(pStmt);
5748 if( tnum==0 ){
5749 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5750 rc = 1;
5751 goto meta_command_exit;
5752 }
5753 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5754 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5755 sqlite3_free(zSql);
5756 i = 0;
5757 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5758 char zLabel[20];
5759 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
5760 i++;
5761 if( zCol==0 ){
5762 if( sqlite3_column_int(pStmt,1)==-1 ){
5763 zCol = "_ROWID_";
5764 }else{
5765 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5766 zCol = zLabel;
5767 }
5768 }
5769 if( zCollist==0 ){
5770 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5771 }else{
5772 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5773 }
5774 }
5775 sqlite3_finalize(pStmt);
5776 zSql = sqlite3_mprintf(
5777 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5778 azArg[2], zCollist, zCollist);
5779 sqlite3_free(zCollist);
5780 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5781 if( rc==SQLITE_OK ){
5782 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5783 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5784 if( rc ){
5785 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5786 }else{
5787 utf8_printf(stdout, "%s;\n", zSql);
5788 raw_printf(stdout,
5789 "WARNING: writing to an imposter table will corrupt the index!\n"
5790 );
5791 }
5792 }else{
5793 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
5794 rc = 1;
5795 }
5796 sqlite3_free(zSql);
5797 }else
5798#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5799
5800#ifdef SQLITE_ENABLE_IOTRACE
5801 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
5802 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
5803 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5804 iotrace = 0;
5805 if( nArg<2 ){
5806 sqlite3IoTrace = 0;
5807 }else if( strcmp(azArg[1], "-")==0 ){
5808 sqlite3IoTrace = iotracePrintf;
5809 iotrace = stdout;
5810 }else{
5811 iotrace = fopen(azArg[1], "w");
5812 if( iotrace==0 ){
5813 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
5814 sqlite3IoTrace = 0;
5815 rc = 1;
5816 }else{
5817 sqlite3IoTrace = iotracePrintf;
5818 }
5819 }
5820 }else
5821#endif
5822
5823 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5824 static const struct {
5825 const char *zLimitName; /* Name of a limit */
5826 int limitCode; /* Integer code for that limit */
5827 } aLimit[] = {
5828 { "length", SQLITE_LIMIT_LENGTH },
5829 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5830 { "column", SQLITE_LIMIT_COLUMN },
5831 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5832 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5833 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5834 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5835 { "attached", SQLITE_LIMIT_ATTACHED },
5836 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5837 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5838 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5839 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5840 };
5841 int i, n2;
5842 open_db(p, 0);
5843 if( nArg==1 ){
5844 for(i=0; i<ArraySize(aLimit); i++){
5845 printf("%20s %d\n", aLimit[i].zLimitName,
5846 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5847 }
5848 }else if( nArg>3 ){
5849 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
5850 rc = 1;
5851 goto meta_command_exit;
5852 }else{
5853 int iLimit = -1;
5854 n2 = strlen30(azArg[1]);
5855 for(i=0; i<ArraySize(aLimit); i++){
5856 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5857 if( iLimit<0 ){
5858 iLimit = i;
5859 }else{
5860 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
5861 rc = 1;
5862 goto meta_command_exit;
5863 }
5864 }
5865 }
5866 if( iLimit<0 ){
5867 utf8_printf(stderr, "unknown limit: \"%s\"\n"
5868 "enter \".limits\" with no arguments for a list.\n",
5869 azArg[1]);
5870 rc = 1;
5871 goto meta_command_exit;
5872 }
5873 if( nArg==3 ){
5874 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5875 (int)integerValue(azArg[2]));
5876 }
5877 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5878 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5879 }
5880 }else
5881
5882 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
5883 open_db(p, 0);
5884 lintDotCommand(p, azArg, nArg);
5885 }else
5886
5887#ifndef SQLITE_OMIT_LOAD_EXTENSION
5888 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
5889 const char *zFile, *zProc;
5890 char *zErrMsg = 0;
5891 if( nArg<2 ){
5892 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
5893 rc = 1;
5894 goto meta_command_exit;
5895 }
5896 zFile = azArg[1];
5897 zProc = nArg>=3 ? azArg[2] : 0;
5898 open_db(p, 0);
5899 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5900 if( rc!=SQLITE_OK ){
5901 utf8_printf(stderr, "Error: %s\n", zErrMsg);
5902 sqlite3_free(zErrMsg);
5903 rc = 1;
5904 }
5905 }else
5906#endif
5907
5908 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5909 if( nArg!=2 ){
5910 raw_printf(stderr, "Usage: .log FILENAME\n");
5911 rc = 1;
5912 }else{
5913 const char *zFile = azArg[1];
5914 output_file_close(p->pLog);
5915 p->pLog = output_file_open(zFile);
5916 }
5917 }else
5918
5919 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5920 const char *zMode = nArg>=2 ? azArg[1] : "";
drhaf2770f2018-01-05 14:55:43 +00005921 int n2 = strlen30(zMode);
drh2ce15c32017-07-11 13:34:40 +00005922 int c2 = zMode[0];
5923 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
5924 p->mode = MODE_Line;
5925 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5926 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
5927 p->mode = MODE_Column;
5928 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5929 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
5930 p->mode = MODE_List;
5931 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5932 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5933 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
5934 p->mode = MODE_Html;
5935 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
5936 p->mode = MODE_Tcl;
5937 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
5938 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5939 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
5940 p->mode = MODE_Csv;
5941 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
5942 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
5943 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
5944 p->mode = MODE_List;
5945 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
5946 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
5947 p->mode = MODE_Insert;
5948 set_table_name(p, nArg>=3 ? azArg[2] : "table");
5949 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5950 p->mode = MODE_Quote;
5951 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5952 p->mode = MODE_Ascii;
5953 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5954 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
5955 }else if( nArg==1 ){
5956 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
5957 }else{
5958 raw_printf(stderr, "Error: mode should be one of: "
5959 "ascii column csv html insert line list quote tabs tcl\n");
5960 rc = 1;
5961 }
5962 p->cMode = p->mode;
5963 }else
5964
5965 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5966 if( nArg==2 ){
5967 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5968 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
5969 }else{
5970 raw_printf(stderr, "Usage: .nullvalue STRING\n");
5971 rc = 1;
5972 }
5973 }else
5974
5975 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
5976 char *zNewFilename; /* Name of the database file to open */
5977 int iName = 1; /* Index in azArg[] of the filename */
5978 int newFlag = 0; /* True to delete file before opening */
5979 /* Close the existing database */
5980 session_close_all(p);
5981 sqlite3_close(p->db);
5982 p->db = 0;
5983 p->zDbFilename = 0;
5984 sqlite3_free(p->zFreeOnClose);
5985 p->zFreeOnClose = 0;
5986 /* Check for command-line arguments */
5987 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5988 const char *z = azArg[iName];
5989 if( optionMatch(z,"new") ){
5990 newFlag = 1;
5991 }else if( z[0]=='-' ){
5992 utf8_printf(stderr, "unknown option: %s\n", z);
5993 rc = 1;
5994 goto meta_command_exit;
5995 }
5996 }
5997 /* If a filename is specified, try to open it first */
5998 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5999 if( zNewFilename ){
6000 if( newFlag ) shellDeleteFile(zNewFilename);
6001 p->zDbFilename = zNewFilename;
6002 open_db(p, 1);
6003 if( p->db==0 ){
6004 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6005 sqlite3_free(zNewFilename);
6006 }else{
6007 p->zFreeOnClose = zNewFilename;
6008 }
6009 }
6010 if( p->db==0 ){
6011 /* As a fall-back open a TEMP database */
6012 p->zDbFilename = 0;
6013 open_db(p, 0);
6014 }
6015 }else
6016
6017 if( c=='o'
6018 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
6019 ){
6020 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
6021 if( nArg>2 ){
6022 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
6023 rc = 1;
6024 goto meta_command_exit;
6025 }
6026 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6027 if( nArg<2 ){
6028 raw_printf(stderr, "Usage: .once FILE\n");
6029 rc = 1;
6030 goto meta_command_exit;
6031 }
6032 p->outCount = 2;
6033 }else{
6034 p->outCount = 0;
6035 }
6036 output_reset(p);
6037 if( zFile[0]=='|' ){
6038#ifdef SQLITE_OMIT_POPEN
6039 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
6040 rc = 1;
6041 p->out = stdout;
6042#else
6043 p->out = popen(zFile + 1, "w");
6044 if( p->out==0 ){
6045 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
6046 p->out = stdout;
6047 rc = 1;
6048 }else{
6049 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6050 }
6051#endif
6052 }else{
6053 p->out = output_file_open(zFile);
6054 if( p->out==0 ){
6055 if( strcmp(zFile,"off")!=0 ){
6056 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
6057 }
6058 p->out = stdout;
6059 rc = 1;
6060 } else {
6061 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
6062 }
6063 }
6064 }else
6065
6066 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6067 int i;
6068 for(i=1; i<nArg; i++){
6069 if( i>1 ) raw_printf(p->out, " ");
6070 utf8_printf(p->out, "%s", azArg[i]);
6071 }
6072 raw_printf(p->out, "\n");
6073 }else
6074
6075 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
6076 if( nArg >= 2) {
6077 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6078 }
6079 if( nArg >= 3) {
6080 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6081 }
6082 }else
6083
6084 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
6085 rc = 2;
6086 }else
6087
6088 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6089 FILE *alt;
6090 if( nArg!=2 ){
6091 raw_printf(stderr, "Usage: .read FILE\n");
6092 rc = 1;
6093 goto meta_command_exit;
6094 }
6095 alt = fopen(azArg[1], "rb");
6096 if( alt==0 ){
6097 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6098 rc = 1;
6099 }else{
6100 rc = process_input(p, alt);
6101 fclose(alt);
6102 }
6103 }else
6104
6105 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
6106 const char *zSrcFile;
6107 const char *zDb;
6108 sqlite3 *pSrc;
6109 sqlite3_backup *pBackup;
6110 int nTimeout = 0;
6111
6112 if( nArg==2 ){
6113 zSrcFile = azArg[1];
6114 zDb = "main";
6115 }else if( nArg==3 ){
6116 zSrcFile = azArg[2];
6117 zDb = azArg[1];
6118 }else{
6119 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
6120 rc = 1;
6121 goto meta_command_exit;
6122 }
6123 rc = sqlite3_open(zSrcFile, &pSrc);
6124 if( rc!=SQLITE_OK ){
6125 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
6126 sqlite3_close(pSrc);
6127 return 1;
6128 }
6129 open_db(p, 0);
6130 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6131 if( pBackup==0 ){
6132 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6133 sqlite3_close(pSrc);
6134 return 1;
6135 }
6136 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6137 || rc==SQLITE_BUSY ){
6138 if( rc==SQLITE_BUSY ){
6139 if( nTimeout++ >= 3 ) break;
6140 sqlite3_sleep(100);
6141 }
6142 }
6143 sqlite3_backup_finish(pBackup);
6144 if( rc==SQLITE_DONE ){
6145 rc = 0;
6146 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
6147 raw_printf(stderr, "Error: source database is busy\n");
6148 rc = 1;
6149 }else{
6150 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6151 rc = 1;
6152 }
6153 sqlite3_close(pSrc);
6154 }else
6155
6156
6157 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6158 if( nArg==2 ){
6159 p->scanstatsOn = booleanValue(azArg[1]);
6160#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6161 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
6162#endif
6163 }else{
6164 raw_printf(stderr, "Usage: .scanstats on|off\n");
6165 rc = 1;
6166 }
6167 }else
6168
6169 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
6170 ShellText sSelect;
6171 ShellState data;
6172 char *zErrMsg = 0;
drh667a2a22018-01-02 00:04:37 +00006173 const char *zDiv = "(";
drhceba7922018-01-01 21:28:25 +00006174 const char *zName = 0;
drh2ce15c32017-07-11 13:34:40 +00006175 int iSchema = 0;
drhceba7922018-01-01 21:28:25 +00006176 int bDebug = 0;
6177 int ii;
drh2ce15c32017-07-11 13:34:40 +00006178
6179 open_db(p, 0);
6180 memcpy(&data, p, sizeof(data));
6181 data.showHeader = 0;
6182 data.cMode = data.mode = MODE_Semi;
6183 initText(&sSelect);
drhceba7922018-01-01 21:28:25 +00006184 for(ii=1; ii<nArg; ii++){
6185 if( optionMatch(azArg[ii],"indent") ){
6186 data.cMode = data.mode = MODE_Pretty;
6187 }else if( optionMatch(azArg[ii],"debug") ){
6188 bDebug = 1;
6189 }else if( zName==0 ){
6190 zName = azArg[ii];
drh2ce15c32017-07-11 13:34:40 +00006191 }else{
drhceba7922018-01-01 21:28:25 +00006192 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6193 rc = 1;
6194 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00006195 }
drh2ce15c32017-07-11 13:34:40 +00006196 }
drhceba7922018-01-01 21:28:25 +00006197 if( zName!=0 ){
drh667a2a22018-01-02 00:04:37 +00006198 int isMaster = sqlite3_strlike(zName, "sqlite_master", 0)==0;
6199 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master",0)==0 ){
drh2ce15c32017-07-11 13:34:40 +00006200 char *new_argv[2], *new_colv[2];
drhc22b7162018-01-01 20:11:23 +00006201 new_argv[0] = sqlite3_mprintf(
6202 "CREATE TABLE %s (\n"
drh2ce15c32017-07-11 13:34:40 +00006203 " type text,\n"
6204 " name text,\n"
6205 " tbl_name text,\n"
6206 " rootpage integer,\n"
6207 " sql text\n"
drh667a2a22018-01-02 00:04:37 +00006208 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
drh2ce15c32017-07-11 13:34:40 +00006209 new_argv[1] = 0;
6210 new_colv[0] = "sql";
6211 new_colv[1] = 0;
6212 callback(&data, 1, new_argv, new_colv);
drhc22b7162018-01-01 20:11:23 +00006213 sqlite3_free(new_argv[0]);
drh2ce15c32017-07-11 13:34:40 +00006214 }
drh2ce15c32017-07-11 13:34:40 +00006215 }
6216 if( zDiv ){
6217 sqlite3_stmt *pStmt = 0;
6218 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6219 -1, &pStmt, 0);
6220 if( rc ){
6221 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6222 sqlite3_finalize(pStmt);
6223 rc = 1;
6224 goto meta_command_exit;
6225 }
6226 appendText(&sSelect, "SELECT sql FROM", 0);
6227 iSchema = 0;
6228 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6229 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6230 char zScNum[30];
6231 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6232 appendText(&sSelect, zDiv, 0);
6233 zDiv = " UNION ALL ";
drhceba7922018-01-01 21:28:25 +00006234 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
6235 if( sqlite3_stricmp(zDb, "main")!=0 ){
drh2ce15c32017-07-11 13:34:40 +00006236 appendText(&sSelect, zDb, '"');
drh2ce15c32017-07-11 13:34:40 +00006237 }else{
drhceba7922018-01-01 21:28:25 +00006238 appendText(&sSelect, "NULL", 0);
drh2ce15c32017-07-11 13:34:40 +00006239 }
drhceba7922018-01-01 21:28:25 +00006240 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6241 appendText(&sSelect, zScNum, 0);
6242 appendText(&sSelect, " AS snum, ", 0);
6243 appendText(&sSelect, zDb, '\'');
6244 appendText(&sSelect, " AS sname FROM ", 0);
6245 appendText(&sSelect, zDb, '"');
6246 appendText(&sSelect, ".sqlite_master", 0);
drh2ce15c32017-07-11 13:34:40 +00006247 }
6248 sqlite3_finalize(pStmt);
drhcde7b772018-01-02 12:50:40 +00006249#ifdef SQLITE_INTROSPECTION_PRAGMAS
drh667a2a22018-01-02 00:04:37 +00006250 if( zName ){
6251 appendText(&sSelect,
6252 " UNION ALL SELECT shell_module_schema(name),"
6253 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6254 }
drhcde7b772018-01-02 12:50:40 +00006255#endif
drh2ce15c32017-07-11 13:34:40 +00006256 appendText(&sSelect, ") WHERE ", 0);
drhceba7922018-01-01 21:28:25 +00006257 if( zName ){
6258 char *zQarg = sqlite3_mprintf("%Q", zName);
6259 if( strchr(zName, '.') ){
drh2ce15c32017-07-11 13:34:40 +00006260 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6261 }else{
6262 appendText(&sSelect, "lower(tbl_name)", 0);
6263 }
drhceba7922018-01-01 21:28:25 +00006264 appendText(&sSelect, strchr(zName, '*') ? " GLOB " : " LIKE ", 0);
drh2ce15c32017-07-11 13:34:40 +00006265 appendText(&sSelect, zQarg, 0);
6266 appendText(&sSelect, " AND ", 0);
6267 sqlite3_free(zQarg);
6268 }
6269 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6270 " ORDER BY snum, rowid", 0);
drhceba7922018-01-01 21:28:25 +00006271 if( bDebug ){
6272 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
6273 }else{
6274 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6275 }
drh2ce15c32017-07-11 13:34:40 +00006276 freeText(&sSelect);
6277 }
6278 if( zErrMsg ){
6279 utf8_printf(stderr,"Error: %s\n", zErrMsg);
6280 sqlite3_free(zErrMsg);
6281 rc = 1;
6282 }else if( rc != SQLITE_OK ){
6283 raw_printf(stderr,"Error: querying schema information\n");
6284 rc = 1;
6285 }else{
6286 rc = 0;
6287 }
6288 }else
6289
6290#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6291 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
6292 sqlite3SelectTrace = (int)integerValue(azArg[1]);
6293 }else
6294#endif
6295
6296#if defined(SQLITE_ENABLE_SESSION)
6297 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
6298 OpenSession *pSession = &p->aSession[0];
6299 char **azCmd = &azArg[1];
6300 int iSes = 0;
6301 int nCmd = nArg - 1;
6302 int i;
6303 if( nArg<=1 ) goto session_syntax_error;
6304 open_db(p, 0);
6305 if( nArg>=3 ){
6306 for(iSes=0; iSes<p->nSession; iSes++){
6307 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
6308 }
6309 if( iSes<p->nSession ){
6310 pSession = &p->aSession[iSes];
6311 azCmd++;
6312 nCmd--;
6313 }else{
6314 pSession = &p->aSession[0];
6315 iSes = 0;
6316 }
6317 }
6318
6319 /* .session attach TABLE
6320 ** Invoke the sqlite3session_attach() interface to attach a particular
6321 ** table so that it is never filtered.
6322 */
6323 if( strcmp(azCmd[0],"attach")==0 ){
6324 if( nCmd!=2 ) goto session_syntax_error;
6325 if( pSession->p==0 ){
6326 session_not_open:
6327 raw_printf(stderr, "ERROR: No sessions are open\n");
6328 }else{
6329 rc = sqlite3session_attach(pSession->p, azCmd[1]);
6330 if( rc ){
6331 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
6332 rc = 0;
6333 }
6334 }
6335 }else
6336
6337 /* .session changeset FILE
6338 ** .session patchset FILE
6339 ** Write a changeset or patchset into a file. The file is overwritten.
6340 */
6341 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
6342 FILE *out = 0;
6343 if( nCmd!=2 ) goto session_syntax_error;
6344 if( pSession->p==0 ) goto session_not_open;
6345 out = fopen(azCmd[1], "wb");
6346 if( out==0 ){
6347 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
6348 }else{
6349 int szChng;
6350 void *pChng;
6351 if( azCmd[0][0]=='c' ){
6352 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
6353 }else{
6354 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
6355 }
6356 if( rc ){
6357 printf("Error: error code %d\n", rc);
6358 rc = 0;
6359 }
6360 if( pChng
6361 && fwrite(pChng, szChng, 1, out)!=1 ){
6362 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
6363 szChng);
6364 }
6365 sqlite3_free(pChng);
6366 fclose(out);
6367 }
6368 }else
6369
6370 /* .session close
6371 ** Close the identified session
6372 */
6373 if( strcmp(azCmd[0], "close")==0 ){
6374 if( nCmd!=1 ) goto session_syntax_error;
6375 if( p->nSession ){
6376 session_close(pSession);
6377 p->aSession[iSes] = p->aSession[--p->nSession];
6378 }
6379 }else
6380
6381 /* .session enable ?BOOLEAN?
6382 ** Query or set the enable flag
6383 */
6384 if( strcmp(azCmd[0], "enable")==0 ){
6385 int ii;
6386 if( nCmd>2 ) goto session_syntax_error;
6387 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6388 if( p->nSession ){
6389 ii = sqlite3session_enable(pSession->p, ii);
6390 utf8_printf(p->out, "session %s enable flag = %d\n",
6391 pSession->zName, ii);
6392 }
6393 }else
6394
6395 /* .session filter GLOB ....
6396 ** Set a list of GLOB patterns of table names to be excluded.
6397 */
6398 if( strcmp(azCmd[0], "filter")==0 ){
6399 int ii, nByte;
6400 if( nCmd<2 ) goto session_syntax_error;
6401 if( p->nSession ){
6402 for(ii=0; ii<pSession->nFilter; ii++){
6403 sqlite3_free(pSession->azFilter[ii]);
6404 }
6405 sqlite3_free(pSession->azFilter);
6406 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6407 pSession->azFilter = sqlite3_malloc( nByte );
6408 if( pSession->azFilter==0 ){
6409 raw_printf(stderr, "Error: out or memory\n");
6410 exit(1);
6411 }
6412 for(ii=1; ii<nCmd; ii++){
6413 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
6414 }
6415 pSession->nFilter = ii-1;
6416 }
6417 }else
6418
6419 /* .session indirect ?BOOLEAN?
6420 ** Query or set the indirect flag
6421 */
6422 if( strcmp(azCmd[0], "indirect")==0 ){
6423 int ii;
6424 if( nCmd>2 ) goto session_syntax_error;
6425 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6426 if( p->nSession ){
6427 ii = sqlite3session_indirect(pSession->p, ii);
6428 utf8_printf(p->out, "session %s indirect flag = %d\n",
6429 pSession->zName, ii);
6430 }
6431 }else
6432
6433 /* .session isempty
6434 ** Determine if the session is empty
6435 */
6436 if( strcmp(azCmd[0], "isempty")==0 ){
6437 int ii;
6438 if( nCmd!=1 ) goto session_syntax_error;
6439 if( p->nSession ){
6440 ii = sqlite3session_isempty(pSession->p);
6441 utf8_printf(p->out, "session %s isempty flag = %d\n",
6442 pSession->zName, ii);
6443 }
6444 }else
6445
6446 /* .session list
6447 ** List all currently open sessions
6448 */
6449 if( strcmp(azCmd[0],"list")==0 ){
6450 for(i=0; i<p->nSession; i++){
6451 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
6452 }
6453 }else
6454
6455 /* .session open DB NAME
6456 ** Open a new session called NAME on the attached database DB.
6457 ** DB is normally "main".
6458 */
6459 if( strcmp(azCmd[0],"open")==0 ){
6460 char *zName;
6461 if( nCmd!=3 ) goto session_syntax_error;
6462 zName = azCmd[2];
6463 if( zName[0]==0 ) goto session_syntax_error;
6464 for(i=0; i<p->nSession; i++){
6465 if( strcmp(p->aSession[i].zName,zName)==0 ){
6466 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
6467 goto meta_command_exit;
6468 }
6469 }
6470 if( p->nSession>=ArraySize(p->aSession) ){
6471 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
6472 goto meta_command_exit;
6473 }
6474 pSession = &p->aSession[p->nSession];
6475 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
6476 if( rc ){
6477 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
6478 rc = 0;
6479 goto meta_command_exit;
6480 }
6481 pSession->nFilter = 0;
6482 sqlite3session_table_filter(pSession->p, session_filter, pSession);
6483 p->nSession++;
6484 pSession->zName = sqlite3_mprintf("%s", zName);
6485 }else
6486 /* If no command name matches, show a syntax error */
6487 session_syntax_error:
6488 session_help(p);
6489 }else
6490#endif
6491
6492#ifdef SQLITE_DEBUG
6493 /* Undocumented commands for internal testing. Subject to change
6494 ** without notice. */
6495 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
6496 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
6497 int i, v;
6498 for(i=1; i<nArg; i++){
6499 v = booleanValue(azArg[i]);
6500 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
6501 }
6502 }
6503 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
6504 int i; sqlite3_int64 v;
6505 for(i=1; i<nArg; i++){
6506 char zBuf[200];
6507 v = integerValue(azArg[i]);
6508 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
6509 utf8_printf(p->out, "%s", zBuf);
6510 }
6511 }
6512 }else
6513#endif
6514
6515 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6516 int bIsInit = 0; /* True to initialize the SELFTEST table */
6517 int bVerbose = 0; /* Verbose output */
6518 int bSelftestExists; /* True if SELFTEST already exists */
6519 int i, k; /* Loop counters */
6520 int nTest = 0; /* Number of tests runs */
6521 int nErr = 0; /* Number of errors seen */
6522 ShellText str; /* Answer for a query */
6523 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
6524
6525 open_db(p,0);
6526 for(i=1; i<nArg; i++){
6527 const char *z = azArg[i];
6528 if( z[0]=='-' && z[1]=='-' ) z++;
6529 if( strcmp(z,"-init")==0 ){
6530 bIsInit = 1;
6531 }else
6532 if( strcmp(z,"-v")==0 ){
6533 bVerbose++;
6534 }else
6535 {
6536 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6537 azArg[i], azArg[0]);
6538 raw_printf(stderr, "Should be one of: --init -v\n");
6539 rc = 1;
6540 goto meta_command_exit;
6541 }
6542 }
6543 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6544 != SQLITE_OK ){
6545 bSelftestExists = 0;
6546 }else{
6547 bSelftestExists = 1;
6548 }
6549 if( bIsInit ){
6550 createSelftestTable(p);
6551 bSelftestExists = 1;
6552 }
6553 initText(&str);
6554 appendText(&str, "x", 0);
6555 for(k=bSelftestExists; k>=0; k--){
6556 if( k==1 ){
6557 rc = sqlite3_prepare_v2(p->db,
6558 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6559 -1, &pStmt, 0);
6560 }else{
6561 rc = sqlite3_prepare_v2(p->db,
6562 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6563 " (1,'run','PRAGMA integrity_check','ok')",
6564 -1, &pStmt, 0);
6565 }
6566 if( rc ){
6567 raw_printf(stderr, "Error querying the selftest table\n");
6568 rc = 1;
6569 sqlite3_finalize(pStmt);
6570 goto meta_command_exit;
6571 }
6572 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6573 int tno = sqlite3_column_int(pStmt, 0);
6574 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6575 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6576 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
6577
6578 k = 0;
6579 if( bVerbose>0 ){
6580 char *zQuote = sqlite3_mprintf("%q", zSql);
6581 printf("%d: %s %s\n", tno, zOp, zSql);
6582 sqlite3_free(zQuote);
6583 }
6584 if( strcmp(zOp,"memo")==0 ){
6585 utf8_printf(p->out, "%s\n", zSql);
6586 }else
6587 if( strcmp(zOp,"run")==0 ){
6588 char *zErrMsg = 0;
6589 str.n = 0;
6590 str.z[0] = 0;
6591 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6592 nTest++;
6593 if( bVerbose ){
6594 utf8_printf(p->out, "Result: %s\n", str.z);
6595 }
6596 if( rc || zErrMsg ){
6597 nErr++;
6598 rc = 1;
6599 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6600 sqlite3_free(zErrMsg);
6601 }else if( strcmp(zAns,str.z)!=0 ){
6602 nErr++;
6603 rc = 1;
6604 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6605 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6606 }
6607 }else
6608 {
6609 utf8_printf(stderr,
6610 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
6611 rc = 1;
6612 break;
6613 }
6614 } /* End loop over rows of content from SELFTEST */
6615 sqlite3_finalize(pStmt);
6616 } /* End loop over k */
6617 freeText(&str);
6618 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6619 }else
6620
6621 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
6622 if( nArg<2 || nArg>3 ){
6623 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
6624 rc = 1;
6625 }
6626 if( nArg>=2 ){
6627 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
6628 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
6629 }
6630 if( nArg>=3 ){
6631 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6632 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
6633 }
6634 }else
6635
6636 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6637 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6638 int i; /* Loop counter */
6639 int bSchema = 0; /* Also hash the schema */
6640 int bSeparate = 0; /* Hash each table separately */
6641 int iSize = 224; /* Hash algorithm to use */
6642 int bDebug = 0; /* Only show the query that would have run */
6643 sqlite3_stmt *pStmt; /* For querying tables names */
6644 char *zSql; /* SQL to be run */
6645 char *zSep; /* Separator */
6646 ShellText sSql; /* Complete SQL for the query to run the hash */
6647 ShellText sQuery; /* Set of queries used to read all content */
6648 open_db(p, 0);
6649 for(i=1; i<nArg; i++){
6650 const char *z = azArg[i];
6651 if( z[0]=='-' ){
6652 z++;
6653 if( z[0]=='-' ) z++;
6654 if( strcmp(z,"schema")==0 ){
6655 bSchema = 1;
6656 }else
6657 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6658 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
6659 ){
6660 iSize = atoi(&z[5]);
6661 }else
6662 if( strcmp(z,"debug")==0 ){
6663 bDebug = 1;
6664 }else
6665 {
6666 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6667 azArg[i], azArg[0]);
6668 raw_printf(stderr, "Should be one of: --schema"
6669 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6670 rc = 1;
6671 goto meta_command_exit;
6672 }
6673 }else if( zLike ){
6674 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6675 rc = 1;
6676 goto meta_command_exit;
6677 }else{
6678 zLike = z;
6679 bSeparate = 1;
6680 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
6681 }
6682 }
6683 if( bSchema ){
6684 zSql = "SELECT lower(name) FROM sqlite_master"
6685 " WHERE type='table' AND coalesce(rootpage,0)>1"
6686 " UNION ALL SELECT 'sqlite_master'"
6687 " ORDER BY 1 collate nocase";
6688 }else{
6689 zSql = "SELECT lower(name) FROM sqlite_master"
6690 " WHERE type='table' AND coalesce(rootpage,0)>1"
6691 " AND name NOT LIKE 'sqlite_%'"
6692 " ORDER BY 1 collate nocase";
6693 }
6694 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6695 initText(&sQuery);
6696 initText(&sSql);
6697 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6698 zSep = "VALUES(";
6699 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6700 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6701 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6702 if( strncmp(zTab, "sqlite_",7)!=0 ){
6703 appendText(&sQuery,"SELECT * FROM ", 0);
6704 appendText(&sQuery,zTab,'"');
6705 appendText(&sQuery," NOT INDEXED;", 0);
6706 }else if( strcmp(zTab, "sqlite_master")==0 ){
6707 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6708 " ORDER BY name;", 0);
6709 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6710 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6711 " ORDER BY name;", 0);
6712 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6713 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6714 " ORDER BY tbl,idx;", 0);
6715 }else if( strcmp(zTab, "sqlite_stat3")==0
6716 || strcmp(zTab, "sqlite_stat4")==0 ){
6717 appendText(&sQuery, "SELECT * FROM ", 0);
6718 appendText(&sQuery, zTab, 0);
6719 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6720 }
6721 appendText(&sSql, zSep, 0);
6722 appendText(&sSql, sQuery.z, '\'');
6723 sQuery.n = 0;
6724 appendText(&sSql, ",", 0);
6725 appendText(&sSql, zTab, '\'');
6726 zSep = "),(";
6727 }
6728 sqlite3_finalize(pStmt);
6729 if( bSeparate ){
6730 zSql = sqlite3_mprintf(
6731 "%s))"
6732 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6733 " FROM [sha3sum$query]",
6734 sSql.z, iSize);
6735 }else{
6736 zSql = sqlite3_mprintf(
6737 "%s))"
6738 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6739 " FROM [sha3sum$query]",
6740 sSql.z, iSize);
6741 }
6742 freeText(&sQuery);
6743 freeText(&sSql);
6744 if( bDebug ){
6745 utf8_printf(p->out, "%s\n", zSql);
6746 }else{
6747 shell_exec(p->db, zSql, shell_callback, p, 0);
6748 }
6749 sqlite3_free(zSql);
6750 }else
6751
6752 if( c=='s'
6753 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
6754 ){
6755 char *zCmd;
6756 int i, x;
6757 if( nArg<2 ){
6758 raw_printf(stderr, "Usage: .system COMMAND\n");
6759 rc = 1;
6760 goto meta_command_exit;
6761 }
6762 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
6763 for(i=2; i<nArg; i++){
6764 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6765 zCmd, azArg[i]);
6766 }
6767 x = system(zCmd);
6768 sqlite3_free(zCmd);
6769 if( x ) raw_printf(stderr, "System command returns %d\n", x);
6770 }else
6771
6772 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drhada70452017-12-21 21:02:27 +00006773 static const char *azBool[] = { "off", "on", "trigger", "full"};
drh2ce15c32017-07-11 13:34:40 +00006774 int i;
6775 if( nArg!=1 ){
6776 raw_printf(stderr, "Usage: .show\n");
6777 rc = 1;
6778 goto meta_command_exit;
6779 }
6780 utf8_printf(p->out, "%12.12s: %s\n","echo",
6781 azBool[ShellHasFlag(p, SHFLG_Echo)]);
6782 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
6783 utf8_printf(p->out, "%12.12s: %s\n","explain",
6784 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
6785 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
6786 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6787 utf8_printf(p->out, "%12.12s: ", "nullvalue");
6788 output_c_string(p->out, p->nullValue);
6789 raw_printf(p->out, "\n");
6790 utf8_printf(p->out,"%12.12s: %s\n","output",
6791 strlen30(p->outfile) ? p->outfile : "stdout");
6792 utf8_printf(p->out,"%12.12s: ", "colseparator");
6793 output_c_string(p->out, p->colSeparator);
6794 raw_printf(p->out, "\n");
6795 utf8_printf(p->out,"%12.12s: ", "rowseparator");
6796 output_c_string(p->out, p->rowSeparator);
6797 raw_printf(p->out, "\n");
6798 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
6799 utf8_printf(p->out, "%12.12s: ", "width");
6800 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
6801 raw_printf(p->out, "%d ", p->colWidth[i]);
6802 }
6803 raw_printf(p->out, "\n");
6804 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6805 p->zDbFilename ? p->zDbFilename : "");
6806 }else
6807
6808 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6809 if( nArg==2 ){
6810 p->statsOn = booleanValue(azArg[1]);
6811 }else if( nArg==1 ){
6812 display_stats(p->db, p, 0);
6813 }else{
6814 raw_printf(stderr, "Usage: .stats ?on|off?\n");
6815 rc = 1;
6816 }
6817 }else
6818
6819 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6820 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6821 || strncmp(azArg[0], "indexes", n)==0) )
6822 ){
6823 sqlite3_stmt *pStmt;
6824 char **azResult;
6825 int nRow, nAlloc;
6826 int ii;
6827 ShellText s;
6828 initText(&s);
6829 open_db(p, 0);
6830 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
6831 if( rc ) return shellDatabaseError(p->db);
6832
6833 if( nArg>2 && c=='i' ){
6834 /* It is an historical accident that the .indexes command shows an error
6835 ** when called with the wrong number of arguments whereas the .tables
6836 ** command does not. */
6837 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6838 rc = 1;
6839 goto meta_command_exit;
6840 }
6841 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
6842 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
6843 if( zDbName==0 ) continue;
6844 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
6845 if( sqlite3_stricmp(zDbName, "main")==0 ){
6846 appendText(&s, "SELECT name FROM ", 0);
6847 }else{
6848 appendText(&s, "SELECT ", 0);
6849 appendText(&s, zDbName, '\'');
6850 appendText(&s, "||'.'||name FROM ", 0);
6851 }
6852 appendText(&s, zDbName, '"');
6853 appendText(&s, ".sqlite_master ", 0);
6854 if( c=='t' ){
6855 appendText(&s," WHERE type IN ('table','view')"
6856 " AND name NOT LIKE 'sqlite_%'"
6857 " AND name LIKE ?1", 0);
6858 }else{
6859 appendText(&s," WHERE type='index'"
6860 " AND tbl_name LIKE ?1", 0);
6861 }
6862 }
6863 rc = sqlite3_finalize(pStmt);
6864 appendText(&s, " ORDER BY 1", 0);
6865 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
6866 freeText(&s);
6867 if( rc ) return shellDatabaseError(p->db);
6868
6869 /* Run the SQL statement prepared by the above block. Store the results
6870 ** as an array of nul-terminated strings in azResult[]. */
6871 nRow = nAlloc = 0;
6872 azResult = 0;
6873 if( nArg>1 ){
6874 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
6875 }else{
6876 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6877 }
6878 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6879 if( nRow>=nAlloc ){
6880 char **azNew;
6881 int n2 = nAlloc*2 + 10;
6882 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
6883 if( azNew==0 ){
6884 rc = shellNomemError();
6885 break;
6886 }
6887 nAlloc = n2;
6888 azResult = azNew;
6889 }
6890 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
6891 if( 0==azResult[nRow] ){
6892 rc = shellNomemError();
6893 break;
6894 }
6895 nRow++;
6896 }
6897 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6898 rc = shellDatabaseError(p->db);
6899 }
6900
6901 /* Pretty-print the contents of array azResult[] to the output */
6902 if( rc==0 && nRow>0 ){
6903 int len, maxlen = 0;
6904 int i, j;
6905 int nPrintCol, nPrintRow;
6906 for(i=0; i<nRow; i++){
6907 len = strlen30(azResult[i]);
6908 if( len>maxlen ) maxlen = len;
6909 }
6910 nPrintCol = 80/(maxlen+2);
6911 if( nPrintCol<1 ) nPrintCol = 1;
6912 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6913 for(i=0; i<nPrintRow; i++){
6914 for(j=i; j<nRow; j+=nPrintRow){
6915 char *zSp = j<nPrintRow ? "" : " ";
6916 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6917 azResult[j] ? azResult[j]:"");
6918 }
6919 raw_printf(p->out, "\n");
6920 }
6921 }
6922
6923 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6924 sqlite3_free(azResult);
6925 }else
6926
6927 /* Begin redirecting output to the file "testcase-out.txt" */
6928 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6929 output_reset(p);
6930 p->out = output_file_open("testcase-out.txt");
6931 if( p->out==0 ){
6932 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
6933 }
6934 if( nArg>=2 ){
6935 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6936 }else{
6937 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6938 }
6939 }else
6940
6941#ifndef SQLITE_UNTESTABLE
drh35f51a42017-11-15 17:07:22 +00006942 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
drh2ce15c32017-07-11 13:34:40 +00006943 static const struct {
6944 const char *zCtrlName; /* Name of a test-control option */
6945 int ctrlCode; /* Integer code for that option */
drhef302e82017-11-15 19:14:08 +00006946 const char *zUsage; /* Usage notes */
drh2ce15c32017-07-11 13:34:40 +00006947 } aCtrl[] = {
drhef302e82017-11-15 19:14:08 +00006948 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
6949 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
6950 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
6951 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
6952 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
6953 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
6954 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
6955#ifdef SQLITE_N_KEYWORD
6956 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD, "IDENTIFIER" },
6957#endif
6958 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
6959 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
6960 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
drh0d9de992017-12-26 18:04:23 +00006961#ifdef YYCOVERAGE
6962 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
6963#endif
drhef302e82017-11-15 19:14:08 +00006964 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
6965 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
6966 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
6967 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
6968 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
drh2ce15c32017-07-11 13:34:40 +00006969 };
6970 int testctrl = -1;
drhef302e82017-11-15 19:14:08 +00006971 int iCtrl = -1;
6972 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
6973 int isOk = 0;
drh2ce15c32017-07-11 13:34:40 +00006974 int i, n2;
mistachkinc6bc15a2017-11-21 21:14:32 +00006975 const char *zCmd = 0;
6976
drh2ce15c32017-07-11 13:34:40 +00006977 open_db(p, 0);
mistachkinc6bc15a2017-11-21 21:14:32 +00006978 zCmd = nArg>=2 ? azArg[1] : "help";
drh35f51a42017-11-15 17:07:22 +00006979
6980 /* The argument can optionally begin with "-" or "--" */
6981 if( zCmd[0]=='-' && zCmd[1] ){
6982 zCmd++;
6983 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
6984 }
6985
6986 /* --help lists all test-controls */
6987 if( strcmp(zCmd,"help")==0 ){
6988 utf8_printf(p->out, "Available test-controls:\n");
6989 for(i=0; i<ArraySize(aCtrl); i++){
drhef302e82017-11-15 19:14:08 +00006990 utf8_printf(p->out, " .testctrl %s %s\n",
6991 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
drh35f51a42017-11-15 17:07:22 +00006992 }
6993 rc = 1;
6994 goto meta_command_exit;
6995 }
drh2ce15c32017-07-11 13:34:40 +00006996
6997 /* convert testctrl text option to value. allow any unique prefix
6998 ** of the option name, or a numerical value. */
drh35f51a42017-11-15 17:07:22 +00006999 n2 = strlen30(zCmd);
drh2ce15c32017-07-11 13:34:40 +00007000 for(i=0; i<ArraySize(aCtrl); i++){
drh35f51a42017-11-15 17:07:22 +00007001 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
drh2ce15c32017-07-11 13:34:40 +00007002 if( testctrl<0 ){
7003 testctrl = aCtrl[i].ctrlCode;
drhef302e82017-11-15 19:14:08 +00007004 iCtrl = i;
drh2ce15c32017-07-11 13:34:40 +00007005 }else{
drh35f51a42017-11-15 17:07:22 +00007006 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
7007 "Use \".testctrl --help\" for help\n", zCmd);
7008 rc = 1;
7009 goto meta_command_exit;
drh2ce15c32017-07-11 13:34:40 +00007010 }
7011 }
7012 }
drhef302e82017-11-15 19:14:08 +00007013 if( testctrl<0 ){
drh35f51a42017-11-15 17:07:22 +00007014 utf8_printf(stderr,"Error: unknown test-control: %s\n"
7015 "Use \".testctrl --help\" for help\n", zCmd);
drh2ce15c32017-07-11 13:34:40 +00007016 }else{
7017 switch(testctrl){
7018
7019 /* sqlite3_test_control(int, db, int) */
7020 case SQLITE_TESTCTRL_OPTIMIZATIONS:
7021 case SQLITE_TESTCTRL_RESERVE:
7022 if( nArg==3 ){
7023 int opt = (int)strtol(azArg[2], 0, 0);
7024 rc2 = sqlite3_test_control(testctrl, p->db, opt);
drhef302e82017-11-15 19:14:08 +00007025 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007026 }
7027 break;
7028
7029 /* sqlite3_test_control(int) */
7030 case SQLITE_TESTCTRL_PRNG_SAVE:
7031 case SQLITE_TESTCTRL_PRNG_RESTORE:
7032 case SQLITE_TESTCTRL_PRNG_RESET:
7033 case SQLITE_TESTCTRL_BYTEORDER:
7034 if( nArg==2 ){
7035 rc2 = sqlite3_test_control(testctrl);
drhef302e82017-11-15 19:14:08 +00007036 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
drh2ce15c32017-07-11 13:34:40 +00007037 }
7038 break;
7039
7040 /* sqlite3_test_control(int, uint) */
7041 case SQLITE_TESTCTRL_PENDING_BYTE:
7042 if( nArg==3 ){
7043 unsigned int opt = (unsigned int)integerValue(azArg[2]);
7044 rc2 = sqlite3_test_control(testctrl, 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, int) */
7050 case SQLITE_TESTCTRL_ASSERT:
7051 case SQLITE_TESTCTRL_ALWAYS:
drhef302e82017-11-15 19:14:08 +00007052 if( nArg==3 ){
7053 int opt = booleanValue(azArg[2]);
7054 rc2 = sqlite3_test_control(testctrl, opt);
7055 isOk = 1;
7056 }
7057 break;
7058
7059 /* sqlite3_test_control(int, int) */
7060 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
drh2ce15c32017-07-11 13:34:40 +00007061 case SQLITE_TESTCTRL_NEVER_CORRUPT:
7062 if( nArg==3 ){
7063 int opt = booleanValue(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, char *) */
7070#ifdef SQLITE_N_KEYWORD
7071 case SQLITE_TESTCTRL_ISKEYWORD:
7072 if( nArg==3 ){
7073 const char *opt = azArg[2];
7074 rc2 = sqlite3_test_control(testctrl, opt);
drhef302e82017-11-15 19:14:08 +00007075 isOk = 1;
drh2ce15c32017-07-11 13:34:40 +00007076 }
7077 break;
7078#endif
7079
7080 case SQLITE_TESTCTRL_IMPOSTER:
7081 if( nArg==5 ){
7082 rc2 = sqlite3_test_control(testctrl, p->db,
7083 azArg[2],
7084 integerValue(azArg[3]),
7085 integerValue(azArg[4]));
drhef302e82017-11-15 19:14:08 +00007086 isOk = 3;
drh2ce15c32017-07-11 13:34:40 +00007087 }
7088 break;
drh0d9de992017-12-26 18:04:23 +00007089
7090#ifdef YYCOVERAGE
7091 case SQLITE_TESTCTRL_PARSER_COVERAGE:
7092 if( nArg==2 ){
7093 sqlite3_test_control(testctrl, p->out);
7094 isOk = 3;
7095 }
7096#endif
drh2ce15c32017-07-11 13:34:40 +00007097 }
7098 }
drhef302e82017-11-15 19:14:08 +00007099 if( isOk==0 && iCtrl>=0 ){
7100 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
7101 rc = 1;
7102 }else if( isOk==1 ){
7103 raw_printf(p->out, "%d\n", rc2);
7104 }else if( isOk==2 ){
7105 raw_printf(p->out, "0x%08x\n", rc2);
7106 }
drh2ce15c32017-07-11 13:34:40 +00007107 }else
7108#endif /* !defined(SQLITE_UNTESTABLE) */
7109
7110 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
7111 open_db(p, 0);
7112 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
7113 }else
7114
7115 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7116 if( nArg==2 ){
7117 enableTimer = booleanValue(azArg[1]);
7118 if( enableTimer && !HAS_TIMER ){
7119 raw_printf(stderr, "Error: timer not available on this system.\n");
7120 enableTimer = 0;
7121 }
7122 }else{
7123 raw_printf(stderr, "Usage: .timer on|off\n");
7124 rc = 1;
7125 }
7126 }else
7127
7128 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
7129 open_db(p, 0);
7130 if( nArg!=2 ){
7131 raw_printf(stderr, "Usage: .trace FILE|off\n");
7132 rc = 1;
7133 goto meta_command_exit;
7134 }
7135 output_file_close(p->traceOut);
7136 p->traceOut = output_file_open(azArg[1]);
7137#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7138 if( p->traceOut==0 ){
7139 sqlite3_trace_v2(p->db, 0, 0, 0);
7140 }else{
7141 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
7142 }
7143#endif
7144 }else
7145
7146#if SQLITE_USER_AUTHENTICATION
7147 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7148 if( nArg<2 ){
7149 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
7150 rc = 1;
7151 goto meta_command_exit;
7152 }
7153 open_db(p, 0);
7154 if( strcmp(azArg[1],"login")==0 ){
7155 if( nArg!=4 ){
7156 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
7157 rc = 1;
7158 goto meta_command_exit;
7159 }
drhaf2770f2018-01-05 14:55:43 +00007160 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
drh2ce15c32017-07-11 13:34:40 +00007161 if( rc ){
7162 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
7163 rc = 1;
7164 }
7165 }else if( strcmp(azArg[1],"add")==0 ){
7166 if( nArg!=5 ){
7167 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
7168 rc = 1;
7169 goto meta_command_exit;
7170 }
drhaf2770f2018-01-05 14:55:43 +00007171 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007172 booleanValue(azArg[4]));
7173 if( rc ){
7174 raw_printf(stderr, "User-Add failed: %d\n", rc);
7175 rc = 1;
7176 }
7177 }else if( strcmp(azArg[1],"edit")==0 ){
7178 if( nArg!=5 ){
7179 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
7180 rc = 1;
7181 goto meta_command_exit;
7182 }
drhaf2770f2018-01-05 14:55:43 +00007183 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
drh2ce15c32017-07-11 13:34:40 +00007184 booleanValue(azArg[4]));
7185 if( rc ){
7186 raw_printf(stderr, "User-Edit failed: %d\n", rc);
7187 rc = 1;
7188 }
7189 }else if( strcmp(azArg[1],"delete")==0 ){
7190 if( nArg!=3 ){
7191 raw_printf(stderr, "Usage: .user delete USER\n");
7192 rc = 1;
7193 goto meta_command_exit;
7194 }
7195 rc = sqlite3_user_delete(p->db, azArg[2]);
7196 if( rc ){
7197 raw_printf(stderr, "User-Delete failed: %d\n", rc);
7198 rc = 1;
7199 }
7200 }else{
7201 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
7202 rc = 1;
7203 goto meta_command_exit;
7204 }
7205 }else
7206#endif /* SQLITE_USER_AUTHENTICATION */
7207
7208 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
7209 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
7210 sqlite3_libversion(), sqlite3_sourceid());
7211 }else
7212
7213 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7214 const char *zDbName = nArg==2 ? azArg[1] : "main";
7215 sqlite3_vfs *pVfs = 0;
7216 if( p->db ){
7217 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7218 if( pVfs ){
7219 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7220 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7221 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7222 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7223 }
7224 }
7225 }else
7226
7227 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7228 sqlite3_vfs *pVfs;
7229 sqlite3_vfs *pCurrent = 0;
7230 if( p->db ){
7231 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7232 }
7233 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7234 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7235 pVfs==pCurrent ? " <--- CURRENT" : "");
7236 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7237 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7238 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7239 if( pVfs->pNext ){
7240 raw_printf(p->out, "-----------------------------------\n");
7241 }
7242 }
7243 }else
7244
7245 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7246 const char *zDbName = nArg==2 ? azArg[1] : "main";
7247 char *zVfsName = 0;
7248 if( p->db ){
7249 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7250 if( zVfsName ){
7251 utf8_printf(p->out, "%s\n", zVfsName);
7252 sqlite3_free(zVfsName);
7253 }
7254 }
7255 }else
7256
7257#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7258 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
7259 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
7260 }else
7261#endif
7262
7263 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
7264 int j;
7265 assert( nArg<=ArraySize(azArg) );
7266 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
7267 p->colWidth[j-1] = (int)integerValue(azArg[j]);
7268 }
7269 }else
7270
7271 {
7272 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
7273 " \"%s\". Enter \".help\" for help\n", azArg[0]);
7274 rc = 1;
7275 }
7276
7277meta_command_exit:
7278 if( p->outCount ){
7279 p->outCount--;
7280 if( p->outCount==0 ) output_reset(p);
7281 }
7282 return rc;
7283}
7284
7285/*
7286** Return TRUE if a semicolon occurs anywhere in the first N characters
7287** of string z[].
7288*/
7289static int line_contains_semicolon(const char *z, int N){
7290 int i;
7291 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
7292 return 0;
7293}
7294
7295/*
7296** Test to see if a line consists entirely of whitespace.
7297*/
7298static int _all_whitespace(const char *z){
7299 for(; *z; z++){
7300 if( IsSpace(z[0]) ) continue;
7301 if( *z=='/' && z[1]=='*' ){
7302 z += 2;
7303 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
7304 if( *z==0 ) return 0;
7305 z++;
7306 continue;
7307 }
7308 if( *z=='-' && z[1]=='-' ){
7309 z += 2;
7310 while( *z && *z!='\n' ){ z++; }
7311 if( *z==0 ) return 1;
7312 continue;
7313 }
7314 return 0;
7315 }
7316 return 1;
7317}
7318
7319/*
7320** Return TRUE if the line typed in is an SQL command terminator other
7321** than a semi-colon. The SQL Server style "go" command is understood
7322** as is the Oracle "/".
7323*/
7324static int line_is_command_terminator(const char *zLine){
7325 while( IsSpace(zLine[0]) ){ zLine++; };
7326 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
7327 return 1; /* Oracle */
7328 }
7329 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
7330 && _all_whitespace(&zLine[2]) ){
7331 return 1; /* SQL Server */
7332 }
7333 return 0;
7334}
7335
7336/*
7337** Return true if zSql is a complete SQL statement. Return false if it
7338** ends in the middle of a string literal or C-style comment.
7339*/
7340static int line_is_complete(char *zSql, int nSql){
7341 int rc;
7342 if( zSql==0 ) return 1;
7343 zSql[nSql] = ';';
7344 zSql[nSql+1] = 0;
7345 rc = sqlite3_complete(zSql);
7346 zSql[nSql] = 0;
7347 return rc;
7348}
7349
7350/*
7351** Run a single line of SQL
7352*/
7353static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
7354 int rc;
7355 char *zErrMsg = 0;
7356
7357 open_db(p, 0);
7358 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
7359 BEGIN_TIMER;
7360 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
7361 END_TIMER;
7362 if( rc || zErrMsg ){
7363 char zPrefix[100];
7364 if( in!=0 || !stdin_is_interactive ){
7365 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
7366 "Error: near line %d:", startline);
7367 }else{
7368 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
7369 }
7370 if( zErrMsg!=0 ){
7371 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
7372 sqlite3_free(zErrMsg);
7373 zErrMsg = 0;
7374 }else{
7375 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
7376 }
7377 return 1;
7378 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
7379 raw_printf(p->out, "changes: %3d total_changes: %d\n",
7380 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
7381 }
7382 return 0;
7383}
7384
7385
7386/*
7387** Read input from *in and process it. If *in==0 then input
7388** is interactive - the user is typing it it. Otherwise, input
7389** is coming from a file or device. A prompt is issued and history
7390** is saved only if input is interactive. An interrupt signal will
7391** cause this routine to exit immediately, unless input is interactive.
7392**
7393** Return the number of errors.
7394*/
7395static int process_input(ShellState *p, FILE *in){
7396 char *zLine = 0; /* A single input line */
7397 char *zSql = 0; /* Accumulated SQL text */
7398 int nLine; /* Length of current line */
7399 int nSql = 0; /* Bytes of zSql[] used */
7400 int nAlloc = 0; /* Allocated zSql[] space */
7401 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
7402 int rc; /* Error code */
7403 int errCnt = 0; /* Number of errors seen */
7404 int lineno = 0; /* Current line number */
7405 int startline = 0; /* Line number for start of current input */
7406
7407 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
7408 fflush(p->out);
7409 zLine = one_input_line(in, zLine, nSql>0);
7410 if( zLine==0 ){
7411 /* End of input */
7412 if( in==0 && stdin_is_interactive ) printf("\n");
7413 break;
7414 }
7415 if( seenInterrupt ){
7416 if( in!=0 ) break;
7417 seenInterrupt = 0;
7418 }
7419 lineno++;
7420 if( nSql==0 && _all_whitespace(zLine) ){
7421 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7422 continue;
7423 }
7424 if( zLine && zLine[0]=='.' && nSql==0 ){
7425 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
7426 rc = do_meta_command(zLine, p);
7427 if( rc==2 ){ /* exit requested */
7428 break;
7429 }else if( rc ){
7430 errCnt++;
7431 }
7432 continue;
7433 }
7434 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
7435 memcpy(zLine,";",2);
7436 }
7437 nLine = strlen30(zLine);
7438 if( nSql+nLine+2>=nAlloc ){
7439 nAlloc = nSql+nLine+100;
7440 zSql = realloc(zSql, nAlloc);
7441 if( zSql==0 ){
7442 raw_printf(stderr, "Error: out of memory\n");
7443 exit(1);
7444 }
7445 }
7446 nSqlPrior = nSql;
7447 if( nSql==0 ){
7448 int i;
7449 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
7450 assert( nAlloc>0 && zSql!=0 );
7451 memcpy(zSql, zLine+i, nLine+1-i);
7452 startline = lineno;
7453 nSql = nLine-i;
7454 }else{
7455 zSql[nSql++] = '\n';
7456 memcpy(zSql+nSql, zLine, nLine+1);
7457 nSql += nLine;
7458 }
7459 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
7460 && sqlite3_complete(zSql) ){
7461 errCnt += runOneSqlLine(p, zSql, in, startline);
7462 nSql = 0;
7463 if( p->outCount ){
7464 output_reset(p);
7465 p->outCount = 0;
7466 }
7467 }else if( nSql && _all_whitespace(zSql) ){
7468 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
7469 nSql = 0;
7470 }
7471 }
7472 if( nSql && !_all_whitespace(zSql) ){
7473 runOneSqlLine(p, zSql, in, startline);
7474 }
7475 free(zSql);
7476 free(zLine);
7477 return errCnt>0;
7478}
7479
7480/*
7481** Return a pathname which is the user's home directory. A
7482** 0 return indicates an error of some kind.
7483*/
7484static char *find_home_dir(int clearFlag){
7485 static char *home_dir = NULL;
7486 if( clearFlag ){
7487 free(home_dir);
7488 home_dir = 0;
7489 return 0;
7490 }
7491 if( home_dir ) return home_dir;
7492
7493#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7494 && !defined(__RTP__) && !defined(_WRS_KERNEL)
7495 {
7496 struct passwd *pwent;
7497 uid_t uid = getuid();
7498 if( (pwent=getpwuid(uid)) != NULL) {
7499 home_dir = pwent->pw_dir;
7500 }
7501 }
7502#endif
7503
7504#if defined(_WIN32_WCE)
7505 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7506 */
7507 home_dir = "/";
7508#else
7509
7510#if defined(_WIN32) || defined(WIN32)
7511 if (!home_dir) {
7512 home_dir = getenv("USERPROFILE");
7513 }
7514#endif
7515
7516 if (!home_dir) {
7517 home_dir = getenv("HOME");
7518 }
7519
7520#if defined(_WIN32) || defined(WIN32)
7521 if (!home_dir) {
7522 char *zDrive, *zPath;
7523 int n;
7524 zDrive = getenv("HOMEDRIVE");
7525 zPath = getenv("HOMEPATH");
7526 if( zDrive && zPath ){
7527 n = strlen30(zDrive) + strlen30(zPath) + 1;
7528 home_dir = malloc( n );
7529 if( home_dir==0 ) return 0;
7530 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7531 return home_dir;
7532 }
7533 home_dir = "c:\\";
7534 }
7535#endif
7536
7537#endif /* !_WIN32_WCE */
7538
7539 if( home_dir ){
7540 int n = strlen30(home_dir) + 1;
7541 char *z = malloc( n );
7542 if( z ) memcpy(z, home_dir, n);
7543 home_dir = z;
7544 }
7545
7546 return home_dir;
7547}
7548
7549/*
7550** Read input from the file given by sqliterc_override. Or if that
7551** parameter is NULL, take input from ~/.sqliterc
7552**
7553** Returns the number of errors.
7554*/
7555static void process_sqliterc(
7556 ShellState *p, /* Configuration data */
7557 const char *sqliterc_override /* Name of config file. NULL to use default */
7558){
7559 char *home_dir = NULL;
7560 const char *sqliterc = sqliterc_override;
7561 char *zBuf = 0;
7562 FILE *in = NULL;
7563
7564 if (sqliterc == NULL) {
7565 home_dir = find_home_dir(0);
7566 if( home_dir==0 ){
7567 raw_printf(stderr, "-- warning: cannot find home directory;"
7568 " cannot read ~/.sqliterc\n");
7569 return;
7570 }
7571 sqlite3_initialize();
7572 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7573 sqliterc = zBuf;
7574 }
7575 in = fopen(sqliterc,"rb");
7576 if( in ){
7577 if( stdin_is_interactive ){
7578 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
7579 }
7580 process_input(p,in);
7581 fclose(in);
7582 }
7583 sqlite3_free(zBuf);
7584}
7585
7586/*
7587** Show available command line options
7588*/
7589static const char zOptions[] =
7590 " -ascii set output mode to 'ascii'\n"
7591 " -bail stop after hitting an error\n"
7592 " -batch force batch I/O\n"
7593 " -column set output mode to 'column'\n"
7594 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
7595 " -csv set output mode to 'csv'\n"
7596 " -echo print commands before execution\n"
7597 " -init FILENAME read/process named file\n"
7598 " -[no]header turn headers on or off\n"
7599#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7600 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7601#endif
7602 " -help show this message\n"
7603 " -html set output mode to HTML\n"
7604 " -interactive force interactive I/O\n"
7605 " -line set output mode to 'line'\n"
7606 " -list set output mode to 'list'\n"
7607 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
7608 " -mmap N default mmap size set to N\n"
7609#ifdef SQLITE_ENABLE_MULTIPLEX
7610 " -multiplex enable the multiplexor VFS\n"
7611#endif
7612 " -newline SEP set output row separator. Default: '\\n'\n"
7613 " -nullvalue TEXT set text string for NULL values. Default ''\n"
7614 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7615 " -quote set output mode to 'quote'\n"
drh2ce15c32017-07-11 13:34:40 +00007616 " -separator SEP set output column separator. Default: '|'\n"
7617 " -stats print memory stats before each finalize\n"
7618 " -version show SQLite version\n"
7619 " -vfs NAME use NAME as the default VFS\n"
7620#ifdef SQLITE_ENABLE_VFSTRACE
7621 " -vfstrace enable tracing of all VFS calls\n"
7622#endif
7623;
7624static void usage(int showDetail){
7625 utf8_printf(stderr,
7626 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
7627 "FILENAME is the name of an SQLite database. A new database is created\n"
7628 "if the file does not previously exist.\n", Argv0);
7629 if( showDetail ){
7630 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
7631 }else{
7632 raw_printf(stderr, "Use the -help option for additional information\n");
7633 }
7634 exit(1);
7635}
7636
7637/*
7638** Initialize the state information in data
7639*/
7640static void main_init(ShellState *data) {
7641 memset(data, 0, sizeof(*data));
7642 data->normalMode = data->cMode = data->mode = MODE_List;
7643 data->autoExplain = 1;
7644 memcpy(data->colSeparator,SEP_Column, 2);
7645 memcpy(data->rowSeparator,SEP_Row, 2);
7646 data->showHeader = 0;
7647 data->shellFlgs = SHFLG_Lookaside;
7648 sqlite3_config(SQLITE_CONFIG_URI, 1);
7649 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
7650 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
7651 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7652 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
7653}
7654
7655/*
7656** Output text to the console in a font that attracts extra attention.
7657*/
7658#ifdef _WIN32
7659static void printBold(const char *zText){
7660 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7661 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7662 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7663 SetConsoleTextAttribute(out,
7664 FOREGROUND_RED|FOREGROUND_INTENSITY
7665 );
7666 printf("%s", zText);
7667 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
7668}
7669#else
7670static void printBold(const char *zText){
7671 printf("\033[1m%s\033[0m", zText);
7672}
7673#endif
7674
7675/*
7676** Get the argument to an --option. Throw an error and die if no argument
7677** is available.
7678*/
7679static char *cmdline_option_value(int argc, char **argv, int i){
7680 if( i==argc ){
7681 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
7682 argv[0], argv[argc-1]);
7683 exit(1);
7684 }
7685 return argv[i];
7686}
7687
7688#ifndef SQLITE_SHELL_IS_UTF8
7689# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7690# define SQLITE_SHELL_IS_UTF8 (0)
7691# else
7692# define SQLITE_SHELL_IS_UTF8 (1)
7693# endif
7694#endif
7695
7696#if SQLITE_SHELL_IS_UTF8
7697int SQLITE_CDECL main(int argc, char **argv){
7698#else
7699int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
7700 char **argv;
7701#endif
7702 char *zErrMsg = 0;
7703 ShellState data;
7704 const char *zInitFile = 0;
7705 int i;
7706 int rc = 0;
7707 int warnInmemoryDb = 0;
7708 int readStdin = 1;
7709 int nCmd = 0;
7710 char **azCmd = 0;
7711
7712 setBinaryMode(stdin, 0);
7713 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
7714 stdin_is_interactive = isatty(0);
7715 stdout_is_console = isatty(1);
7716
7717#if USE_SYSTEM_SQLITE+0!=1
drhb3c45232017-08-28 14:33:27 +00007718 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
drh2ce15c32017-07-11 13:34:40 +00007719 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
7720 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7721 exit(1);
7722 }
7723#endif
7724 main_init(&data);
7725#if !SQLITE_SHELL_IS_UTF8
7726 sqlite3_initialize();
7727 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7728 if( argv==0 ){
7729 raw_printf(stderr, "out of memory\n");
7730 exit(1);
7731 }
7732 for(i=0; i<argc; i++){
7733 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7734 if( argv[i]==0 ){
7735 raw_printf(stderr, "out of memory\n");
7736 exit(1);
7737 }
7738 }
7739#endif
7740 assert( argc>=1 && argv && argv[0] );
7741 Argv0 = argv[0];
7742
7743 /* Make sure we have a valid signal handler early, before anything
7744 ** else is done.
7745 */
7746#ifdef SIGINT
7747 signal(SIGINT, interrupt_handler);
mistachkinb4bab902017-10-27 17:09:44 +00007748#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
7749 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
drh2ce15c32017-07-11 13:34:40 +00007750#endif
7751
7752#ifdef SQLITE_SHELL_DBNAME_PROC
7753 {
7754 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7755 ** of a C-function that will provide the name of the database file. Use
7756 ** this compile-time option to embed this shell program in larger
7757 ** applications. */
7758 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7759 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7760 warnInmemoryDb = 0;
7761 }
7762#endif
7763
7764 /* Do an initial pass through the command-line argument to locate
7765 ** the name of the database file, the name of the initialization file,
7766 ** the size of the alternative malloc heap,
7767 ** and the first command to execute.
7768 */
7769 for(i=1; i<argc; i++){
7770 char *z;
7771 z = argv[i];
7772 if( z[0]!='-' ){
7773 if( data.zDbFilename==0 ){
7774 data.zDbFilename = z;
7775 }else{
7776 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7777 ** mean that nothing is read from stdin */
7778 readStdin = 0;
7779 nCmd++;
7780 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7781 if( azCmd==0 ){
7782 raw_printf(stderr, "out of memory\n");
7783 exit(1);
7784 }
7785 azCmd[nCmd-1] = z;
7786 }
7787 }
7788 if( z[1]=='-' ) z++;
7789 if( strcmp(z,"-separator")==0
7790 || strcmp(z,"-nullvalue")==0
7791 || strcmp(z,"-newline")==0
7792 || strcmp(z,"-cmd")==0
7793 ){
7794 (void)cmdline_option_value(argc, argv, ++i);
7795 }else if( strcmp(z,"-init")==0 ){
7796 zInitFile = cmdline_option_value(argc, argv, ++i);
7797 }else if( strcmp(z,"-batch")==0 ){
7798 /* Need to check for batch mode here to so we can avoid printing
7799 ** informational messages (like from process_sqliterc) before
7800 ** we do the actual processing of arguments later in a second pass.
7801 */
7802 stdin_is_interactive = 0;
7803 }else if( strcmp(z,"-heap")==0 ){
7804#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7805 const char *zSize;
7806 sqlite3_int64 szHeap;
7807
7808 zSize = cmdline_option_value(argc, argv, ++i);
7809 szHeap = integerValue(zSize);
7810 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
7811 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
7812#else
7813 (void)cmdline_option_value(argc, argv, ++i);
7814#endif
drh2ce15c32017-07-11 13:34:40 +00007815 }else if( strcmp(z,"-pagecache")==0 ){
7816 int n, sz;
7817 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7818 if( sz>70000 ) sz = 70000;
7819 if( sz<0 ) sz = 0;
7820 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7821 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7822 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
7823 data.shellFlgs |= SHFLG_Pagecache;
7824 }else if( strcmp(z,"-lookaside")==0 ){
7825 int n, sz;
7826 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
7827 if( sz<0 ) sz = 0;
7828 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
7829 if( n<0 ) n = 0;
7830 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7831 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
7832#ifdef SQLITE_ENABLE_VFSTRACE
7833 }else if( strcmp(z,"-vfstrace")==0 ){
7834 extern int vfstrace_register(
7835 const char *zTraceName,
7836 const char *zOldVfsName,
7837 int (*xOut)(const char*,void*),
7838 void *pOutArg,
7839 int makeDefault
7840 );
7841 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
7842#endif
7843#ifdef SQLITE_ENABLE_MULTIPLEX
7844 }else if( strcmp(z,"-multiplex")==0 ){
7845 extern int sqlite3_multiple_initialize(const char*,int);
7846 sqlite3_multiplex_initialize(0, 1);
7847#endif
7848 }else if( strcmp(z,"-mmap")==0 ){
7849 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7850 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
7851 }else if( strcmp(z,"-vfs")==0 ){
7852 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
7853 if( pVfs ){
7854 sqlite3_vfs_register(pVfs, 1);
7855 }else{
7856 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
7857 exit(1);
7858 }
7859 }
7860 }
7861 if( data.zDbFilename==0 ){
7862#ifndef SQLITE_OMIT_MEMORYDB
7863 data.zDbFilename = ":memory:";
7864 warnInmemoryDb = argc==1;
7865#else
7866 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
7867 return 1;
7868#endif
7869 }
7870 data.out = stdout;
7871
7872 /* Go ahead and open the database file if it already exists. If the
7873 ** file does not exist, delay opening it. This prevents empty database
7874 ** files from being created if a user mistypes the database name argument
7875 ** to the sqlite command-line tool.
7876 */
7877 if( access(data.zDbFilename, 0)==0 ){
7878 open_db(&data, 0);
7879 }
7880
7881 /* Process the initialization file if there is one. If no -init option
7882 ** is given on the command line, look for a file named ~/.sqliterc and
7883 ** try to process it.
7884 */
7885 process_sqliterc(&data,zInitFile);
7886
7887 /* Make a second pass through the command-line argument and set
7888 ** options. This second pass is delayed until after the initialization
7889 ** file is processed so that the command-line arguments will override
7890 ** settings in the initialization file.
7891 */
7892 for(i=1; i<argc; i++){
7893 char *z = argv[i];
7894 if( z[0]!='-' ) continue;
7895 if( z[1]=='-' ){ z++; }
7896 if( strcmp(z,"-init")==0 ){
7897 i++;
7898 }else if( strcmp(z,"-html")==0 ){
7899 data.mode = MODE_Html;
7900 }else if( strcmp(z,"-list")==0 ){
7901 data.mode = MODE_List;
7902 }else if( strcmp(z,"-quote")==0 ){
7903 data.mode = MODE_Quote;
7904 }else if( strcmp(z,"-line")==0 ){
7905 data.mode = MODE_Line;
7906 }else if( strcmp(z,"-column")==0 ){
7907 data.mode = MODE_Column;
7908 }else if( strcmp(z,"-csv")==0 ){
7909 data.mode = MODE_Csv;
7910 memcpy(data.colSeparator,",",2);
7911 }else if( strcmp(z,"-ascii")==0 ){
7912 data.mode = MODE_Ascii;
7913 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
7914 SEP_Unit);
7915 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
7916 SEP_Record);
7917 }else if( strcmp(z,"-separator")==0 ){
7918 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
7919 "%s",cmdline_option_value(argc,argv,++i));
7920 }else if( strcmp(z,"-newline")==0 ){
7921 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
7922 "%s",cmdline_option_value(argc,argv,++i));
7923 }else if( strcmp(z,"-nullvalue")==0 ){
7924 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
7925 "%s",cmdline_option_value(argc,argv,++i));
7926 }else if( strcmp(z,"-header")==0 ){
7927 data.showHeader = 1;
7928 }else if( strcmp(z,"-noheader")==0 ){
7929 data.showHeader = 0;
7930 }else if( strcmp(z,"-echo")==0 ){
7931 ShellSetFlag(&data, SHFLG_Echo);
7932 }else if( strcmp(z,"-eqp")==0 ){
drhada70452017-12-21 21:02:27 +00007933 data.autoEQP = AUTOEQP_on;
drh2ce15c32017-07-11 13:34:40 +00007934 }else if( strcmp(z,"-eqpfull")==0 ){
drhada70452017-12-21 21:02:27 +00007935 data.autoEQP = AUTOEQP_full;
drh2ce15c32017-07-11 13:34:40 +00007936 }else if( strcmp(z,"-stats")==0 ){
7937 data.statsOn = 1;
7938 }else if( strcmp(z,"-scanstats")==0 ){
7939 data.scanstatsOn = 1;
7940 }else if( strcmp(z,"-backslash")==0 ){
7941 /* Undocumented command-line option: -backslash
7942 ** Causes C-style backslash escapes to be evaluated in SQL statements
7943 ** prior to sending the SQL into SQLite. Useful for injecting
7944 ** crazy bytes in the middle of SQL statements for testing and debugging.
7945 */
7946 ShellSetFlag(&data, SHFLG_Backslash);
7947 }else if( strcmp(z,"-bail")==0 ){
7948 bail_on_error = 1;
7949 }else if( strcmp(z,"-version")==0 ){
7950 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
7951 return 0;
7952 }else if( strcmp(z,"-interactive")==0 ){
7953 stdin_is_interactive = 1;
7954 }else if( strcmp(z,"-batch")==0 ){
7955 stdin_is_interactive = 0;
7956 }else if( strcmp(z,"-heap")==0 ){
7957 i++;
drh2ce15c32017-07-11 13:34:40 +00007958 }else if( strcmp(z,"-pagecache")==0 ){
7959 i+=2;
7960 }else if( strcmp(z,"-lookaside")==0 ){
7961 i+=2;
7962 }else if( strcmp(z,"-mmap")==0 ){
7963 i++;
7964 }else if( strcmp(z,"-vfs")==0 ){
7965 i++;
7966#ifdef SQLITE_ENABLE_VFSTRACE
7967 }else if( strcmp(z,"-vfstrace")==0 ){
7968 i++;
7969#endif
7970#ifdef SQLITE_ENABLE_MULTIPLEX
7971 }else if( strcmp(z,"-multiplex")==0 ){
7972 i++;
7973#endif
7974 }else if( strcmp(z,"-help")==0 ){
7975 usage(1);
7976 }else if( strcmp(z,"-cmd")==0 ){
7977 /* Run commands that follow -cmd first and separately from commands
7978 ** that simply appear on the command-line. This seems goofy. It would
7979 ** be better if all commands ran in the order that they appear. But
7980 ** we retain the goofy behavior for historical compatibility. */
7981 if( i==argc-1 ) break;
7982 z = cmdline_option_value(argc,argv,++i);
7983 if( z[0]=='.' ){
7984 rc = do_meta_command(z, &data);
7985 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
7986 }else{
7987 open_db(&data, 0);
7988 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7989 if( zErrMsg!=0 ){
7990 utf8_printf(stderr,"Error: %s\n", zErrMsg);
7991 if( bail_on_error ) return rc!=0 ? rc : 1;
7992 }else if( rc!=0 ){
7993 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
7994 if( bail_on_error ) return rc;
7995 }
7996 }
7997 }else{
7998 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7999 raw_printf(stderr,"Use -help for a list of options.\n");
8000 return 1;
8001 }
8002 data.cMode = data.mode;
8003 }
8004
8005 if( !readStdin ){
8006 /* Run all arguments that do not begin with '-' as if they were separate
8007 ** command-line inputs, except for the argToSkip argument which contains
8008 ** the database filename.
8009 */
8010 for(i=0; i<nCmd; i++){
8011 if( azCmd[i][0]=='.' ){
8012 rc = do_meta_command(azCmd[i], &data);
8013 if( rc ) return rc==2 ? 0 : rc;
8014 }else{
8015 open_db(&data, 0);
8016 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
8017 if( zErrMsg!=0 ){
8018 utf8_printf(stderr,"Error: %s\n", zErrMsg);
8019 return rc!=0 ? rc : 1;
8020 }else if( rc!=0 ){
8021 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
8022 return rc;
8023 }
8024 }
8025 }
8026 free(azCmd);
8027 }else{
8028 /* Run commands received from standard input
8029 */
8030 if( stdin_is_interactive ){
8031 char *zHome;
8032 char *zHistory = 0;
8033 int nHistory;
8034 printf(
8035 "SQLite version %s %.19s\n" /*extra-version-info*/
8036 "Enter \".help\" for usage hints.\n",
8037 sqlite3_libversion(), sqlite3_sourceid()
8038 );
8039 if( warnInmemoryDb ){
8040 printf("Connected to a ");
8041 printBold("transient in-memory database");
8042 printf(".\nUse \".open FILENAME\" to reopen on a "
8043 "persistent database.\n");
8044 }
8045 zHome = find_home_dir(0);
8046 if( zHome ){
8047 nHistory = strlen30(zHome) + 20;
8048 if( (zHistory = malloc(nHistory))!=0 ){
8049 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8050 }
8051 }
8052 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +00008053#if HAVE_READLINE || HAVE_EDITLINE
8054 rl_attempted_completion_function = readline_completion;
8055#elif HAVE_LINENOISE
8056 linenoiseSetCompletionCallback(linenoise_completion);
8057#endif
drh2ce15c32017-07-11 13:34:40 +00008058 rc = process_input(&data, 0);
8059 if( zHistory ){
drh5a75dd82017-07-18 20:59:40 +00008060 shell_stifle_history(2000);
drh2ce15c32017-07-11 13:34:40 +00008061 shell_write_history(zHistory);
8062 free(zHistory);
8063 }
8064 }else{
8065 rc = process_input(&data, stdin);
8066 }
8067 }
8068 set_table_name(&data, 0);
8069 if( data.db ){
8070 session_close_all(&data);
8071 sqlite3_close(data.db);
8072 }
8073 sqlite3_free(data.zFreeOnClose);
8074 find_home_dir(1);
8075#if !SQLITE_SHELL_IS_UTF8
8076 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
8077 sqlite3_free(argv);
8078#endif
8079 return rc;
8080}