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