4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
11 *************************************************************************
12 ** This file contains code to implement the "sqlite" command line
13 ** utility for accessing SQLite databases.
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
21 ** Warning pragmas copied from msvc.h in the core.
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) */
42 ** No support for loadable extensions in VxWorks.
44 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45 # define SQLITE_OMIT_LOAD_EXTENSION 1
49 ** Enable large-file support for fopen() and friends on unix.
51 #ifndef SQLITE_DISABLE_LFS
52 # define _LARGE_FILE 1
53 # ifndef _FILE_OFFSET_BITS
54 # define _FILE_OFFSET_BITS 64
56 # define _LARGEFILE_SOURCE 1
64 typedef sqlite3_int64 i64
;
65 typedef sqlite3_uint64 u64
;
66 typedef unsigned char u8
;
67 #if SQLITE_USER_AUTHENTICATION
68 # include "sqlite3userauth.h"
73 #if !defined(_WIN32) && !defined(WIN32)
75 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
79 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
82 # if defined(__MINGW32__)
83 # define DIRENT dirent
85 # define S_ISLNK(mode) (0)
89 #include <sys/types.h>
93 # include <readline/readline.h>
94 # include <readline/history.h>
98 # include <editline/readline.h>
101 #if HAVE_EDITLINE || HAVE_READLINE
103 # define shell_add_history(X) add_history(X)
104 # define shell_read_history(X) read_history(X)
105 # define shell_write_history(X) write_history(X)
106 # define shell_stifle_history(X) stifle_history(X)
107 # define shell_readline(X) readline(X)
111 # include "linenoise.h"
112 # define shell_add_history(X) linenoiseHistoryAdd(X)
113 # define shell_read_history(X) linenoiseHistoryLoad(X)
114 # define shell_write_history(X) linenoiseHistorySave(X)
115 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
116 # define shell_readline(X) linenoise(X)
120 # define shell_read_history(X)
121 # define shell_write_history(X)
122 # define shell_stifle_history(X)
124 # define SHELL_USE_LOCAL_GETLINE 1
128 #if defined(_WIN32) || defined(WIN32)
131 # define isatty(h) _isatty(h)
133 # define access(f,m) _access((f),(m))
136 # define popen _popen
138 # define pclose _pclose
140 /* Make sure isatty() has a prototype. */
141 extern int isatty(int);
143 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
144 /* popen and pclose are not C89 functions and so are
145 ** sometimes omitted from the <stdio.h> header */
146 extern FILE *popen(const char*,const char*);
147 extern int pclose(FILE*);
149 # define SQLITE_OMIT_POPEN 1
153 #if defined(_WIN32_WCE)
154 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
155 * thus we always assume that we have a console. That can be
156 * overridden with the -batch command line option.
161 /* ctype macros that work with signed characters */
162 #define IsSpace(X) isspace((unsigned char)X)
163 #define IsDigit(X) isdigit((unsigned char)X)
164 #define ToLower(X) (char)tolower((unsigned char)X)
166 #if defined(_WIN32) || defined(WIN32)
169 /* string conversion routines only needed on Win32 */
170 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
171 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
172 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
173 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
176 /* On Windows, we normally run with output mode of TEXT so that \n characters
177 ** are automatically translated into \r\n. However, this behavior needs
178 ** to be disabled in some cases (ex: when generating CSV output and when
179 ** rendering quoted strings that contain \n characters). The following
180 ** routines take care of that.
182 #if defined(_WIN32) || defined(WIN32)
183 static void setBinaryMode(FILE *file
, int isOutput
){
184 if( isOutput
) fflush(file
);
185 _setmode(_fileno(file
), _O_BINARY
);
187 static void setTextMode(FILE *file
, int isOutput
){
188 if( isOutput
) fflush(file
);
189 _setmode(_fileno(file
), _O_TEXT
);
192 # define setBinaryMode(X,Y)
193 # define setTextMode(X,Y)
197 /* True if the timer is enabled */
198 static int enableTimer
= 0;
200 /* Return the current wall-clock time */
201 static sqlite3_int64
timeOfDay(void){
202 static sqlite3_vfs
*clockVfs
= 0;
204 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
205 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
206 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
209 clockVfs
->xCurrentTime(clockVfs
, &r
);
210 t
= (sqlite3_int64
)(r
*86400000.0);
215 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
216 #include <sys/time.h>
217 #include <sys/resource.h>
219 /* VxWorks does not support getrusage() as far as we can determine */
220 #if defined(_WRS_KERNEL) || defined(__RTP__)
222 struct timeval ru_utime
; /* user CPU time used */
223 struct timeval ru_stime
; /* system CPU time used */
225 #define getrusage(A,B) memset(B,0,sizeof(*B))
228 /* Saved resource information for the beginning of an operation */
229 static struct rusage sBegin
; /* CPU time at start */
230 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
233 ** Begin timing an operation
235 static void beginTimer(void){
237 getrusage(RUSAGE_SELF
, &sBegin
);
238 iBegin
= timeOfDay();
242 /* Return the difference of two time_structs in seconds */
243 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
244 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
245 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
249 ** Print the timing results.
251 static void endTimer(void){
253 sqlite3_int64 iEnd
= timeOfDay();
255 getrusage(RUSAGE_SELF
, &sEnd
);
256 printf("Run Time: real %.3f user %f sys %f\n",
257 (iEnd
- iBegin
)*0.001,
258 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
259 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
263 #define BEGIN_TIMER beginTimer()
264 #define END_TIMER endTimer()
267 #elif (defined(_WIN32) || defined(WIN32))
269 /* Saved resource information for the beginning of an operation */
270 static HANDLE hProcess
;
271 static FILETIME ftKernelBegin
;
272 static FILETIME ftUserBegin
;
273 static sqlite3_int64 ftWallBegin
;
274 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
275 LPFILETIME
, LPFILETIME
);
276 static GETPROCTIMES getProcessTimesAddr
= NULL
;
279 ** Check to see if we have timer support. Return 1 if necessary
280 ** support found (or found previously).
282 static int hasTimer(void){
283 if( getProcessTimesAddr
){
286 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
287 ** versions. See if the version we are running on has it, and if it
288 ** does, save off a pointer to it and the current process handle.
290 hProcess
= GetCurrentProcess();
292 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
293 if( NULL
!= hinstLib
){
294 getProcessTimesAddr
=
295 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
296 if( NULL
!= getProcessTimesAddr
){
299 FreeLibrary(hinstLib
);
307 ** Begin timing an operation
309 static void beginTimer(void){
310 if( enableTimer
&& getProcessTimesAddr
){
311 FILETIME ftCreation
, ftExit
;
312 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
313 &ftKernelBegin
,&ftUserBegin
);
314 ftWallBegin
= timeOfDay();
318 /* Return the difference of two FILETIME structs in seconds */
319 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
320 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
321 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
322 return (double) ((i64End
- i64Start
) / 10000000.0);
326 ** Print the timing results.
328 static void endTimer(void){
329 if( enableTimer
&& getProcessTimesAddr
){
330 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
331 sqlite3_int64 ftWallEnd
= timeOfDay();
332 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
333 printf("Run Time: real %.3f user %f sys %f\n",
334 (ftWallEnd
- ftWallBegin
)*0.001,
335 timeDiff(&ftUserBegin
, &ftUserEnd
),
336 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
340 #define BEGIN_TIMER beginTimer()
341 #define END_TIMER endTimer()
342 #define HAS_TIMER hasTimer()
351 ** Used to prevent warnings about unused parameters
353 #define UNUSED_PARAMETER(x) (void)(x)
356 ** Number of elements in an array
358 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
361 ** If the following flag is set, then command execution stops
362 ** at an error if we are not interactive.
364 static int bail_on_error
= 0;
367 ** Threat stdin as an interactive input if the following variable
368 ** is true. Otherwise, assume stdin is connected to a file or pipe.
370 static int stdin_is_interactive
= 1;
373 ** On Windows systems we have to know if standard output is a console
374 ** in order to translate UTF-8 into MBCS. The following variable is
375 ** true if translation is required.
377 static int stdout_is_console
= 1;
380 ** The following is the open SQLite database. We make a pointer
381 ** to this database a static variable so that it can be accessed
382 ** by the SIGINT handler to interrupt database processing.
384 static sqlite3
*globalDb
= 0;
387 ** True if an interrupt (Control-C) has been received.
389 static volatile int seenInterrupt
= 0;
392 ** This is the name of our program. It is set in main(), used
393 ** in a number of other places, mostly for error messages.
398 ** Prompt strings. Initialized in main. Settable with
399 ** .prompt main continue
401 static char mainPrompt
[20]; /* First line prompt. default: "sqlite> "*/
402 static char continuePrompt
[20]; /* Continuation prompt. default: " ...> " */
405 ** Render output like fprintf(). Except, if the output is going to the
406 ** console and if this is running on a Windows machine, translate the
407 ** output from UTF-8 into MBCS.
409 #if defined(_WIN32) || defined(WIN32)
410 void utf8_printf(FILE *out
, const char *zFormat
, ...){
412 va_start(ap
, zFormat
);
413 if( stdout_is_console
&& (out
==stdout
|| out
==stderr
) ){
414 char *z1
= sqlite3_vmprintf(zFormat
, ap
);
415 char *z2
= sqlite3_win32_utf8_to_mbcs_v2(z1
, 0);
420 vfprintf(out
, zFormat
, ap
);
424 #elif !defined(utf8_printf)
425 # define utf8_printf fprintf
429 ** Render output like fprintf(). This should not be used on anything that
430 ** includes string formatting (e.g. "%s").
432 #if !defined(raw_printf)
433 # define raw_printf fprintf
437 ** Write I/O traces to the following stream.
439 #ifdef SQLITE_ENABLE_IOTRACE
440 static FILE *iotrace
= 0;
444 ** This routine works like printf in that its first argument is a
445 ** format string and subsequent arguments are values to be substituted
446 ** in place of % fields. The result of formatting this string
447 ** is written to iotrace.
449 #ifdef SQLITE_ENABLE_IOTRACE
450 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
453 if( iotrace
==0 ) return;
454 va_start(ap
, zFormat
);
455 z
= sqlite3_vmprintf(zFormat
, ap
);
457 utf8_printf(iotrace
, "%s", z
);
463 ** Output string zUtf to stream pOut as w characters. If w is negative,
464 ** then right-justify the text. W is the width in UTF-8 characters, not
465 ** in bytes. This is different from the %*.*s specification in printf
466 ** since with %*.*s the width is measured in bytes, not characters.
468 static void utf8_width_print(FILE *pOut
, int w
, const char *zUtf
){
471 int aw
= w
<0 ? -w
: w
;
473 if( aw
>(int)sizeof(zBuf
)/3 ) aw
= (int)sizeof(zBuf
)/3;
474 for(i
=n
=0; zUtf
[i
]; i
++){
475 if( (zUtf
[i
]&0xc0)!=0x80 ){
478 do{ i
++; }while( (zUtf
[i
]&0xc0)==0x80 );
484 utf8_printf(pOut
, "%.*s", i
, zUtf
);
486 utf8_printf(pOut
, "%*s%s", aw
-n
, "", zUtf
);
488 utf8_printf(pOut
, "%s%*s", zUtf
, aw
-n
, "");
494 ** Determines if a string is a number of not.
496 static int isNumber(const char *z
, int *realnum
){
497 if( *z
=='-' || *z
=='+' ) z
++;
502 if( realnum
) *realnum
= 0;
503 while( IsDigit(*z
) ){ z
++; }
506 if( !IsDigit(*z
) ) return 0;
507 while( IsDigit(*z
) ){ z
++; }
508 if( realnum
) *realnum
= 1;
510 if( *z
=='e' || *z
=='E' ){
512 if( *z
=='+' || *z
=='-' ) z
++;
513 if( !IsDigit(*z
) ) return 0;
514 while( IsDigit(*z
) ){ z
++; }
515 if( realnum
) *realnum
= 1;
521 ** Compute a string length that is limited to what can be stored in
522 ** lower 30 bits of a 32-bit signed integer.
524 static int strlen30(const char *z
){
526 while( *z2
){ z2
++; }
527 return 0x3fffffff & (int)(z2
- z
);
531 ** Return the length of a string in characters. Multibyte UTF8 characters
532 ** count as a single character.
534 static int strlenChar(const char *z
){
537 if( (0xc0&*(z
++))!=0x80 ) n
++;
543 ** This routine reads a line of text from FILE in, stores
544 ** the text in memory obtained from malloc() and returns a pointer
545 ** to the text. NULL is returned at end of file, or if malloc()
548 ** If zLine is not NULL then it is a malloced buffer returned from
549 ** a previous call to this routine that may be reused.
551 static char *local_getline(char *zLine
, FILE *in
){
552 int nLine
= zLine
==0 ? 0 : 100;
557 nLine
= nLine
*2 + 100;
558 zLine
= realloc(zLine
, nLine
);
559 if( zLine
==0 ) return 0;
561 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
569 while( zLine
[n
] ) n
++;
570 if( n
>0 && zLine
[n
-1]=='\n' ){
572 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
577 #if defined(_WIN32) || defined(WIN32)
578 /* For interactive input on Windows systems, translate the
579 ** multi-byte characterset characters into UTF-8. */
580 if( stdin_is_interactive
&& in
==stdin
){
581 char *zTrans
= sqlite3_win32_mbcs_to_utf8_v2(zLine
, 0);
583 int nTrans
= strlen30(zTrans
)+1;
585 zLine
= realloc(zLine
, nTrans
);
587 sqlite3_free(zTrans
);
591 memcpy(zLine
, zTrans
, nTrans
);
592 sqlite3_free(zTrans
);
595 #endif /* defined(_WIN32) || defined(WIN32) */
600 ** Retrieve a single line of input text.
602 ** If in==0 then read from standard input and prompt before each line.
603 ** If isContinuation is true, then a continuation prompt is appropriate.
604 ** If isContinuation is zero, then the main prompt should be used.
606 ** If zPrior is not NULL then it is a buffer from a prior call to this
607 ** routine that can be reused.
609 ** The result is stored in space obtained from malloc() and must either
610 ** be freed by the caller or else passed back into this routine via the
611 ** zPrior argument for reuse.
613 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
617 zResult
= local_getline(zPrior
, in
);
619 zPrompt
= isContinuation
? continuePrompt
: mainPrompt
;
620 #if SHELL_USE_LOCAL_GETLINE
621 printf("%s", zPrompt
);
623 zResult
= local_getline(zPrior
, stdin
);
626 zResult
= shell_readline(zPrompt
);
627 if( zResult
&& *zResult
) shell_add_history(zResult
);
635 ** Return the value of a hexadecimal digit. Return -1 if the input
636 ** is not a hex digit.
638 static int hexDigitValue(char c
){
639 if( c
>='0' && c
<='9' ) return c
- '0';
640 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
641 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
646 ** Interpret zArg as an integer value, possibly with suffixes.
648 static sqlite3_int64
integerValue(const char *zArg
){
650 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
652 { "MiB", 1024*1024 },
653 { "GiB", 1024*1024*1024 },
656 { "GB", 1000000000 },
666 }else if( zArg
[0]=='+' ){
669 if( zArg
[0]=='0' && zArg
[1]=='x' ){
672 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
677 while( IsDigit(zArg
[0]) ){
678 v
= v
*10 + zArg
[0] - '0';
682 for(i
=0; i
<ArraySize(aMult
); i
++){
683 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
688 return isNeg
? -v
: v
;
692 ** A variable length string to which one can append text.
694 typedef struct ShellText ShellText
;
702 ** Initialize and destroy a ShellText object
704 static void initText(ShellText
*p
){
705 memset(p
, 0, sizeof(*p
));
707 static void freeText(ShellText
*p
){
712 /* zIn is either a pointer to a NULL-terminated string in memory obtained
713 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
714 ** added to zIn, and the result returned in memory obtained from malloc().
715 ** zIn, if it was not NULL, is freed.
717 ** If the third argument, quote, is not '\0', then it is used as a
718 ** quote character for zAppend.
720 static void appendText(ShellText
*p
, char const *zAppend
, char quote
){
723 int nAppend
= strlen30(zAppend
);
725 len
= nAppend
+p
->n
+1;
728 for(i
=0; i
<nAppend
; i
++){
729 if( zAppend
[i
]==quote
) len
++;
733 if( p
->n
+len
>=p
->nAlloc
){
734 p
->nAlloc
= p
->nAlloc
*2 + len
+ 20;
735 p
->z
= realloc(p
->z
, p
->nAlloc
);
737 memset(p
, 0, sizeof(*p
));
743 char *zCsr
= p
->z
+p
->n
;
745 for(i
=0; i
<nAppend
; i
++){
746 *zCsr
++ = zAppend
[i
];
747 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
750 p
->n
= (int)(zCsr
- p
->z
);
753 memcpy(p
->z
+p
->n
, zAppend
, nAppend
);
760 ** Attempt to determine if identifier zName needs to be quoted, either
761 ** because it contains non-alphanumeric characters, or because it is an
762 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
763 ** that quoting is required.
765 ** Return '"' if quoting is required. Return 0 if no quoting is required.
767 static char quoteChar(const char *zName
){
768 /* All SQLite keywords, in alphabetical order */
769 static const char *azKeywords
[] = {
770 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
771 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
772 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
773 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
774 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
775 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
776 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
777 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
778 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
779 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
780 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
781 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
782 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
783 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
784 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
785 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
786 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
789 int i
, lwr
, upr
, mid
, c
;
790 if( !isalpha((unsigned char)zName
[0]) && zName
[0]!='_' ) return '"';
791 for(i
=0; zName
[i
]; i
++){
792 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ) return '"';
795 upr
= sizeof(azKeywords
)/sizeof(azKeywords
[0]) - 1;
798 c
= sqlite3_stricmp(azKeywords
[mid
], zName
);
799 if( c
==0 ) return '"';
810 ** Construct a fake object name and column list to describe the structure
811 ** of the view, virtual table, or table valued function zSchema.zName.
813 static char *shellFakeSchema(
814 sqlite3
*db
, /* The database connection containing the vtab */
815 const char *zSchema
, /* Schema of the database holding the vtab */
816 const char *zName
/* The name of the virtual table */
818 sqlite3_stmt
*pStmt
= 0;
825 zSql
= sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
826 zSchema
? zSchema
: "main", zName
);
827 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
831 cQuote
= quoteChar(zSchema
);
832 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")==0 ) cQuote
= 0;
833 appendText(&s
, zSchema
, cQuote
);
834 appendText(&s
, ".", 0);
836 cQuote
= quoteChar(zName
);
837 appendText(&s
, zName
, cQuote
);
838 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
839 const char *zCol
= (const char*)sqlite3_column_text(pStmt
, 1);
841 appendText(&s
, zDiv
, 0);
843 cQuote
= quoteChar(zCol
);
844 appendText(&s
, zCol
, cQuote
);
846 appendText(&s
, ")", 0);
847 sqlite3_finalize(pStmt
);
856 ** SQL function: shell_module_schema(X)
858 ** Return a fake schema for the table-valued function or eponymous virtual
861 static void shellModuleSchema(
862 sqlite3_context
*pCtx
,
864 sqlite3_value
**apVal
866 const char *zName
= (const char*)sqlite3_value_text(apVal
[0]);
867 char *zFake
= shellFakeSchema(sqlite3_context_db_handle(pCtx
), 0, zName
);
868 UNUSED_PARAMETER(nVal
);
870 sqlite3_result_text(pCtx
, sqlite3_mprintf("/* %s */", zFake
),
877 ** SQL function: shell_add_schema(S,X)
879 ** Add the schema name X to the CREATE statement in S and return the result.
882 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
887 ** CREATE UNIQUE INDEX
890 ** CREATE VIRTUAL TABLE
892 ** This UDF is used by the .schema command to insert the schema name of
893 ** attached databases into the middle of the sqlite_master.sql field.
895 static void shellAddSchemaName(
896 sqlite3_context
*pCtx
,
898 sqlite3_value
**apVal
900 static const char *aPrefix
[] = {
909 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
910 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
911 const char *zName
= (const char*)sqlite3_value_text(apVal
[2]);
912 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
913 UNUSED_PARAMETER(nVal
);
914 if( zIn
!=0 && strncmp(zIn
, "CREATE ", 7)==0 ){
915 for(i
=0; i
<(int)(sizeof(aPrefix
)/sizeof(aPrefix
[0])); i
++){
916 int n
= strlen30(aPrefix
[i
]);
917 if( strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
921 char cQuote
= quoteChar(zSchema
);
922 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")!=0 ){
923 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
925 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
929 && aPrefix
[i
][0]=='V'
930 && (zFake
= shellFakeSchema(db
, zSchema
, zName
))!=0
933 z
= sqlite3_mprintf("%s\n/* %s */", zIn
, zFake
);
935 z
= sqlite3_mprintf("%z\n/* %s */", z
, zFake
);
940 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
946 sqlite3_result_value(pCtx
, apVal
[0]);
950 ** The source code for several run-time loadable extensions is inserted
951 ** below by the ../tool/mkshellc.tcl script. Before processing that included
952 ** code, we need to override some macros to make the included program code
953 ** work here in the middle of this regular program.
955 #define SQLITE_EXTENSION_INIT1
956 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
958 #if defined(_WIN32) && defined(_MSC_VER)
959 INCLUDE test_windirent
.h
960 INCLUDE test_windirent
.c
961 #define dirent DIRENT
963 INCLUDE
../ext
/misc
/shathree
.c
964 INCLUDE
../ext
/misc
/fileio
.c
965 INCLUDE
../ext
/misc
/completion
.c
966 INCLUDE
../ext
/misc
/appendvfs
.c
967 #ifdef SQLITE_HAVE_ZLIB
968 INCLUDE
../ext
/misc
/zipfile
.c
969 INCLUDE
../ext
/misc
/sqlar
.c
971 INCLUDE
../ext
/expert
/sqlite3expert
.h
972 INCLUDE
../ext
/expert
/sqlite3expert
.c
974 #if defined(SQLITE_ENABLE_SESSION)
976 ** State information for a single open session
978 typedef struct OpenSession OpenSession
;
980 char *zName
; /* Symbolic name for this session */
981 int nFilter
; /* Number of xFilter rejection GLOB patterns */
982 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
983 sqlite3_session
*p
; /* The open session */
988 ** Shell output mode information from before ".explain on",
989 ** saved so that it can be restored by ".explain off"
991 typedef struct SavedModeInfo SavedModeInfo
;
992 struct SavedModeInfo
{
993 int valid
; /* Is there legit data in here? */
994 int mode
; /* Mode prior to ".explain on" */
995 int showHeader
; /* The ".header" setting prior to ".explain on" */
996 int colWidth
[100]; /* Column widths prior to ".explain on" */
999 typedef struct ExpertInfo ExpertInfo
;
1001 sqlite3expert
*pExpert
;
1006 ** State information about the database connection is contained in an
1007 ** instance of the following structure.
1009 typedef struct ShellState ShellState
;
1011 sqlite3
*db
; /* The database */
1012 u8 autoExplain
; /* Automatically turn on .explain mode */
1013 u8 autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1014 u8 statsOn
; /* True to display memory stats before each finalize */
1015 u8 scanstatsOn
; /* True to display scan stats before each finalize */
1016 u8 openMode
; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1017 u8 doXdgOpen
; /* Invoke start/open/xdg-open in output_reset() */
1018 int outCount
; /* Revert to stdout when reaching zero */
1019 int cnt
; /* Number of records displayed so far */
1020 FILE *out
; /* Write results here */
1021 FILE *traceOut
; /* Output for sqlite3_trace() */
1022 int nErr
; /* Number of errors seen */
1023 int mode
; /* An output mode setting */
1024 int modePrior
; /* Saved mode */
1025 int cMode
; /* temporary output mode for the current query */
1026 int normalMode
; /* Output mode before ".explain on" */
1027 int writableSchema
; /* True if PRAGMA writable_schema=ON */
1028 int showHeader
; /* True to show column names in List or Column mode */
1029 int nCheck
; /* Number of ".check" commands run */
1030 unsigned shellFlgs
; /* Various flags */
1031 char *zDestTable
; /* Name of destination table when MODE_Insert */
1032 char *zTempFile
; /* Temporary file that might need deleting */
1033 char zTestcase
[30]; /* Name of current test case */
1034 char colSeparator
[20]; /* Column separator character for several modes */
1035 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
1036 char colSepPrior
[20]; /* Saved column separator */
1037 char rowSepPrior
[20]; /* Saved row separator */
1038 int colWidth
[100]; /* Requested width of each column when in column mode*/
1039 int actualWidth
[100]; /* Actual width of each column */
1040 char nullValue
[20]; /* The text to print when a NULL comes back from
1042 char outfile
[FILENAME_MAX
]; /* Filename for *out */
1043 const char *zDbFilename
; /* name of the database file */
1044 char *zFreeOnClose
; /* Filename to free when closing */
1045 const char *zVfs
; /* Name of VFS to use */
1046 sqlite3_stmt
*pStmt
; /* Current statement if any. */
1047 FILE *pLog
; /* Write log output here */
1048 int *aiIndent
; /* Array of indents used in MODE_Explain */
1049 int nIndent
; /* Size of array aiIndent[] */
1050 int iIndent
; /* Index of current op in aiIndent[] */
1051 #if defined(SQLITE_ENABLE_SESSION)
1052 int nSession
; /* Number of active sessions */
1053 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
1055 ExpertInfo expert
; /* Valid if previous command was ".expert OPT..." */
1059 /* Allowed values for ShellState.autoEQP
1061 #define AUTOEQP_off 0
1062 #define AUTOEQP_on 1
1063 #define AUTOEQP_trigger 2
1064 #define AUTOEQP_full 3
1066 /* Allowed values for ShellState.openMode
1068 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1069 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1070 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1071 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1074 ** These are the allowed shellFlgs values
1076 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1077 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1078 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1079 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1080 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1081 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1082 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1085 ** Macros for testing and setting shellFlgs
1087 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1088 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1089 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1092 ** These are the allowed modes.
1094 #define MODE_Line 0 /* One column per line. Blank line between records */
1095 #define MODE_Column 1 /* One record per line in neat columns */
1096 #define MODE_List 2 /* One record per line with a separator */
1097 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1098 #define MODE_Html 4 /* Generate an XHTML table */
1099 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1100 #define MODE_Quote 6 /* Quote values as for SQL */
1101 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1102 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1103 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1104 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1105 #define MODE_Pretty 11 /* Pretty-print schemas */
1107 static const char *modeDescr
[] = {
1123 ** These are the column/row/line separators used by the various
1124 ** import/export modes.
1126 #define SEP_Column "|"
1127 #define SEP_Row "\n"
1128 #define SEP_Tab "\t"
1129 #define SEP_Space " "
1130 #define SEP_Comma ","
1131 #define SEP_CrLf "\r\n"
1132 #define SEP_Unit "\x1F"
1133 #define SEP_Record "\x1E"
1136 ** A callback for the sqlite3_log() interface.
1138 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
1139 ShellState
*p
= (ShellState
*)pArg
;
1140 if( p
->pLog
==0 ) return;
1141 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
1146 ** SQL function: shell_putsnl(X)
1148 ** Write the text X to the screen (or whatever output is being directed)
1149 ** adding a newline at the end, and then return X.
1151 static void shellPutsFunc(
1152 sqlite3_context
*pCtx
,
1154 sqlite3_value
**apVal
1156 ShellState
*p
= (ShellState
*)sqlite3_user_data(pCtx
);
1158 utf8_printf(p
->out
, "%s\n", sqlite3_value_text(apVal
[0]));
1159 sqlite3_result_value(pCtx
, apVal
[0]);
1163 ** SQL function: edit(VALUE)
1164 ** edit(VALUE,EDITOR)
1168 ** (1) Write VALUE into a temporary file.
1169 ** (2) Run program EDITOR on that temporary file.
1170 ** (3) Read the temporary file back and return its content as the result.
1171 ** (4) Delete the temporary file
1173 ** If the EDITOR argument is omitted, use the value in the VISUAL
1174 ** environment variable. If still there is no EDITOR, through an error.
1176 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1178 #ifndef SQLITE_NOHAVE_SYSTEM
1179 static void editFunc(
1180 sqlite3_context
*context
,
1182 sqlite3_value
**argv
1184 const char *zEditor
;
1185 char *zTempFile
= 0;
1193 unsigned char *p
= 0;
1196 zEditor
= (const char*)sqlite3_value_text(argv
[1]);
1198 zEditor
= getenv("VISUAL");
1201 sqlite3_result_error(context
, "no editor for edit()", -1);
1204 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
){
1205 sqlite3_result_error(context
, "NULL input to edit()", -1);
1208 db
= sqlite3_context_db_handle(context
);
1210 sqlite3_file_control(db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &zTempFile
);
1212 sqlite3_uint64 r
= 0;
1213 sqlite3_randomness(sizeof(r
), &r
);
1214 zTempFile
= sqlite3_mprintf("temp%llx", r
);
1216 sqlite3_result_error_nomem(context
);
1220 bBin
= sqlite3_value_type(argv
[0])==SQLITE_BLOB
;
1221 f
= fopen(zTempFile
, bBin
? "wb" : "w");
1223 sqlite3_result_error(context
, "edit() cannot open temp file", -1);
1226 sz
= sqlite3_value_bytes(argv
[0]);
1228 x
= fwrite(sqlite3_value_blob(argv
[0]), 1, sz
, f
);
1230 x
= fwrite(sqlite3_value_text(argv
[0]), 1, sz
, f
);
1235 sqlite3_result_error(context
, "edit() could not write the whole file", -1);
1238 zCmd
= sqlite3_mprintf("%s \"%s\"", zEditor
, zTempFile
);
1240 sqlite3_result_error_nomem(context
);
1246 sqlite3_result_error(context
, "EDITOR returned non-zero", -1);
1249 f
= fopen(zTempFile
, bBin
? "rb" : "r");
1251 sqlite3_result_error(context
,
1252 "edit() cannot reopen temp file after edit", -1);
1255 fseek(f
, 0, SEEK_END
);
1258 p
= sqlite3_malloc64( sz
+(bBin
==0) );
1260 sqlite3_result_error_nomem(context
);
1264 x
= fread(p
, 1, sz
, f
);
1266 x
= fread(p
, 1, sz
, f
);
1272 sqlite3_result_error(context
, "could not read back the whole file", -1);
1276 sqlite3_result_blob64(context
, p
, sz
, sqlite3_free
);
1278 sqlite3_result_text64(context
, (const char*)p
, sz
,
1279 sqlite3_free
, SQLITE_UTF8
);
1286 sqlite3_free(zTempFile
);
1289 #endif /* SQLITE_NOHAVE_SYSTEM */
1292 ** Save or restore the current output mode
1294 static void outputModePush(ShellState
*p
){
1295 p
->modePrior
= p
->mode
;
1296 memcpy(p
->colSepPrior
, p
->colSeparator
, sizeof(p
->colSeparator
));
1297 memcpy(p
->rowSepPrior
, p
->rowSeparator
, sizeof(p
->rowSeparator
));
1299 static void outputModePop(ShellState
*p
){
1300 p
->mode
= p
->modePrior
;
1301 memcpy(p
->colSeparator
, p
->colSepPrior
, sizeof(p
->colSeparator
));
1302 memcpy(p
->rowSeparator
, p
->rowSepPrior
, sizeof(p
->rowSeparator
));
1306 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1308 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
1310 char *zBlob
= (char *)pBlob
;
1311 raw_printf(out
,"X'");
1312 for(i
=0; i
<nBlob
; i
++){ raw_printf(out
,"%02x",zBlob
[i
]&0xff); }
1313 raw_printf(out
,"'");
1317 ** Find a string that is not found anywhere in z[]. Return a pointer
1320 ** Try to use zA and zB first. If both of those are already found in z[]
1321 ** then make up some string and store it in the buffer zBuf.
1323 static const char *unused_string(
1324 const char *z
, /* Result must not appear anywhere in z */
1325 const char *zA
, const char *zB
, /* Try these first */
1326 char *zBuf
/* Space to store a generated string */
1329 if( strstr(z
, zA
)==0 ) return zA
;
1330 if( strstr(z
, zB
)==0 ) return zB
;
1332 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
1333 }while( strstr(z
,zBuf
)!=0 );
1338 ** Output the given string as a quoted string using SQL quoting conventions.
1340 ** See also: output_quoted_escaped_string()
1342 static void output_quoted_string(FILE *out
, const char *z
){
1345 setBinaryMode(out
, 1);
1346 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1348 utf8_printf(out
,"'%s'",z
);
1350 raw_printf(out
, "'");
1352 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1355 utf8_printf(out
, "%.*s", i
, z
);
1359 raw_printf(out
, "'");
1367 raw_printf(out
, "'");
1369 setTextMode(out
, 1);
1373 ** Output the given string as a quoted string using SQL quoting conventions.
1374 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1375 ** get corrupted by end-of-line translation facilities in some operating
1378 ** This is like output_quoted_string() but with the addition of the \r\n
1379 ** escape mechanism.
1381 static void output_quoted_escaped_string(FILE *out
, const char *z
){
1384 setBinaryMode(out
, 1);
1385 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1387 utf8_printf(out
,"'%s'",z
);
1389 const char *zNL
= 0;
1390 const char *zCR
= 0;
1393 char zBuf1
[20], zBuf2
[20];
1394 for(i
=0; z
[i
]; i
++){
1395 if( z
[i
]=='\n' ) nNL
++;
1396 if( z
[i
]=='\r' ) nCR
++;
1399 raw_printf(out
, "replace(");
1400 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1403 raw_printf(out
, "replace(");
1404 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1406 raw_printf(out
, "'");
1408 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1411 utf8_printf(out
, "%.*s", i
, z
);
1415 raw_printf(out
, "'");
1423 raw_printf(out
, "%s", zNL
);
1426 raw_printf(out
, "%s", zCR
);
1428 raw_printf(out
, "'");
1430 raw_printf(out
, ",'%s',char(13))", zCR
);
1433 raw_printf(out
, ",'%s',char(10))", zNL
);
1436 setTextMode(out
, 1);
1440 ** Output the given string as a quoted according to C or TCL quoting rules.
1442 static void output_c_string(FILE *out
, const char *z
){
1445 while( (c
= *(z
++))!=0 ){
1452 }else if( c
=='\t' ){
1455 }else if( c
=='\n' ){
1458 }else if( c
=='\r' ){
1461 }else if( !isprint(c
&0xff) ){
1462 raw_printf(out
, "\\%03o", c
&0xff);
1471 ** Output the given string with characters that are special to
1474 static void output_html_string(FILE *out
, const char *z
){
1486 utf8_printf(out
,"%.*s",i
,z
);
1489 raw_printf(out
,"<");
1490 }else if( z
[i
]=='&' ){
1491 raw_printf(out
,"&");
1492 }else if( z
[i
]=='>' ){
1493 raw_printf(out
,">");
1494 }else if( z
[i
]=='\"' ){
1495 raw_printf(out
,""");
1496 }else if( z
[i
]=='\'' ){
1497 raw_printf(out
,"'");
1506 ** If a field contains any character identified by a 1 in the following
1507 ** array, then the string must be quoted for CSV.
1509 static const char needCsvQuote
[] = {
1510 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1511 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1512 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1513 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1514 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1515 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1516 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1517 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1518 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1519 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1520 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1521 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1522 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1523 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1525 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1529 ** Output a single term of CSV. Actually, p->colSeparator is used for
1530 ** the separator, which may or may not be a comma. p->nullValue is
1531 ** the null value. Strings are quoted if necessary. The separator
1532 ** is only issued if bSep is true.
1534 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
1537 utf8_printf(out
,"%s",p
->nullValue
);
1540 int nSep
= strlen30(p
->colSeparator
);
1541 for(i
=0; z
[i
]; i
++){
1542 if( needCsvQuote
[((unsigned char*)z
)[i
]]
1543 || (z
[i
]==p
->colSeparator
[0] &&
1544 (nSep
==1 || memcmp(z
, p
->colSeparator
, nSep
)==0)) ){
1550 char *zQuoted
= sqlite3_mprintf("\"%w\"", z
);
1551 utf8_printf(out
, "%s", zQuoted
);
1552 sqlite3_free(zQuoted
);
1554 utf8_printf(out
, "%s", z
);
1558 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1563 ** This routine runs when the user presses Ctrl-C
1565 static void interrupt_handler(int NotUsed
){
1566 UNUSED_PARAMETER(NotUsed
);
1568 if( seenInterrupt
>2 ) exit(1);
1569 if( globalDb
) sqlite3_interrupt(globalDb
);
1572 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1574 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1576 static BOOL WINAPI
ConsoleCtrlHandler(
1577 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
1579 if( dwCtrlType
==CTRL_C_EVENT
){
1580 interrupt_handler(0);
1587 #ifndef SQLITE_OMIT_AUTHORIZATION
1589 ** When the ".auth ON" is set, the following authorizer callback is
1590 ** invoked. It always returns SQLITE_OK.
1592 static int shellAuth(
1600 ShellState
*p
= (ShellState
*)pClientData
;
1601 static const char *azAction
[] = { 0,
1602 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1603 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1604 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1605 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1606 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1607 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1608 "PRAGMA", "READ", "SELECT",
1609 "TRANSACTION", "UPDATE", "ATTACH",
1610 "DETACH", "ALTER_TABLE", "REINDEX",
1611 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1612 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1620 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
1622 raw_printf(p
->out
, " ");
1624 output_c_string(p
->out
, az
[i
]);
1626 raw_printf(p
->out
, "NULL");
1629 raw_printf(p
->out
, "\n");
1635 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1637 ** This routine converts some CREATE TABLE statements for shadow tables
1638 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1640 static void printSchemaLine(FILE *out
, const char *z
, const char *zTail
){
1641 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
1642 utf8_printf(out
, "CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
1644 utf8_printf(out
, "%s%s", z
, zTail
);
1647 static void printSchemaLineN(FILE *out
, char *z
, int n
, const char *zTail
){
1650 printSchemaLine(out
, z
, zTail
);
1655 ** Return true if string z[] has nothing but whitespace and comments to the
1656 ** end of the first line.
1658 static int wsToEol(const char *z
){
1660 for(i
=0; z
[i
]; i
++){
1661 if( z
[i
]=='\n' ) return 1;
1662 if( IsSpace(z
[i
]) ) continue;
1663 if( z
[i
]=='-' && z
[i
+1]=='-' ) return 1;
1671 ** This is the callback routine that the shell
1672 ** invokes for each row of a query result.
1674 static int shell_callback(
1676 int nArg
, /* Number of result columns */
1677 char **azArg
, /* Text of each result column */
1678 char **azCol
, /* Column names */
1679 int *aiType
/* Column types */
1682 ShellState
*p
= (ShellState
*)pArg
;
1684 if( azArg
==0 ) return 0;
1688 if( azArg
==0 ) break;
1689 for(i
=0; i
<nArg
; i
++){
1690 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
1691 if( len
>w
) w
= len
;
1693 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1694 for(i
=0; i
<nArg
; i
++){
1695 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
1696 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
1702 static const int aExplainWidths
[] = {4, 13, 4, 4, 4, 13, 2, 13};
1703 const int *colWidth
;
1706 if( p
->cMode
==MODE_Column
){
1707 colWidth
= p
->colWidth
;
1708 showHdr
= p
->showHeader
;
1709 rowSep
= p
->rowSeparator
;
1711 colWidth
= aExplainWidths
;
1716 for(i
=0; i
<nArg
; i
++){
1718 if( i
<ArraySize(p
->colWidth
) ){
1724 w
= strlenChar(azCol
[i
] ? azCol
[i
] : "");
1726 n
= strlenChar(azArg
&& azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1729 if( i
<ArraySize(p
->actualWidth
) ){
1730 p
->actualWidth
[i
] = w
;
1733 utf8_width_print(p
->out
, w
, azCol
[i
]);
1734 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1738 for(i
=0; i
<nArg
; i
++){
1740 if( i
<ArraySize(p
->actualWidth
) ){
1741 w
= p
->actualWidth
[i
];
1746 utf8_printf(p
->out
,"%-*.*s%s",w
,w
,
1747 "----------------------------------------------------------"
1748 "----------------------------------------------------------",
1749 i
==nArg
-1 ? rowSep
: " ");
1753 if( azArg
==0 ) break;
1754 for(i
=0; i
<nArg
; i
++){
1756 if( i
<ArraySize(p
->actualWidth
) ){
1757 w
= p
->actualWidth
[i
];
1761 if( p
->cMode
==MODE_Explain
&& azArg
[i
] && strlenChar(azArg
[i
])>w
){
1762 w
= strlenChar(azArg
[i
]);
1764 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
1765 if( p
->iIndent
<p
->nIndent
){
1766 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
1770 utf8_width_print(p
->out
, w
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1771 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1775 case MODE_Semi
: { /* .schema and .fullschema output */
1776 printSchemaLine(p
->out
, azArg
[0], ";\n");
1779 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
1787 if( azArg
[0]==0 ) break;
1788 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
1789 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
1791 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
1794 z
= sqlite3_mprintf("%s", azArg
[0]);
1796 for(i
=0; IsSpace(z
[i
]); i
++){}
1797 for(; (c
= z
[i
])!=0; i
++){
1799 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
1800 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
1801 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
1806 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
1808 if( strlen30(z
)>=79 ){
1809 for(i
=j
=0; (c
= z
[i
])!=0; i
++){ /* Copy changes from z[i] back to z[j] */
1812 }else if( c
=='"' || c
=='\'' || c
=='`' ){
1816 }else if( c
=='-' && z
[i
+1]=='-' ){
1822 if( nLine
>0 && nParen
==0 && j
>0 ){
1823 printSchemaLineN(p
->out
, z
, j
, "\n");
1828 if( nParen
==1 && cEnd
==0
1829 && (c
=='(' || c
=='\n' || (c
==',' && !wsToEol(z
+i
+1)))
1832 printSchemaLineN(p
->out
, z
, j
, "\n ");
1835 while( IsSpace(z
[i
+1]) ){ i
++; }
1840 printSchemaLine(p
->out
, z
, ";\n");
1845 if( p
->cnt
++==0 && p
->showHeader
){
1846 for(i
=0; i
<nArg
; i
++){
1847 utf8_printf(p
->out
,"%s%s",azCol
[i
],
1848 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
1851 if( azArg
==0 ) break;
1852 for(i
=0; i
<nArg
; i
++){
1854 if( z
==0 ) z
= p
->nullValue
;
1855 utf8_printf(p
->out
, "%s", z
);
1857 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1859 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1865 if( p
->cnt
++==0 && p
->showHeader
){
1866 raw_printf(p
->out
,"<TR>");
1867 for(i
=0; i
<nArg
; i
++){
1868 raw_printf(p
->out
,"<TH>");
1869 output_html_string(p
->out
, azCol
[i
]);
1870 raw_printf(p
->out
,"</TH>\n");
1872 raw_printf(p
->out
,"</TR>\n");
1874 if( azArg
==0 ) break;
1875 raw_printf(p
->out
,"<TR>");
1876 for(i
=0; i
<nArg
; i
++){
1877 raw_printf(p
->out
,"<TD>");
1878 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1879 raw_printf(p
->out
,"</TD>\n");
1881 raw_printf(p
->out
,"</TR>\n");
1885 if( p
->cnt
++==0 && p
->showHeader
){
1886 for(i
=0; i
<nArg
; i
++){
1887 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
1888 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1890 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1892 if( azArg
==0 ) break;
1893 for(i
=0; i
<nArg
; i
++){
1894 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1895 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1897 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1901 setBinaryMode(p
->out
, 1);
1902 if( p
->cnt
++==0 && p
->showHeader
){
1903 for(i
=0; i
<nArg
; i
++){
1904 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
1906 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1909 for(i
=0; i
<nArg
; i
++){
1910 output_csv(p
, azArg
[i
], i
<nArg
-1);
1912 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1914 setTextMode(p
->out
, 1);
1918 if( azArg
==0 ) break;
1919 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
1920 if( p
->showHeader
){
1921 raw_printf(p
->out
,"(");
1922 for(i
=0; i
<nArg
; i
++){
1923 if( i
>0 ) raw_printf(p
->out
, ",");
1924 if( quoteChar(azCol
[i
]) ){
1925 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
1926 utf8_printf(p
->out
, "%s", z
);
1929 raw_printf(p
->out
, "%s", azCol
[i
]);
1932 raw_printf(p
->out
,")");
1935 for(i
=0; i
<nArg
; i
++){
1936 raw_printf(p
->out
, i
>0 ? "," : " VALUES(");
1937 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
1938 utf8_printf(p
->out
,"NULL");
1939 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
1940 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
1941 output_quoted_string(p
->out
, azArg
[i
]);
1943 output_quoted_escaped_string(p
->out
, azArg
[i
]);
1945 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
1946 utf8_printf(p
->out
,"%s", azArg
[i
]);
1947 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
1949 double r
= sqlite3_column_double(p
->pStmt
, i
);
1950 sqlite3_snprintf(50,z
,"%!.20g", r
);
1951 raw_printf(p
->out
, "%s", z
);
1952 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
1953 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
1954 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
1955 output_hex_blob(p
->out
, pBlob
, nBlob
);
1956 }else if( isNumber(azArg
[i
], 0) ){
1957 utf8_printf(p
->out
,"%s", azArg
[i
]);
1958 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
1959 output_quoted_string(p
->out
, azArg
[i
]);
1961 output_quoted_escaped_string(p
->out
, azArg
[i
]);
1964 raw_printf(p
->out
,");\n");
1968 if( azArg
==0 ) break;
1969 if( p
->cnt
==0 && p
->showHeader
){
1970 for(i
=0; i
<nArg
; i
++){
1971 if( i
>0 ) raw_printf(p
->out
, ",");
1972 output_quoted_string(p
->out
, azCol
[i
]);
1974 raw_printf(p
->out
,"\n");
1977 for(i
=0; i
<nArg
; i
++){
1978 if( i
>0 ) raw_printf(p
->out
, ",");
1979 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
1980 utf8_printf(p
->out
,"NULL");
1981 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
1982 output_quoted_string(p
->out
, azArg
[i
]);
1983 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
1984 utf8_printf(p
->out
,"%s", azArg
[i
]);
1985 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
1987 double r
= sqlite3_column_double(p
->pStmt
, i
);
1988 sqlite3_snprintf(50,z
,"%!.20g", r
);
1989 raw_printf(p
->out
, "%s", z
);
1990 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
1991 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
1992 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
1993 output_hex_blob(p
->out
, pBlob
, nBlob
);
1994 }else if( isNumber(azArg
[i
], 0) ){
1995 utf8_printf(p
->out
,"%s", azArg
[i
]);
1997 output_quoted_string(p
->out
, azArg
[i
]);
2000 raw_printf(p
->out
,"\n");
2004 if( p
->cnt
++==0 && p
->showHeader
){
2005 for(i
=0; i
<nArg
; i
++){
2006 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2007 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
2009 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2011 if( azArg
==0 ) break;
2012 for(i
=0; i
<nArg
; i
++){
2013 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2014 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2016 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2024 ** This is the callback routine that the SQLite library
2025 ** invokes for each row of a query result.
2027 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
2028 /* since we don't have type info, call the shell_callback with a NULL value */
2029 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
2033 ** This is the callback routine from sqlite3_exec() that appends all
2034 ** output onto the end of a ShellText object.
2036 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
2037 ShellText
*p
= (ShellText
*)pArg
;
2039 UNUSED_PARAMETER(az
);
2040 if( azArg
==0 ) return 0;
2041 if( p
->n
) appendText(p
, "|", 0);
2042 for(i
=0; i
<nArg
; i
++){
2043 if( i
) appendText(p
, ",", 0);
2044 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
2050 ** Generate an appropriate SELFTEST table in the main database.
2052 static void createSelftestTable(ShellState
*p
){
2055 "SAVEPOINT selftest_init;\n"
2056 "CREATE TABLE IF NOT EXISTS selftest(\n"
2057 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2058 " op TEXT,\n" /* Operator: memo run */
2059 " cmd TEXT,\n" /* Command text */
2060 " ans TEXT\n" /* Desired answer */
2062 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2063 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2064 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2065 " 'memo','Tests generated by --init');\n"
2066 "INSERT INTO [_shell$self]\n"
2068 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2069 "FROM sqlite_master ORDER BY 2'',224))',\n"
2070 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2071 "FROM sqlite_master ORDER BY 2',224));\n"
2072 "INSERT INTO [_shell$self]\n"
2074 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2075 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2076 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2078 " SELECT name FROM sqlite_master\n"
2079 " WHERE type='table'\n"
2080 " AND name<>'selftest'\n"
2081 " AND coalesce(rootpage,0)>0\n"
2084 "INSERT INTO [_shell$self]\n"
2085 " VALUES('run','PRAGMA integrity_check','ok');\n"
2086 "INSERT INTO selftest(tno,op,cmd,ans)"
2087 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2088 "DROP TABLE [_shell$self];"
2091 utf8_printf(stderr
, "SELFTEST initialization failure: %s\n", zErrMsg
);
2092 sqlite3_free(zErrMsg
);
2094 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
2099 ** Set the destination table field of the ShellState structure to
2100 ** the name of the table given. Escape any quote characters in the
2103 static void set_table_name(ShellState
*p
, const char *zName
){
2108 if( p
->zDestTable
){
2109 free(p
->zDestTable
);
2112 if( zName
==0 ) return;
2113 cQuote
= quoteChar(zName
);
2114 n
= strlen30(zName
);
2115 if( cQuote
) n
+= n
+2;
2116 z
= p
->zDestTable
= malloc( n
+1 );
2118 raw_printf(stderr
,"Error: out of memory\n");
2122 if( cQuote
) z
[n
++] = cQuote
;
2123 for(i
=0; zName
[i
]; i
++){
2125 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
2127 if( cQuote
) z
[n
++] = cQuote
;
2133 ** Execute a query statement that will generate SQL output. Print
2134 ** the result columns, comma-separated, on a line and then add a
2135 ** semicolon terminator to the end of that line.
2137 ** If the number of columns is 1 and that column contains text "--"
2138 ** then write the semicolon on a separate line. That way, if a
2139 ** "--" comment occurs at the end of the statement, the comment
2140 ** won't consume the semicolon terminator.
2142 static int run_table_dump_query(
2143 ShellState
*p
, /* Query context */
2144 const char *zSelect
, /* SELECT statement to extract content */
2145 const char *zFirstRow
/* Print before first row, if not NULL */
2147 sqlite3_stmt
*pSelect
;
2152 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
2153 if( rc
!=SQLITE_OK
|| !pSelect
){
2154 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2155 sqlite3_errmsg(p
->db
));
2156 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2159 rc
= sqlite3_step(pSelect
);
2160 nResult
= sqlite3_column_count(pSelect
);
2161 while( rc
==SQLITE_ROW
){
2163 utf8_printf(p
->out
, "%s", zFirstRow
);
2166 z
= (const char*)sqlite3_column_text(pSelect
, 0);
2167 utf8_printf(p
->out
, "%s", z
);
2168 for(i
=1; i
<nResult
; i
++){
2169 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
2172 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
2174 raw_printf(p
->out
, "\n;\n");
2176 raw_printf(p
->out
, ";\n");
2178 rc
= sqlite3_step(pSelect
);
2180 rc
= sqlite3_finalize(pSelect
);
2181 if( rc
!=SQLITE_OK
){
2182 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2183 sqlite3_errmsg(p
->db
));
2184 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2190 ** Allocate space and save off current error string.
2192 static char *save_err_msg(
2193 sqlite3
*db
/* Database to query */
2195 int nErrMsg
= 1+strlen30(sqlite3_errmsg(db
));
2196 char *zErrMsg
= sqlite3_malloc64(nErrMsg
);
2198 memcpy(zErrMsg
, sqlite3_errmsg(db
), nErrMsg
);
2205 ** Attempt to display I/O stats on Linux using /proc/PID/io
2207 static void displayLinuxIoStats(FILE *out
){
2210 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
2211 in
= fopen(z
, "rb");
2213 while( fgets(z
, sizeof(z
), in
)!=0 ){
2214 static const struct {
2215 const char *zPattern
;
2218 { "rchar: ", "Bytes received by read():" },
2219 { "wchar: ", "Bytes sent to write():" },
2220 { "syscr: ", "Read() system calls:" },
2221 { "syscw: ", "Write() system calls:" },
2222 { "read_bytes: ", "Bytes read from storage:" },
2223 { "write_bytes: ", "Bytes written to storage:" },
2224 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2227 for(i
=0; i
<ArraySize(aTrans
); i
++){
2228 int n
= strlen30(aTrans
[i
].zPattern
);
2229 if( strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
2230 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
2240 ** Display a single line of status using 64-bit values.
2242 static void displayStatLine(
2243 ShellState
*p
, /* The shell context */
2244 char *zLabel
, /* Label for this one line */
2245 char *zFormat
, /* Format for the result */
2246 int iStatusCtrl
, /* Which status to display */
2247 int bReset
/* True to reset the stats */
2249 sqlite3_int64 iCur
= -1;
2250 sqlite3_int64 iHiwtr
= -1;
2253 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
2254 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
2255 if( zFormat
[i
]=='%' ) nPercent
++;
2258 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
2260 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
2262 raw_printf(p
->out
, "%-36s %s\n", zLabel
, zLine
);
2266 ** Display memory stats.
2268 static int display_stats(
2269 sqlite3
*db
, /* Database to query */
2270 ShellState
*pArg
, /* Pointer to ShellState */
2271 int bReset
/* True to reset the stats */
2276 if( pArg
&& pArg
->out
){
2277 displayStatLine(pArg
, "Memory Used:",
2278 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
2279 displayStatLine(pArg
, "Number of Outstanding Allocations:",
2280 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
2281 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
2282 displayStatLine(pArg
, "Number of Pcache Pages Used:",
2283 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
2285 displayStatLine(pArg
, "Number of Pcache Overflow Bytes:",
2286 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
2287 displayStatLine(pArg
, "Largest Allocation:",
2288 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
2289 displayStatLine(pArg
, "Largest Pcache Allocation:",
2290 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
2291 #ifdef YYTRACKMAXSTACKDEPTH
2292 displayStatLine(pArg
, "Deepest Parser Stack:",
2293 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
2297 if( pArg
&& pArg
->out
&& db
){
2298 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
2300 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
2301 &iCur
, &iHiwtr
, bReset
);
2302 raw_printf(pArg
->out
,
2303 "Lookaside Slots Used: %d (max %d)\n",
2305 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
2306 &iCur
, &iHiwtr
, bReset
);
2307 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
2309 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
2310 &iCur
, &iHiwtr
, bReset
);
2311 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
2313 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
2314 &iCur
, &iHiwtr
, bReset
);
2315 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
2319 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
2320 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
2323 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
2324 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
2326 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
2327 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
2329 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
2330 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
2332 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
2333 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
2336 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
2337 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
2341 if( pArg
&& pArg
->out
&& db
&& pArg
->pStmt
){
2342 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
2344 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
2345 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
2346 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
2347 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
2348 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
2349 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
2350 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
2354 displayLinuxIoStats(pArg
->out
);
2357 /* Do not remove this machine readable comment: extra-stats-output-here */
2363 ** Display scan stats.
2365 static void display_scanstats(
2366 sqlite3
*db
, /* Database to query */
2367 ShellState
*pArg
/* Pointer to ShellState */
2369 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2370 UNUSED_PARAMETER(db
);
2371 UNUSED_PARAMETER(pArg
);
2374 raw_printf(pArg
->out
, "-------- scanstats --------\n");
2376 for(k
=0; k
<=mx
; k
++){
2377 double rEstLoop
= 1.0;
2379 sqlite3_stmt
*p
= pArg
->pStmt
;
2380 sqlite3_int64 nLoop
, nVisit
;
2383 const char *zExplain
;
2384 if( sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NLOOP
, (void*)&nLoop
) ){
2387 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_SELECTID
, (void*)&iSid
);
2388 if( iSid
>mx
) mx
= iSid
;
2389 if( iSid
!=k
) continue;
2391 rEstLoop
= (double)nLoop
;
2392 if( k
>0 ) raw_printf(pArg
->out
, "-------- subquery %d -------\n", k
);
2395 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NVISIT
, (void*)&nVisit
);
2396 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EST
, (void*)&rEst
);
2397 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EXPLAIN
, (void*)&zExplain
);
2398 utf8_printf(pArg
->out
, "Loop %2d: %s\n", n
, zExplain
);
2400 raw_printf(pArg
->out
,
2401 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2402 nLoop
, nVisit
, (sqlite3_int64
)(rEstLoop
+0.5), rEst
2406 raw_printf(pArg
->out
, "---------------------------\n");
2411 ** Parameter azArray points to a zero-terminated array of strings. zStr
2412 ** points to a single nul-terminated string. Return non-zero if zStr
2413 ** is equal, according to strcmp(), to any of the strings in the array.
2414 ** Otherwise, return zero.
2416 static int str_in_array(const char *zStr
, const char **azArray
){
2418 for(i
=0; azArray
[i
]; i
++){
2419 if( 0==strcmp(zStr
, azArray
[i
]) ) return 1;
2425 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2426 ** and populate the ShellState.aiIndent[] array with the number of
2427 ** spaces each opcode should be indented before it is output.
2429 ** The indenting rules are:
2431 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2432 ** all opcodes that occur between the p2 jump destination and the opcode
2433 ** itself by 2 spaces.
2435 ** * For each "Goto", if the jump destination is earlier in the program
2436 ** and ends on one of:
2437 ** Yield SeekGt SeekLt RowSetRead Rewind
2438 ** or if the P1 parameter is one instead of zero,
2439 ** then indent all opcodes between the earlier instruction
2440 ** and "Goto" by 2 spaces.
2442 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
2443 const char *zSql
; /* The text of the SQL statement */
2444 const char *z
; /* Used to check if this is an EXPLAIN */
2445 int *abYield
= 0; /* True if op is an OP_Yield */
2446 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
2447 int iOp
; /* Index of operation in p->aiIndent[] */
2449 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2450 "NextIfOpen", "PrevIfOpen", 0 };
2451 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2453 const char *azGoto
[] = { "Goto", 0 };
2455 /* Try to figure out if this is really an EXPLAIN statement. If this
2456 ** cannot be verified, return early. */
2457 if( sqlite3_column_count(pSql
)!=8 ){
2461 zSql
= sqlite3_sql(pSql
);
2462 if( zSql
==0 ) return;
2463 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
2464 if( sqlite3_strnicmp(z
, "explain", 7) ){
2469 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
2471 int iAddr
= sqlite3_column_int(pSql
, 0);
2472 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
2474 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2475 ** p2 is an instruction address, set variable p2op to the index of that
2476 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2477 ** the current instruction is part of a sub-program generated by an
2478 ** SQL trigger or foreign key. */
2479 int p2
= sqlite3_column_int(pSql
, 3);
2480 int p2op
= (p2
+ (iOp
-iAddr
));
2482 /* Grow the p->aiIndent array as required */
2485 /* Do further verfication that this is explain output. Abort if
2487 static const char *explainCols
[] = {
2488 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2490 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
2491 if( strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
2493 sqlite3_reset(pSql
);
2499 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
2500 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
2502 abYield
[iOp
] = str_in_array(zOp
, azYield
);
2503 p
->aiIndent
[iOp
] = 0;
2506 if( str_in_array(zOp
, azNext
) ){
2507 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2509 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
2510 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
2512 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2517 sqlite3_free(abYield
);
2518 sqlite3_reset(pSql
);
2522 ** Free the array allocated by explain_data_prepare().
2524 static void explain_data_delete(ShellState
*p
){
2525 sqlite3_free(p
->aiIndent
);
2532 ** Disable and restore .wheretrace and .selecttrace settings.
2534 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2535 extern int sqlite3SelectTrace
;
2536 static int savedSelectTrace
;
2538 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2539 extern int sqlite3WhereTrace
;
2540 static int savedWhereTrace
;
2542 static void disable_debug_trace_modes(void){
2543 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2544 savedSelectTrace
= sqlite3SelectTrace
;
2545 sqlite3SelectTrace
= 0;
2547 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2548 savedWhereTrace
= sqlite3WhereTrace
;
2549 sqlite3WhereTrace
= 0;
2552 static void restore_debug_trace_modes(void){
2553 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2554 sqlite3SelectTrace
= savedSelectTrace
;
2556 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2557 sqlite3WhereTrace
= savedWhereTrace
;
2562 ** Run a prepared statement
2564 static void exec_prepared_stmt(
2565 ShellState
*pArg
, /* Pointer to ShellState */
2566 sqlite3_stmt
*pStmt
, /* Statment to run */
2567 int (*xCallback
)(void*,int,char**,char**,int*) /* Callback function */
2571 /* perform the first step. this will tell us if we
2572 ** have a result set or not and how wide it is.
2574 rc
= sqlite3_step(pStmt
);
2575 /* if we have a result set... */
2576 if( SQLITE_ROW
== rc
){
2577 /* if we have a callback... */
2579 /* allocate space for col name ptr, value ptr, and type */
2580 int nCol
= sqlite3_column_count(pStmt
);
2581 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
2585 char **azCols
= (char **)pData
; /* Names of result columns */
2586 char **azVals
= &azCols
[nCol
]; /* Results */
2587 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
2589 assert(sizeof(int) <= sizeof(char *));
2590 /* save off ptrs to column names */
2591 for(i
=0; i
<nCol
; i
++){
2592 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
2595 /* extract the data and data types */
2596 for(i
=0; i
<nCol
; i
++){
2597 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
2598 if( x
==SQLITE_BLOB
&& pArg
&& pArg
->cMode
==MODE_Insert
){
2601 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
2603 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
2605 break; /* from for */
2609 /* if data and types extracted successfully... */
2610 if( SQLITE_ROW
== rc
){
2611 /* call the supplied callback with the result row data */
2612 if( xCallback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
2615 rc
= sqlite3_step(pStmt
);
2618 } while( SQLITE_ROW
== rc
);
2619 sqlite3_free(pData
);
2623 rc
= sqlite3_step(pStmt
);
2624 } while( rc
== SQLITE_ROW
);
2629 #ifndef SQLITE_OMIT_VIRTUALTABLE
2631 ** This function is called to process SQL if the previous shell command
2632 ** was ".expert". It passes the SQL in the second argument directly to
2633 ** the sqlite3expert object.
2635 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2636 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2637 ** an English language error message. It is the responsibility of the
2638 ** caller to eventually free this buffer using sqlite3_free().
2640 static int expertHandleSQL(
2645 assert( pState
->expert
.pExpert
);
2646 assert( pzErr
==0 || *pzErr
==0 );
2647 return sqlite3_expert_sql(pState
->expert
.pExpert
, zSql
, pzErr
);
2651 ** This function is called either to silently clean up the object
2652 ** created by the ".expert" command (if bCancel==1), or to generate a
2653 ** report from it and then clean it up (if bCancel==0).
2655 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2656 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2657 ** an English language error message. It is the responsibility of the
2658 ** caller to eventually free this buffer using sqlite3_free().
2660 static int expertFinish(
2666 sqlite3expert
*p
= pState
->expert
.pExpert
;
2668 assert( bCancel
|| pzErr
==0 || *pzErr
==0 );
2670 FILE *out
= pState
->out
;
2671 int bVerbose
= pState
->expert
.bVerbose
;
2673 rc
= sqlite3_expert_analyze(p
, pzErr
);
2674 if( rc
==SQLITE_OK
){
2675 int nQuery
= sqlite3_expert_count(p
);
2679 const char *zCand
= sqlite3_expert_report(p
,0,EXPERT_REPORT_CANDIDATES
);
2680 raw_printf(out
, "-- Candidates -----------------------------\n");
2681 raw_printf(out
, "%s\n", zCand
);
2683 for(i
=0; i
<nQuery
; i
++){
2684 const char *zSql
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_SQL
);
2685 const char *zIdx
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_INDEXES
);
2686 const char *zEQP
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_PLAN
);
2687 if( zIdx
==0 ) zIdx
= "(no new indexes)\n";
2689 raw_printf(out
, "-- Query %d --------------------------------\n",i
+1);
2690 raw_printf(out
, "%s\n\n", zSql
);
2692 raw_printf(out
, "%s\n", zIdx
);
2693 raw_printf(out
, "%s\n", zEQP
);
2697 sqlite3_expert_destroy(p
);
2698 pState
->expert
.pExpert
= 0;
2703 ** Implementation of ".expert" dot command.
2705 static int expertDotCommand(
2706 ShellState
*pState
, /* Current shell tool state */
2707 char **azArg
, /* Array of arguments passed to dot command */
2708 int nArg
/* Number of entries in azArg[] */
2715 assert( pState
->expert
.pExpert
==0 );
2716 memset(&pState
->expert
, 0, sizeof(ExpertInfo
));
2718 for(i
=1; rc
==SQLITE_OK
&& i
<nArg
; i
++){
2721 if( z
[0]=='-' && z
[1]=='-' ) z
++;
2723 if( n
>=2 && 0==strncmp(z
, "-verbose", n
) ){
2724 pState
->expert
.bVerbose
= 1;
2726 else if( n
>=2 && 0==strncmp(z
, "-sample", n
) ){
2728 raw_printf(stderr
, "option requires an argument: %s\n", z
);
2731 iSample
= (int)integerValue(azArg
[++i
]);
2732 if( iSample
<0 || iSample
>100 ){
2733 raw_printf(stderr
, "value out of range: %s\n", azArg
[i
]);
2739 raw_printf(stderr
, "unknown option: %s\n", z
);
2744 if( rc
==SQLITE_OK
){
2745 pState
->expert
.pExpert
= sqlite3_expert_new(pState
->db
, &zErr
);
2746 if( pState
->expert
.pExpert
==0 ){
2747 raw_printf(stderr
, "sqlite3_expert_new: %s\n", zErr
);
2750 sqlite3_expert_config(
2751 pState
->expert
.pExpert
, EXPERT_CONFIG_SAMPLE
, iSample
2758 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2761 ** Execute a statement or set of statements. Print
2762 ** any result rows/columns depending on the current mode
2763 ** set via the supplied callback.
2765 ** This is very similar to SQLite's built-in sqlite3_exec()
2766 ** function except it takes a slightly different callback
2767 ** and callback data argument.
2769 static int shell_exec(
2770 sqlite3
*db
, /* An open database */
2771 const char *zSql
, /* SQL to be evaluated */
2772 int (*xCallback
)(void*,int,char**,char**,int*), /* Callback function */
2773 /* (not the same as sqlite3_exec) */
2774 ShellState
*pArg
, /* Pointer to ShellState */
2775 char **pzErrMsg
/* Error msg written here */
2777 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
2778 int rc
= SQLITE_OK
; /* Return Code */
2780 const char *zLeftover
; /* Tail of unprocessed SQL */
2786 #ifndef SQLITE_OMIT_VIRTUALTABLE
2787 if( pArg
->expert
.pExpert
){
2788 rc
= expertHandleSQL(pArg
, zSql
, pzErrMsg
);
2789 return expertFinish(pArg
, (rc
!=SQLITE_OK
), pzErrMsg
);
2793 while( zSql
[0] && (SQLITE_OK
== rc
) ){
2794 static const char *zStmtSql
;
2795 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
2796 if( SQLITE_OK
!= rc
){
2798 *pzErrMsg
= save_err_msg(db
);
2802 /* this happens for a comment or white-space */
2804 while( IsSpace(zSql
[0]) ) zSql
++;
2807 zStmtSql
= sqlite3_sql(pStmt
);
2808 if( zStmtSql
==0 ) zStmtSql
= "";
2809 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
2811 /* save off the prepared statment handle and reset row count */
2813 pArg
->pStmt
= pStmt
;
2817 /* echo the sql statement if echo on */
2818 if( pArg
&& ShellHasFlag(pArg
, SHFLG_Echo
) ){
2819 utf8_printf(pArg
->out
, "%s\n", zStmtSql
? zStmtSql
: zSql
);
2822 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2823 if( pArg
&& pArg
->autoEQP
&& sqlite3_strlike("EXPLAIN%",zStmtSql
,0)!=0 ){
2824 sqlite3_stmt
*pExplain
;
2827 disable_debug_trace_modes();
2828 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, -1, &triggerEQP
);
2829 if( pArg
->autoEQP
>=AUTOEQP_trigger
){
2830 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 1, 0);
2832 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
2833 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2834 if( rc
==SQLITE_OK
){
2835 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
2836 raw_printf(pArg
->out
,"--EQP-- %d,",sqlite3_column_int(pExplain
, 0));
2837 raw_printf(pArg
->out
,"%d,", sqlite3_column_int(pExplain
, 1));
2838 raw_printf(pArg
->out
,"%d,", sqlite3_column_int(pExplain
, 2));
2839 utf8_printf(pArg
->out
,"%s\n", sqlite3_column_text(pExplain
, 3));
2842 sqlite3_finalize(pExplain
);
2844 if( pArg
->autoEQP
>=AUTOEQP_full
){
2845 /* Also do an EXPLAIN for ".eqp full" mode */
2846 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
2847 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2848 if( rc
==SQLITE_OK
){
2849 pArg
->cMode
= MODE_Explain
;
2850 explain_data_prepare(pArg
, pExplain
);
2851 exec_prepared_stmt(pArg
, pExplain
, xCallback
);
2852 explain_data_delete(pArg
);
2854 sqlite3_finalize(pExplain
);
2857 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, triggerEQP
, 0);
2858 restore_debug_trace_modes();
2862 pArg
->cMode
= pArg
->mode
;
2863 if( pArg
->autoExplain
2864 && sqlite3_column_count(pStmt
)==8
2865 && sqlite3_strlike("EXPLAIN%", zStmtSql
,0)==0
2867 pArg
->cMode
= MODE_Explain
;
2870 /* If the shell is currently in ".explain" mode, gather the extra
2871 ** data required to add indents to the output.*/
2872 if( pArg
->cMode
==MODE_Explain
){
2873 explain_data_prepare(pArg
, pStmt
);
2877 exec_prepared_stmt(pArg
, pStmt
, xCallback
);
2878 explain_data_delete(pArg
);
2880 /* print usage stats if stats on */
2881 if( pArg
&& pArg
->statsOn
){
2882 display_stats(db
, pArg
, 0);
2885 /* print loop-counters if required */
2886 if( pArg
&& pArg
->scanstatsOn
){
2887 display_scanstats(db
, pArg
);
2890 /* Finalize the statement just executed. If this fails, save a
2891 ** copy of the error message. Otherwise, set zSql to point to the
2892 ** next statement to execute. */
2893 rc2
= sqlite3_finalize(pStmt
);
2894 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
2895 if( rc
==SQLITE_OK
){
2897 while( IsSpace(zSql
[0]) ) zSql
++;
2898 }else if( pzErrMsg
){
2899 *pzErrMsg
= save_err_msg(db
);
2902 /* clear saved stmt handle */
2913 ** Release memory previously allocated by tableColumnList().
2915 static void freeColumnList(char **azCol
){
2917 for(i
=1; azCol
[i
]; i
++){
2918 sqlite3_free(azCol
[i
]);
2920 /* azCol[0] is a static string */
2921 sqlite3_free(azCol
);
2925 ** Return a list of pointers to strings which are the names of all
2926 ** columns in table zTab. The memory to hold the names is dynamically
2927 ** allocated and must be released by the caller using a subsequent call
2928 ** to freeColumnList().
2930 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2931 ** value that needs to be preserved, then azCol[0] is filled in with the
2932 ** name of the rowid column.
2934 ** The first regular column in the table is azCol[1]. The list is terminated
2935 ** by an entry with azCol[i]==0.
2937 static char **tableColumnList(ShellState
*p
, const char *zTab
){
2939 sqlite3_stmt
*pStmt
;
2943 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
2944 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
2945 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
2948 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
2949 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
2952 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
2953 if( nCol
>=nAlloc
-2 ){
2954 nAlloc
= nAlloc
*2 + nCol
+ 10;
2955 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
2957 raw_printf(stderr
, "Error: out of memory\n");
2961 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
2962 if( sqlite3_column_int(pStmt
, 5) ){
2965 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
2974 sqlite3_finalize(pStmt
);
2975 if( azCol
==0 ) return 0;
2979 /* The decision of whether or not a rowid really needs to be preserved
2980 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2981 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2982 ** rowids on tables where the rowid is inaccessible because there are other
2983 ** columns in the table named "rowid", "_rowid_", and "oid".
2985 if( preserveRowid
&& isIPK
){
2986 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2987 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2988 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2989 ** ROWID aliases. To distinguish these cases, check to see if
2990 ** there is a "pk" entry in "PRAGMA index_list". There will be
2991 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2993 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2994 " WHERE origin='pk'", zTab
);
2995 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
2998 freeColumnList(azCol
);
3001 rc
= sqlite3_step(pStmt
);
3002 sqlite3_finalize(pStmt
);
3003 preserveRowid
= rc
==SQLITE_ROW
;
3005 if( preserveRowid
){
3006 /* Only preserve the rowid if we can find a name to use for the
3008 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
3011 for(i
=1; i
<=nCol
; i
++){
3012 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
3015 /* At this point, we know that azRowid[j] is not the name of any
3016 ** ordinary column in the table. Verify that azRowid[j] is a valid
3017 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3018 ** tables will fail this last check */
3019 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
3020 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
3029 ** Toggle the reverse_unordered_selects setting.
3031 static void toggleSelectOrder(sqlite3
*db
){
3032 sqlite3_stmt
*pStmt
= 0;
3035 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
3036 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
3037 iSetting
= sqlite3_column_int(pStmt
, 0);
3039 sqlite3_finalize(pStmt
);
3040 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
3041 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
3042 sqlite3_exec(db
, zStmt
, 0, 0, 0);
3046 ** This is a different callback routine used for dumping the database.
3047 ** Each row received by this callback consists of a table name,
3048 ** the table type ("index" or "table") and SQL to create the table.
3049 ** This routine should print text sufficient to recreate the table.
3051 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
3056 ShellState
*p
= (ShellState
*)pArg
;
3058 UNUSED_PARAMETER(azNotUsed
);
3059 if( nArg
!=3 || azArg
==0 ) return 0;
3064 if( strcmp(zTable
, "sqlite_sequence")==0 ){
3065 raw_printf(p
->out
, "DELETE FROM sqlite_sequence;\n");
3066 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 ){
3067 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
3068 }else if( strncmp(zTable
, "sqlite_", 7)==0 ){
3070 }else if( strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
3072 if( !p
->writableSchema
){
3073 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
3074 p
->writableSchema
= 1;
3076 zIns
= sqlite3_mprintf(
3077 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3078 "VALUES('table','%q','%q',0,'%q');",
3079 zTable
, zTable
, zSql
);
3080 utf8_printf(p
->out
, "%s\n", zIns
);
3084 printSchemaLine(p
->out
, zSql
, ";\n");
3087 if( strcmp(zType
, "table")==0 ){
3092 char *savedDestTable
;
3095 azCol
= tableColumnList(p
, zTable
);
3101 /* Always quote the table name, even if it appears to be pure ascii,
3102 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3104 appendText(&sTable
, zTable
, quoteChar(zTable
));
3105 /* If preserving the rowid, add a column list after the table name.
3106 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3107 ** instead of the usual "INSERT INTO tab VALUES(...)".
3110 appendText(&sTable
, "(", 0);
3111 appendText(&sTable
, azCol
[0], 0);
3112 for(i
=1; azCol
[i
]; i
++){
3113 appendText(&sTable
, ",", 0);
3114 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
3116 appendText(&sTable
, ")", 0);
3119 /* Build an appropriate SELECT statement */
3121 appendText(&sSelect
, "SELECT ", 0);
3123 appendText(&sSelect
, azCol
[0], 0);
3124 appendText(&sSelect
, ",", 0);
3126 for(i
=1; azCol
[i
]; i
++){
3127 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
3129 appendText(&sSelect
, ",", 0);
3132 freeColumnList(azCol
);
3133 appendText(&sSelect
, " FROM ", 0);
3134 appendText(&sSelect
, zTable
, quoteChar(zTable
));
3136 savedDestTable
= p
->zDestTable
;
3137 savedMode
= p
->mode
;
3138 p
->zDestTable
= sTable
.z
;
3139 p
->mode
= p
->cMode
= MODE_Insert
;
3140 rc
= shell_exec(p
->db
, sSelect
.z
, shell_callback
, p
, 0);
3141 if( (rc
&0xff)==SQLITE_CORRUPT
){
3142 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
3143 toggleSelectOrder(p
->db
);
3144 shell_exec(p
->db
, sSelect
.z
, shell_callback
, p
, 0);
3145 toggleSelectOrder(p
->db
);
3147 p
->zDestTable
= savedDestTable
;
3148 p
->mode
= savedMode
;
3157 ** Run zQuery. Use dump_callback() as the callback routine so that
3158 ** the contents of the query are output as SQL statements.
3160 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3161 ** "ORDER BY rowid DESC" to the end.
3163 static int run_schema_dump_query(
3169 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
3170 if( rc
==SQLITE_CORRUPT
){
3172 int len
= strlen30(zQuery
);
3173 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
3175 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
3179 zQ2
= malloc( len
+100 );
3180 if( zQ2
==0 ) return rc
;
3181 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
3182 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
3184 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
3186 rc
= SQLITE_CORRUPT
;
3195 ** Text of a help message
3197 static char zHelp
[] =
3198 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3199 ".archive ... Manage SQL archives: \".archive --help\" for details\n"
3201 #ifndef SQLITE_OMIT_AUTHORIZATION
3202 ".auth ON|OFF Show authorizer callbacks\n"
3204 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
3205 ".bail on|off Stop after hitting an error. Default OFF\n"
3206 ".binary on|off Turn binary output on or off. Default OFF\n"
3207 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
3208 ".changes on|off Show number of rows changed by SQL\n"
3209 ".check GLOB Fail if output since .testcase does not match\n"
3210 ".clone NEWDB Clone data into NEWDB from the existing database\n"
3211 ".databases List names and files of attached databases\n"
3212 ".dbinfo ?DB? Show status information about the database\n"
3213 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
3214 " If TABLE specified, only dump tables matching\n"
3215 " LIKE pattern TABLE.\n"
3216 ".echo on|off Turn command echo on or off\n"
3217 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
3218 ".excel Display the output of next command in a spreadsheet\n"
3219 ".exit Exit this program\n"
3220 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
3221 /* Because explain mode comes on automatically now, the ".explain" mode
3222 ** is removed from the help screen. It is still supported for legacy, however */
3223 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
3224 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3225 ".headers on|off Turn display of headers on or off\n"
3226 ".help Show this message\n"
3227 ".import FILE TABLE Import data from FILE into TABLE\n"
3228 #ifndef SQLITE_OMIT_TEST_CONTROL
3229 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3231 ".indexes ?TABLE? Show names of all indexes\n"
3232 " If TABLE specified, only show indexes for tables\n"
3233 " matching LIKE pattern TABLE.\n"
3234 #ifdef SQLITE_ENABLE_IOTRACE
3235 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3237 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
3238 ".lint OPTIONS Report potential schema issues. Options:\n"
3239 " fkey-indexes Find missing foreign key indexes\n"
3240 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3241 ".load FILE ?ENTRY? Load an extension library\n"
3243 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
3244 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
3245 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
3246 " csv Comma-separated values\n"
3247 " column Left-aligned columns. (See .width)\n"
3248 " html HTML <table> code\n"
3249 " insert SQL insert statements for TABLE\n"
3250 " line One value per line\n"
3251 " list Values delimited by \"|\"\n"
3252 " quote Escape answers as for SQL\n"
3253 " tabs Tab-separated values\n"
3254 " tcl TCL list elements\n"
3255 ".nullvalue STRING Use STRING in place of NULL values\n"
3256 ".once (-e|-x|FILE) Output for the next SQL command only to FILE\n"
3257 " or invoke system text editor (-e) or spreadsheet (-x)\n"
3259 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3260 " The --new option starts with an empty file\n"
3261 ".output ?FILE? Send output to FILE or stdout\n"
3262 ".print STRING... Print literal STRING\n"
3263 ".prompt MAIN CONTINUE Replace the standard prompts\n"
3264 ".quit Exit this program\n"
3265 ".read FILENAME Execute SQL in FILENAME\n"
3266 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
3267 ".save FILE Write in-memory database into FILE\n"
3268 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3269 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3270 " Add --indent for pretty-printing\n"
3271 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
3272 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3273 " separator for both the output mode and .import\n"
3274 #if defined(SQLITE_ENABLE_SESSION)
3275 ".session CMD ... Create or control sessions\n"
3277 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
3278 #ifndef SQLITE_NOHAVE_SYSTEM
3279 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
3281 ".show Show the current values for various settings\n"
3282 ".stats ?on|off? Show stats or turn stats on or off\n"
3283 #ifndef SQLITE_NOHAVE_SYSTEM
3284 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
3286 ".tables ?TABLE? List names of tables\n"
3287 " If TABLE specified, only list tables matching\n"
3288 " LIKE pattern TABLE.\n"
3289 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
3290 ".timeout MS Try opening locked tables for MS milliseconds\n"
3291 ".timer on|off Turn SQL timer on or off\n"
3292 ".trace FILE|off Output each SQL statement as it is run\n"
3293 ".vfsinfo ?AUX? Information about the top-level VFS\n"
3294 ".vfslist List all available VFSes\n"
3295 ".vfsname ?AUX? Print the name of the VFS stack\n"
3296 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
3297 " Negative values right-justify\n"
3300 #if defined(SQLITE_ENABLE_SESSION)
3302 ** Print help information for the ".sessions" command
3304 void session_help(ShellState
*p
){
3306 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3307 "If ?NAME? is omitted, the first defined session is used.\n"
3309 " attach TABLE Attach TABLE\n"
3310 " changeset FILE Write a changeset into FILE\n"
3311 " close Close one session\n"
3312 " enable ?BOOLEAN? Set or query the enable bit\n"
3313 " filter GLOB... Reject tables matching GLOBs\n"
3314 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3315 " isempty Query whether the session is empty\n"
3316 " list List currently open session names\n"
3317 " open DB NAME Open a new session on DB\n"
3318 " patchset FILE Write a patchset into FILE\n"
3324 /* Forward reference */
3325 static int process_input(ShellState
*p
, FILE *in
);
3328 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
3329 ** and return a pointer to the buffer. The caller is responsible for freeing
3332 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3335 ** For convenience, a nul-terminator byte is always appended to the data read
3336 ** from the file before the buffer is returned. This byte is not included in
3337 ** the final value of (*pnByte), if applicable.
3339 ** NULL is returned if any error is encountered. The final value of *pnByte
3340 ** is undefined in this case.
3342 static char *readFile(const char *zName
, int *pnByte
){
3343 FILE *in
= fopen(zName
, "rb");
3347 if( in
==0 ) return 0;
3348 fseek(in
, 0, SEEK_END
);
3351 pBuf
= sqlite3_malloc64( nIn
+1 );
3352 if( pBuf
==0 ) return 0;
3353 nRead
= fread(pBuf
, nIn
, 1, in
);
3360 if( pnByte
) *pnByte
= nIn
;
3364 #if defined(SQLITE_ENABLE_SESSION)
3366 ** Close a single OpenSession object and release all of its associated
3369 static void session_close(OpenSession
*pSession
){
3371 sqlite3session_delete(pSession
->p
);
3372 sqlite3_free(pSession
->zName
);
3373 for(i
=0; i
<pSession
->nFilter
; i
++){
3374 sqlite3_free(pSession
->azFilter
[i
]);
3376 sqlite3_free(pSession
->azFilter
);
3377 memset(pSession
, 0, sizeof(OpenSession
));
3382 ** Close all OpenSession objects and release all associated resources.
3384 #if defined(SQLITE_ENABLE_SESSION)
3385 static void session_close_all(ShellState
*p
){
3387 for(i
=0; i
<p
->nSession
; i
++){
3388 session_close(&p
->aSession
[i
]);
3393 # define session_close_all(X)
3397 ** Implementation of the xFilter function for an open session. Omit
3398 ** any tables named by ".session filter" but let all other table through.
3400 #if defined(SQLITE_ENABLE_SESSION)
3401 static int session_filter(void *pCtx
, const char *zTab
){
3402 OpenSession
*pSession
= (OpenSession
*)pCtx
;
3404 for(i
=0; i
<pSession
->nFilter
; i
++){
3405 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
3412 ** Try to deduce the type of file for zName based on its content. Return
3413 ** one of the SHELL_OPEN_* constants.
3415 static int deduceDatabaseType(const char *zName
){
3416 FILE *f
= fopen(zName
, "rb");
3418 int rc
= SHELL_OPEN_UNSPEC
;
3420 if( f
==0 ) return SHELL_OPEN_NORMAL
;
3421 fseek(f
, -25, SEEK_END
);
3422 n
= fread(zBuf
, 25, 1, f
);
3423 if( n
==1 && memcmp(zBuf
, "Start-Of-SQLite3-", 17)==0 ){
3424 rc
= SHELL_OPEN_APPENDVFS
;
3426 fseek(f
, -22, SEEK_END
);
3427 n
= fread(zBuf
, 22, 1, f
);
3428 if( n
==1 && zBuf
[0]==0x50 && zBuf
[1]==0x4b && zBuf
[2]==0x05
3430 rc
= SHELL_OPEN_ZIPFILE
;
3438 ** Make sure the database is open. If it is not, then open it. If
3439 ** the database fails to open, print an error message and exit.
3441 static void open_db(ShellState
*p
, int keepAlive
){
3443 sqlite3_initialize();
3444 if( p
->openMode
==SHELL_OPEN_UNSPEC
&& access(p
->zDbFilename
,0)==0 ){
3445 p
->openMode
= (u8
)deduceDatabaseType(p
->zDbFilename
);
3447 switch( p
->openMode
){
3448 case SHELL_OPEN_APPENDVFS
: {
3449 sqlite3_open_v2(p
->zDbFilename
, &p
->db
,
3450 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, "apndvfs");
3453 case SHELL_OPEN_ZIPFILE
: {
3454 sqlite3_open(":memory:", &p
->db
);
3457 case SHELL_OPEN_UNSPEC
:
3458 case SHELL_OPEN_NORMAL
: {
3459 sqlite3_open(p
->zDbFilename
, &p
->db
);
3464 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3465 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
3466 p
->zDbFilename
, sqlite3_errmsg(p
->db
));
3467 if( keepAlive
) return;
3470 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3471 sqlite3_enable_load_extension(p
->db
, 1);
3473 sqlite3_fileio_init(p
->db
, 0, 0);
3474 sqlite3_shathree_init(p
->db
, 0, 0);
3475 sqlite3_completion_init(p
->db
, 0, 0);
3476 #ifdef SQLITE_HAVE_ZLIB
3477 sqlite3_zipfile_init(p
->db
, 0, 0);
3478 sqlite3_sqlar_init(p
->db
, 0, 0);
3480 sqlite3_create_function(p
->db
, "shell_add_schema", 3, SQLITE_UTF8
, 0,
3481 shellAddSchemaName
, 0, 0);
3482 sqlite3_create_function(p
->db
, "shell_module_schema", 1, SQLITE_UTF8
, 0,
3483 shellModuleSchema
, 0, 0);
3484 sqlite3_create_function(p
->db
, "shell_putsnl", 1, SQLITE_UTF8
, p
,
3485 shellPutsFunc
, 0, 0);
3486 #ifndef SQLITE_NOHAVE_SYSTEM
3487 sqlite3_create_function(p
->db
, "edit", 1, SQLITE_UTF8
, 0,
3489 sqlite3_create_function(p
->db
, "edit", 2, SQLITE_UTF8
, 0,
3492 if( p
->openMode
==SHELL_OPEN_ZIPFILE
){
3493 char *zSql
= sqlite3_mprintf(
3494 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p
->zDbFilename
);
3495 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
3501 #if HAVE_READLINE || HAVE_EDITLINE
3503 ** Readline completion callbacks
3505 static char *readline_completion_generator(const char *text
, int state
){
3506 static sqlite3_stmt
*pStmt
= 0;
3510 sqlite3_finalize(pStmt
);
3511 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3512 " FROM completion(%Q) ORDER BY 1", text
);
3513 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3516 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
3517 zRet
= strdup((const char*)sqlite3_column_text(pStmt
, 0));
3519 sqlite3_finalize(pStmt
);
3525 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
3526 rl_attempted_completion_over
= 1;
3527 return rl_completion_matches(zText
, readline_completion_generator
);
3530 #elif HAVE_LINENOISE
3532 ** Linenoise completion callback
3534 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
3535 int nLine
= strlen30(zLine
);
3537 sqlite3_stmt
*pStmt
= 0;
3541 if( nLine
>sizeof(zBuf
)-30 ) return;
3542 if( zLine
[0]=='.' ) return;
3543 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
3544 if( i
==nLine
-1 ) return;
3546 memcpy(zBuf
, zLine
, iStart
);
3547 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3548 " FROM completion(%Q,%Q) ORDER BY 1",
3549 &zLine
[iStart
], zLine
);
3550 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3552 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3553 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
3554 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
3555 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
3556 if( iStart
+nCompletion
< sizeof(zBuf
)-1 ){
3557 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
3558 linenoiseAddCompletion(lc
, zBuf
);
3561 sqlite3_finalize(pStmt
);
3566 ** Do C-language style dequoting.
3572 ** \v -> vertical tab
3574 ** \r -> carriage return
3579 ** \NNN -> ascii character NNN in octal
3581 static void resolve_backslashes(char *z
){
3584 while( *z
&& *z
!='\\' ) z
++;
3585 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
3586 if( c
=='\\' && z
[i
+1]!=0 ){
3604 }else if( c
=='\'' ){
3606 }else if( c
=='\\' ){
3608 }else if( c
>='0' && c
<='7' ){
3610 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3612 c
= (c
<<3) + z
[i
] - '0';
3613 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3615 c
= (c
<<3) + z
[i
] - '0';
3626 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3627 ** for TRUE and FALSE. Return the integer value if appropriate.
3629 static int booleanValue(const char *zArg
){
3631 if( zArg
[0]=='0' && zArg
[1]=='x' ){
3632 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
3634 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
3636 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
3637 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
3640 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
3643 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3649 ** Set or clear a shell flag according to a boolean value.
3651 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
3652 if( booleanValue(zArg
) ){
3653 ShellSetFlag(p
, mFlag
);
3655 ShellClearFlag(p
, mFlag
);
3660 ** Close an output file, assuming it is not stderr or stdout
3662 static void output_file_close(FILE *f
){
3663 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
3667 ** Try to open an output file. The names "stdout" and "stderr" are
3668 ** recognized and do the right thing. NULL is returned if the output
3669 ** filename is "off".
3671 static FILE *output_file_open(const char *zFile
, int bTextMode
){
3673 if( strcmp(zFile
,"stdout")==0 ){
3675 }else if( strcmp(zFile
, "stderr")==0 ){
3677 }else if( strcmp(zFile
, "off")==0 ){
3680 f
= fopen(zFile
, bTextMode
? "w" : "wb");
3682 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
3688 #if !defined(SQLITE_UNTESTABLE)
3689 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3691 ** A routine for handling output from sqlite3_trace().
3693 static int sql_trace_callback(
3699 FILE *f
= (FILE*)pArg
;
3700 UNUSED_PARAMETER(mType
);
3701 UNUSED_PARAMETER(pP
);
3703 const char *z
= (const char*)pX
;
3704 int i
= strlen30(z
);
3705 while( i
>0 && z
[i
-1]==';' ){ i
--; }
3706 utf8_printf(f
, "%.*s;\n", i
, z
);
3714 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
3715 ** a useful spot to set a debugger breakpoint.
3717 static void test_breakpoint(void){
3718 static int nCall
= 0;
3723 ** An object used to read a CSV and other files for import.
3725 typedef struct ImportCtx ImportCtx
;
3727 const char *zFile
; /* Name of the input file */
3728 FILE *in
; /* Read the CSV text from this input stream */
3729 char *z
; /* Accumulated text for a field */
3730 int n
; /* Number of bytes in z */
3731 int nAlloc
; /* Space allocated for z[] */
3732 int nLine
; /* Current line number */
3733 int bNotFirst
; /* True if one or more bytes already read */
3734 int cTerm
; /* Character that terminated the most recent field */
3735 int cColSep
; /* The column separator character. (Usually ",") */
3736 int cRowSep
; /* The row separator character. (Usually "\n") */
3739 /* Append a single byte to z[] */
3740 static void import_append_char(ImportCtx
*p
, int c
){
3741 if( p
->n
+1>=p
->nAlloc
){
3742 p
->nAlloc
+= p
->nAlloc
+ 100;
3743 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
3745 raw_printf(stderr
, "out of memory\n");
3749 p
->z
[p
->n
++] = (char)c
;
3752 /* Read a single field of CSV text. Compatible with rfc4180 and extended
3753 ** with the option of having a separator other than ",".
3755 ** + Input comes from p->in.
3756 ** + Store results in p->z of length p->n. Space to hold p->z comes
3757 ** from sqlite3_malloc64().
3758 ** + Use p->cSep as the column separator. The default is ",".
3759 ** + Use p->rSep as the row separator. The default is "\n".
3760 ** + Keep track of the line number in p->nLine.
3761 ** + Store the character that terminates the field in p->cTerm. Store
3762 ** EOF on end-of-file.
3763 ** + Report syntax errors on stderr
3765 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
3767 int cSep
= p
->cColSep
;
3768 int rSep
= p
->cRowSep
;
3771 if( c
==EOF
|| seenInterrupt
){
3777 int startLine
= p
->nLine
;
3782 if( c
==rSep
) p
->nLine
++;
3789 if( (c
==cSep
&& pc
==cQuote
)
3790 || (c
==rSep
&& pc
==cQuote
)
3791 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
3792 || (c
==EOF
&& pc
==cQuote
)
3794 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
3798 if( pc
==cQuote
&& c
!='\r' ){
3799 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
3800 p
->zFile
, p
->nLine
, cQuote
);
3803 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
3804 p
->zFile
, startLine
, cQuote
);
3808 import_append_char(p
, c
);
3813 /* If this is the first field being parsed and it begins with the
3814 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3815 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
3816 import_append_char(p
, c
);
3818 if( (c
&0xff)==0xbb ){
3819 import_append_char(p
, c
);
3821 if( (c
&0xff)==0xbf ){
3824 return csv_read_one_field(p
);
3828 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
3829 import_append_char(p
, c
);
3834 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
3838 if( p
->z
) p
->z
[p
->n
] = 0;
3843 /* Read a single field of ASCII delimited text.
3845 ** + Input comes from p->in.
3846 ** + Store results in p->z of length p->n. Space to hold p->z comes
3847 ** from sqlite3_malloc64().
3848 ** + Use p->cSep as the column separator. The default is "\x1F".
3849 ** + Use p->rSep as the row separator. The default is "\x1E".
3850 ** + Keep track of the row number in p->nLine.
3851 ** + Store the character that terminates the field in p->cTerm. Store
3852 ** EOF on end-of-file.
3853 ** + Report syntax errors on stderr
3855 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
3857 int cSep
= p
->cColSep
;
3858 int rSep
= p
->cRowSep
;
3861 if( c
==EOF
|| seenInterrupt
){
3865 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
3866 import_append_char(p
, c
);
3873 if( p
->z
) p
->z
[p
->n
] = 0;
3878 ** Try to transfer data for table zTable. If an error is seen while
3879 ** moving forward, try to go backwards. The backwards movement won't
3880 ** work for WITHOUT ROWID tables.
3882 static void tryToCloneData(
3887 sqlite3_stmt
*pQuery
= 0;
3888 sqlite3_stmt
*pInsert
= 0;
3893 int nTable
= strlen30(zTable
);
3896 const int spinRate
= 10000;
3898 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
3899 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3901 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
3902 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
3906 n
= sqlite3_column_count(pQuery
);
3907 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
3909 raw_printf(stderr
, "out of memory\n");
3912 sqlite3_snprintf(200+nTable
,zInsert
,
3913 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
3914 i
= strlen30(zInsert
);
3916 memcpy(zInsert
+i
, ",?", 2);
3919 memcpy(zInsert
+i
, ");", 3);
3920 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
3922 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
3923 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
3928 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
3930 switch( sqlite3_column_type(pQuery
, i
) ){
3932 sqlite3_bind_null(pInsert
, i
+1);
3935 case SQLITE_INTEGER
: {
3936 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
3939 case SQLITE_FLOAT
: {
3940 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
3944 sqlite3_bind_text(pInsert
, i
+1,
3945 (const char*)sqlite3_column_text(pQuery
,i
),
3950 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
3951 sqlite3_column_bytes(pQuery
,i
),
3957 rc
= sqlite3_step(pInsert
);
3958 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
3959 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
3960 sqlite3_errmsg(newDb
));
3962 sqlite3_reset(pInsert
);
3964 if( (cnt
%spinRate
)==0 ){
3965 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
3969 if( rc
==SQLITE_DONE
) break;
3970 sqlite3_finalize(pQuery
);
3971 sqlite3_free(zQuery
);
3972 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3974 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3976 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
3979 } /* End for(k=0...) */
3982 sqlite3_finalize(pQuery
);
3983 sqlite3_finalize(pInsert
);
3984 sqlite3_free(zQuery
);
3985 sqlite3_free(zInsert
);
3990 ** Try to transfer all rows of the schema that match zWhere. For
3991 ** each row, invoke xForEach() on the object defined by that row.
3992 ** If an error is encountered while moving forward through the
3993 ** sqlite_master table, try again moving backwards.
3995 static void tryToCloneSchema(
3999 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
4001 sqlite3_stmt
*pQuery
= 0;
4004 const unsigned char *zName
;
4005 const unsigned char *zSql
;
4008 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4009 " WHERE %s", zWhere
);
4010 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4012 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
4013 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4015 goto end_schema_xfer
;
4017 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4018 zName
= sqlite3_column_text(pQuery
, 0);
4019 zSql
= sqlite3_column_text(pQuery
, 1);
4020 printf("%s... ", zName
); fflush(stdout
);
4021 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
4023 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
4024 sqlite3_free(zErrMsg
);
4028 xForEach(p
, newDb
, (const char*)zName
);
4032 if( rc
!=SQLITE_DONE
){
4033 sqlite3_finalize(pQuery
);
4034 sqlite3_free(zQuery
);
4035 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4036 " WHERE %s ORDER BY rowid DESC", zWhere
);
4037 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4039 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
4040 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4042 goto end_schema_xfer
;
4044 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4045 zName
= sqlite3_column_text(pQuery
, 0);
4046 zSql
= sqlite3_column_text(pQuery
, 1);
4047 printf("%s... ", zName
); fflush(stdout
);
4048 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
4050 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
4051 sqlite3_free(zErrMsg
);
4055 xForEach(p
, newDb
, (const char*)zName
);
4061 sqlite3_finalize(pQuery
);
4062 sqlite3_free(zQuery
);
4066 ** Open a new database file named "zNewDb". Try to recover as much information
4067 ** as possible out of the main database (which might be corrupt) and write it
4070 static void tryToClone(ShellState
*p
, const char *zNewDb
){
4073 if( access(zNewDb
,0)==0 ){
4074 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
4077 rc
= sqlite3_open(zNewDb
, &newDb
);
4079 utf8_printf(stderr
, "Cannot create output database: %s\n",
4080 sqlite3_errmsg(newDb
));
4082 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
4083 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
4084 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
4085 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
4086 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
4087 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4089 sqlite3_close(newDb
);
4093 ** Change the output file back to stdout.
4095 ** If the p->doXdgOpen flag is set, that means the output was being
4096 ** redirected to a temporary file named by p->zTempFile. In that case,
4097 ** launch start/open/xdg-open on that temporary file.
4099 static void output_reset(ShellState
*p
){
4100 if( p
->outfile
[0]=='|' ){
4101 #ifndef SQLITE_OMIT_POPEN
4105 output_file_close(p
->out
);
4106 #ifndef SQLITE_NOHAVE_SYSTEM
4108 const char *zXdgOpenCmd
=
4111 #elif defined(__APPLE__)
4117 zCmd
= sqlite3_mprintf("%s %s", zXdgOpenCmd
, p
->zTempFile
);
4119 utf8_printf(stderr
, "Failed: [%s]\n", zCmd
);
4125 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
4132 ** Run an SQL command and return the single integer result.
4134 static int db_int(ShellState
*p
, const char *zSql
){
4135 sqlite3_stmt
*pStmt
;
4137 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4138 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
4139 res
= sqlite3_column_int(pStmt
,0);
4141 sqlite3_finalize(pStmt
);
4146 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
4148 static unsigned int get2byteInt(unsigned char *a
){
4149 return (a
[0]<<8) + a
[1];
4151 static unsigned int get4byteInt(unsigned char *a
){
4152 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
4156 ** Implementation of the ".info" command.
4158 ** Return 1 on error, 2 to exit, and 0 otherwise.
4160 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
4161 static const struct { const char *zName
; int ofst
; } aField
[] = {
4162 { "file change counter:", 24 },
4163 { "database page count:", 28 },
4164 { "freelist page count:", 36 },
4165 { "schema cookie:", 40 },
4166 { "schema format:", 44 },
4167 { "default cache size:", 48 },
4168 { "autovacuum top root:", 52 },
4169 { "incremental vacuum:", 64 },
4170 { "text encoding:", 56 },
4171 { "user version:", 60 },
4172 { "application id:", 68 },
4173 { "software version:", 96 },
4175 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
4176 { "number of tables:",
4177 "SELECT count(*) FROM %s WHERE type='table'" },
4178 { "number of indexes:",
4179 "SELECT count(*) FROM %s WHERE type='index'" },
4180 { "number of triggers:",
4181 "SELECT count(*) FROM %s WHERE type='trigger'" },
4182 { "number of views:",
4183 "SELECT count(*) FROM %s WHERE type='view'" },
4185 "SELECT total(length(sql)) FROM %s" },
4189 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
4190 sqlite3_stmt
*pStmt
= 0;
4191 unsigned char aHdr
[100];
4193 if( p
->db
==0 ) return 1;
4194 sqlite3_prepare_v2(p
->db
,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4196 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
4197 if( sqlite3_step(pStmt
)==SQLITE_ROW
4198 && sqlite3_column_bytes(pStmt
,0)>100
4200 memcpy(aHdr
, sqlite3_column_blob(pStmt
,0), 100);
4201 sqlite3_finalize(pStmt
);
4203 raw_printf(stderr
, "unable to read database header\n");
4204 sqlite3_finalize(pStmt
);
4207 i
= get2byteInt(aHdr
+16);
4208 if( i
==1 ) i
= 65536;
4209 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
4210 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
4211 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
4212 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
4213 for(i
=0; i
<ArraySize(aField
); i
++){
4214 int ofst
= aField
[i
].ofst
;
4215 unsigned int val
= get4byteInt(aHdr
+ ofst
);
4216 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
4219 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
4220 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
4221 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
4224 raw_printf(p
->out
, "\n");
4227 zSchemaTab
= sqlite3_mprintf("main.sqlite_master");
4228 }else if( strcmp(zDb
,"temp")==0 ){
4229 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_master");
4231 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_master", zDb
);
4233 for(i
=0; i
<ArraySize(aQuery
); i
++){
4234 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
4235 int val
= db_int(p
, zSql
);
4237 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
4239 sqlite3_free(zSchemaTab
);
4244 ** Print the current sqlite3_errmsg() value to stderr and return 1.
4246 static int shellDatabaseError(sqlite3
*db
){
4247 const char *zErr
= sqlite3_errmsg(db
);
4248 utf8_printf(stderr
, "Error: %s\n", zErr
);
4253 ** Print an out-of-memory message to stderr and return 1.
4255 static int shellNomemError(void){
4256 raw_printf(stderr
, "Error: out of memory\n");
4261 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4262 ** if they match and FALSE (0) if they do not match.
4266 ** '*' Matches any sequence of zero or more characters.
4268 ** '?' Matches exactly one character.
4270 ** [...] Matches one character from the enclosed list of
4273 ** [^...] Matches one character not in the enclosed list.
4275 ** '#' Matches any sequence of one or more digits with an
4276 ** optional + or - sign in front
4278 ** ' ' Any span of whitespace matches any other span of
4281 ** Extra whitespace at the end of z[] is ignored.
4283 static int testcase_glob(const char *zGlob
, const char *z
){
4288 while( (c
= (*(zGlob
++)))!=0 ){
4290 if( !IsSpace(*z
) ) return 0;
4291 while( IsSpace(*zGlob
) ) zGlob
++;
4292 while( IsSpace(*z
) ) z
++;
4294 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
4295 if( c
=='?' && (*(z
++))==0 ) return 0;
4300 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
4305 while( (c2
= (*(z
++)))!=0 ){
4308 if( c2
==0 ) return 0;
4310 if( testcase_glob(zGlob
,z
) ) return 1;
4314 if( (*(z
++))==0 ) return 0;
4320 if( c
==0 ) return 0;
4327 if( c
==']' ) seen
= 1;
4330 while( c2
&& c2
!=']' ){
4331 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
4333 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
4343 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
4345 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
4346 if( !IsDigit(z
[0]) ) return 0;
4348 while( IsDigit(z
[0]) ){ z
++; }
4350 if( c
!=(*(z
++)) ) return 0;
4353 while( IsSpace(*z
) ){ z
++; }
4359 ** Compare the string as a command-line option with either one or two
4360 ** initial "-" characters.
4362 static int optionMatch(const char *zStr
, const char *zOpt
){
4363 if( zStr
[0]!='-' ) return 0;
4365 if( zStr
[0]=='-' ) zStr
++;
4366 return strcmp(zStr
, zOpt
)==0;
4372 int shellDeleteFile(const char *zFilename
){
4375 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
4379 rc
= unlink(zFilename
);
4385 ** Try to delete the temporary file (if there is one) and free the
4386 ** memory used to hold the name of the temp file.
4388 static void clearTempFile(ShellState
*p
){
4389 if( p
->zTempFile
==0 ) return;
4390 if( p
->doXdgOpen
) return;
4391 if( shellDeleteFile(p
->zTempFile
) ) return;
4392 sqlite3_free(p
->zTempFile
);
4397 ** Create a new temp file name with the given suffix.
4399 static void newTempFile(ShellState
*p
, const char *zSuffix
){
4401 sqlite3_free(p
->zTempFile
);
4404 sqlite3_file_control(p
->db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &p
->zTempFile
);
4406 if( p
->zTempFile
==0 ){
4408 sqlite3_randomness(sizeof(r
), &r
);
4409 p
->zTempFile
= sqlite3_mprintf("temp%llx.%s", r
, zSuffix
);
4411 p
->zTempFile
= sqlite3_mprintf("%z.%s", p
->zTempFile
, zSuffix
);
4413 if( p
->zTempFile
==0 ){
4414 raw_printf(stderr
, "out of memory\n");
4421 ** The implementation of SQL scalar function fkey_collate_clause(), used
4422 ** by the ".lint fkey-indexes" command. This scalar function is always
4423 ** called with four arguments - the parent table name, the parent column name,
4424 ** the child table name and the child column name.
4426 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4428 ** If either of the named tables or columns do not exist, this function
4429 ** returns an empty string. An empty string is also returned if both tables
4430 ** and columns exist but have the same default collation sequence. Or,
4431 ** if both exist but the default collation sequences are different, this
4432 ** function returns the string " COLLATE <parent-collation>", where
4433 ** <parent-collation> is the default collation sequence of the parent column.
4435 static void shellFkeyCollateClause(
4436 sqlite3_context
*pCtx
,
4438 sqlite3_value
**apVal
4440 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
4441 const char *zParent
;
4442 const char *zParentCol
;
4443 const char *zParentSeq
;
4445 const char *zChildCol
;
4446 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
4450 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
4451 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
4452 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
4453 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
4455 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
4456 rc
= sqlite3_table_column_metadata(
4457 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
4459 if( rc
==SQLITE_OK
){
4460 rc
= sqlite3_table_column_metadata(
4461 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
4465 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
4466 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
4467 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
4474 ** The implementation of dot-command ".lint fkey-indexes".
4476 static int lintFkeyIndexes(
4477 ShellState
*pState
, /* Current shell tool state */
4478 char **azArg
, /* Array of arguments passed to dot command */
4479 int nArg
/* Number of entries in azArg[] */
4481 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
4482 FILE *out
= pState
->out
; /* Stream to write non-error output to */
4483 int bVerbose
= 0; /* If -verbose is present */
4484 int bGroupByParent
= 0; /* If -groupbyparent is present */
4485 int i
; /* To iterate through azArg[] */
4486 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
4487 int rc
; /* Return code */
4488 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
4491 ** This SELECT statement returns one row for each foreign key constraint
4492 ** in the schema of the main database. The column values are:
4494 ** 0. The text of an SQL statement similar to:
4496 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
4498 ** This SELECT is similar to the one that the foreign keys implementation
4499 ** needs to run internally on child tables. If there is an index that can
4500 ** be used to optimize this query, then it can also be used by the FK
4501 ** implementation to optimize DELETE or UPDATE statements on the parent
4504 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4505 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4506 ** contains an index that can be used to optimize the query.
4508 ** 2. Human readable text that describes the child table and columns. e.g.
4510 ** "child_table(child_key1, child_key2)"
4512 ** 3. Human readable text that describes the parent table and columns. e.g.
4514 ** "parent_table(parent_key1, parent_key2)"
4516 ** 4. A full CREATE INDEX statement for an index that could be used to
4517 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4519 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4521 ** 5. The name of the parent table.
4523 ** These six values are used by the C logic below to generate the report.
4527 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
4528 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4529 " || fkey_collate_clause("
4530 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4532 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4533 " || group_concat('*=?', ' AND ') || ')'"
4535 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4537 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4539 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4540 " || ' ON ' || quote(s.name) || '('"
4541 " || group_concat(quote(f.[from]) ||"
4542 " fkey_collate_clause("
4543 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4547 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4548 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4549 "GROUP BY s.name, f.id "
4550 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4552 const char *zGlobIPK
= "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4554 for(i
=2; i
<nArg
; i
++){
4555 int n
= strlen30(azArg
[i
]);
4556 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
4559 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
4564 raw_printf(stderr
, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4567 return SQLITE_ERROR
;
4571 /* Register the fkey_collate_clause() SQL function */
4572 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
4573 0, shellFkeyCollateClause
, 0, 0
4577 if( rc
==SQLITE_OK
){
4578 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
4580 if( rc
==SQLITE_OK
){
4581 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
4584 if( rc
==SQLITE_OK
){
4587 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
4589 sqlite3_stmt
*pExplain
= 0;
4590 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
4591 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
4592 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
4593 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
4594 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
4595 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
4597 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4598 if( rc
!=SQLITE_OK
) break;
4599 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
4600 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
4602 0==sqlite3_strglob(zGlob
, zPlan
)
4603 || 0==sqlite3_strglob(zGlobIPK
, zPlan
)
4606 rc
= sqlite3_finalize(pExplain
);
4607 if( rc
!=SQLITE_OK
) break;
4610 raw_printf(stderr
, "Error: internal error");
4614 && (bVerbose
|| res
==0)
4615 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
4617 raw_printf(out
, "-- Parent table %s\n", zParent
);
4618 sqlite3_free(zPrev
);
4619 zPrev
= sqlite3_mprintf("%s", zParent
);
4623 raw_printf(out
, "%s%s --> %s\n", zIndent
, zCI
, zTarget
);
4624 }else if( bVerbose
){
4625 raw_printf(out
, "%s/* no extra indexes required for %s -> %s */\n",
4626 zIndent
, zFrom
, zTarget
4631 sqlite3_free(zPrev
);
4633 if( rc
!=SQLITE_OK
){
4634 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4637 rc2
= sqlite3_finalize(pSql
);
4638 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
4640 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4643 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4650 ** Implementation of ".lint" dot command.
4652 static int lintDotCommand(
4653 ShellState
*pState
, /* Current shell tool state */
4654 char **azArg
, /* Array of arguments passed to dot command */
4655 int nArg
/* Number of entries in azArg[] */
4658 n
= (nArg
>=2 ? strlen30(azArg
[1]) : 0);
4659 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
4660 return lintFkeyIndexes(pState
, azArg
, nArg
);
4663 raw_printf(stderr
, "Usage %s sub-command ?switches...?\n", azArg
[0]);
4664 raw_printf(stderr
, "Where sub-commands are:\n");
4665 raw_printf(stderr
, " fkey-indexes\n");
4666 return SQLITE_ERROR
;
4669 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4670 /*********************************************************************************
4671 ** The ".archive" or ".ar" command.
4673 static void shellPrepare(
4677 sqlite3_stmt
**ppStmt
4680 if( *pRc
==SQLITE_OK
){
4681 int rc
= sqlite3_prepare_v2(db
, zSql
, -1, ppStmt
, 0);
4682 if( rc
!=SQLITE_OK
){
4683 raw_printf(stderr
, "sql error: %s (%d)\n",
4684 sqlite3_errmsg(db
), sqlite3_errcode(db
)
4691 static void shellPreparePrintf(
4694 sqlite3_stmt
**ppStmt
,
4699 if( *pRc
==SQLITE_OK
){
4703 z
= sqlite3_vmprintf(zFmt
, ap
);
4705 *pRc
= SQLITE_NOMEM
;
4707 shellPrepare(db
, pRc
, z
, ppStmt
);
4713 static void shellFinalize(
4718 sqlite3
*db
= sqlite3_db_handle(pStmt
);
4719 int rc
= sqlite3_finalize(pStmt
);
4720 if( *pRc
==SQLITE_OK
){
4721 if( rc
!=SQLITE_OK
){
4722 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
4729 static void shellReset(
4733 int rc
= sqlite3_reset(pStmt
);
4734 if( *pRc
==SQLITE_OK
){
4735 if( rc
!=SQLITE_OK
){
4736 sqlite3
*db
= sqlite3_db_handle(pStmt
);
4737 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
4743 ** Structure representing a single ".ar" command.
4745 typedef struct ArCommand ArCommand
;
4747 u8 eCmd
; /* An AR_CMD_* value */
4748 u8 bVerbose
; /* True if --verbose */
4749 u8 bZip
; /* True if the archive is a ZIP */
4750 u8 bDryRun
; /* True if --dry-run */
4751 u8 bAppend
; /* True if --append */
4752 int nArg
; /* Number of command arguments */
4753 char *zSrcTable
; /* "sqlar", "zipfile($file)" or "zip" */
4754 const char *zFile
; /* --file argument, or NULL */
4755 const char *zDir
; /* --directory argument, or NULL */
4756 char **azArg
; /* Array of command arguments */
4757 ShellState
*p
; /* Shell state */
4758 sqlite3
*db
; /* Database containing the archive */
4762 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4764 static int arUsage(FILE *f
){
4767 "Usage: .ar [OPTION...] [FILE...]\n"
4768 "The .ar command manages sqlar archives.\n"
4771 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4772 " .ar -tf archive.sar # List members of archive.sar\n"
4773 " .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4775 "Each command line must feature exactly one command option:\n"
4776 " -c, --create Create a new archive\n"
4777 " -u, --update Update or add files to an existing archive\n"
4778 " -t, --list List contents of archive\n"
4779 " -x, --extract Extract files from archive\n"
4781 "And zero or more optional options:\n"
4782 " -v, --verbose Print each filename as it is processed\n"
4783 " -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
4784 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS\n"
4785 " -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
4786 " -n, --dryrun Show the SQL that would have occurred\n"
4788 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4791 return SQLITE_ERROR
;
4795 ** Print an error message for the .ar command to stderr and return
4798 static int arErrorMsg(const char *zFmt
, ...){
4802 z
= sqlite3_vmprintf(zFmt
, ap
);
4804 raw_printf(stderr
, "Error: %s (try \".ar --help\")\n", z
);
4806 return SQLITE_ERROR
;
4810 ** Values for ArCommand.eCmd.
4812 #define AR_CMD_CREATE 1
4813 #define AR_CMD_EXTRACT 2
4814 #define AR_CMD_LIST 3
4815 #define AR_CMD_UPDATE 4
4816 #define AR_CMD_HELP 5
4819 ** Other (non-command) switches.
4821 #define AR_SWITCH_VERBOSE 6
4822 #define AR_SWITCH_FILE 7
4823 #define AR_SWITCH_DIRECTORY 8
4824 #define AR_SWITCH_APPEND 9
4825 #define AR_SWITCH_DRYRUN 10
4827 static int arProcessSwitch(ArCommand
*pAr
, int eSwitch
, const char *zArg
){
4830 case AR_CMD_EXTRACT
:
4835 return arErrorMsg("multiple command options");
4837 pAr
->eCmd
= eSwitch
;
4840 case AR_SWITCH_DRYRUN
:
4843 case AR_SWITCH_VERBOSE
:
4846 case AR_SWITCH_APPEND
:
4848 /* Fall thru into --file */
4849 case AR_SWITCH_FILE
:
4852 case AR_SWITCH_DIRECTORY
:
4861 ** Parse the command line for an ".ar" command. The results are written into
4862 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
4863 ** successfully, otherwise an error message is written to stderr and
4864 ** SQLITE_ERROR returned.
4866 static int arParseCommand(
4867 char **azArg
, /* Array of arguments passed to dot command */
4868 int nArg
, /* Number of entries in azArg[] */
4869 ArCommand
*pAr
/* Populate this object */
4877 { "create", 'c', AR_CMD_CREATE
, 0 },
4878 { "extract", 'x', AR_CMD_EXTRACT
, 0 },
4879 { "list", 't', AR_CMD_LIST
, 0 },
4880 { "update", 'u', AR_CMD_UPDATE
, 0 },
4881 { "help", 'h', AR_CMD_HELP
, 0 },
4882 { "verbose", 'v', AR_SWITCH_VERBOSE
, 0 },
4883 { "file", 'f', AR_SWITCH_FILE
, 1 },
4884 { "append", 'a', AR_SWITCH_APPEND
, 1 },
4885 { "directory", 'C', AR_SWITCH_DIRECTORY
, 1 },
4886 { "dryrun", 'n', AR_SWITCH_DRYRUN
, 0 },
4888 int nSwitch
= sizeof(aSwitch
) / sizeof(struct ArSwitch
);
4889 struct ArSwitch
*pEnd
= &aSwitch
[nSwitch
];
4892 return arUsage(stderr
);
4895 memset(pAr
, 0, sizeof(ArCommand
));
4898 /* Traditional style [tar] invocation */
4901 for(i
=0; z
[i
]; i
++){
4902 const char *zArg
= 0;
4903 struct ArSwitch
*pOpt
;
4904 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
4905 if( z
[i
]==pOpt
->cShort
) break;
4908 return arErrorMsg("unrecognized option: %c", z
[i
]);
4912 return arErrorMsg("option requires an argument: %c",z
[i
]);
4914 zArg
= azArg
[iArg
++];
4916 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
4918 pAr
->nArg
= nArg
-iArg
;
4920 pAr
->azArg
= &azArg
[iArg
];
4923 /* Non-traditional invocation */
4925 for(iArg
=1; iArg
<nArg
; iArg
++){
4929 /* All remaining command line words are command arguments. */
4930 pAr
->azArg
= &azArg
[iArg
];
4931 pAr
->nArg
= nArg
-iArg
;
4938 /* One or more short options */
4940 const char *zArg
= 0;
4941 struct ArSwitch
*pOpt
;
4942 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
4943 if( z
[i
]==pOpt
->cShort
) break;
4946 return arErrorMsg("unrecognized option: %c\n", z
[i
]);
4953 if( iArg
>=(nArg
-1) ){
4954 return arErrorMsg("option requires an argument: %c\n",z
[i
]);
4956 zArg
= azArg
[++iArg
];
4959 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
4961 }else if( z
[2]=='\0' ){
4962 /* A -- option, indicating that all remaining command line words
4963 ** are command arguments. */
4964 pAr
->azArg
= &azArg
[iArg
+1];
4965 pAr
->nArg
= nArg
-iArg
-1;
4969 const char *zArg
= 0; /* Argument for option, if any */
4970 struct ArSwitch
*pMatch
= 0; /* Matching option */
4971 struct ArSwitch
*pOpt
; /* Iterator */
4972 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
4973 const char *zLong
= pOpt
->zLong
;
4974 if( (n
-2)<=strlen30(zLong
) && 0==memcmp(&z
[2], zLong
, n
-2) ){
4976 return arErrorMsg("ambiguous option: %s",z
);
4984 return arErrorMsg("unrecognized option: %s", z
);
4987 if( iArg
>=(nArg
-1) ){
4988 return arErrorMsg("option requires an argument: %s", z
);
4990 zArg
= azArg
[++iArg
];
4992 if( arProcessSwitch(pAr
, pMatch
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
5002 ** This function assumes that all arguments within the ArCommand.azArg[]
5003 ** array refer to archive members, as for the --extract or --list commands.
5004 ** It checks that each of them are present. If any specified file is not
5005 ** present in the archive, an error is printed to stderr and an error
5006 ** code returned. Otherwise, if all specified arguments are present in
5007 ** the archive, SQLITE_OK is returned.
5009 ** This function strips any trailing '/' characters from each argument.
5010 ** This is consistent with the way the [tar] command seems to work on
5013 static int arCheckEntries(ArCommand
*pAr
){
5017 sqlite3_stmt
*pTest
= 0;
5019 shellPreparePrintf(pAr
->db
, &rc
, &pTest
,
5020 "SELECT name FROM %s WHERE name=$name",
5023 j
= sqlite3_bind_parameter_index(pTest
, "$name");
5024 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
5025 char *z
= pAr
->azArg
[i
];
5026 int n
= strlen30(z
);
5028 while( n
>0 && z
[n
-1]=='/' ) n
--;
5030 sqlite3_bind_text(pTest
, j
, z
, -1, SQLITE_STATIC
);
5031 if( SQLITE_ROW
==sqlite3_step(pTest
) ){
5034 shellReset(&rc
, pTest
);
5035 if( rc
==SQLITE_OK
&& bOk
==0 ){
5036 utf8_printf(stderr
, "not found in archive: %s\n", z
);
5040 shellFinalize(&rc
, pTest
);
5046 ** Format a WHERE clause that can be used against the "sqlar" table to
5047 ** identify all archive members that match the command arguments held
5048 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5049 ** The caller is responsible for eventually calling sqlite3_free() on
5050 ** any non-NULL (*pzWhere) value.
5052 static void arWhereClause(
5055 char **pzWhere
/* OUT: New WHERE clause */
5058 if( *pRc
==SQLITE_OK
){
5060 zWhere
= sqlite3_mprintf("1");
5063 const char *zSep
= "";
5064 for(i
=0; i
<pAr
->nArg
; i
++){
5065 const char *z
= pAr
->azArg
[i
];
5066 zWhere
= sqlite3_mprintf(
5067 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5068 zWhere
, zSep
, z
, strlen30(z
)+1, z
5071 *pRc
= SQLITE_NOMEM
;
5082 ** Implementation of .ar "lisT" command.
5084 static int arListCommand(ArCommand
*pAr
){
5085 const char *zSql
= "SELECT %s FROM %s WHERE %s";
5086 const char *azCols
[] = {
5088 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
5092 sqlite3_stmt
*pSql
= 0;
5095 rc
= arCheckEntries(pAr
);
5096 arWhereClause(&rc
, pAr
, &zWhere
);
5098 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql
, azCols
[pAr
->bVerbose
],
5099 pAr
->zSrcTable
, zWhere
);
5101 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
5103 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
5104 if( pAr
->bVerbose
){
5105 utf8_printf(pAr
->p
->out
, "%s % 10d %s %s\n",
5106 sqlite3_column_text(pSql
, 0),
5107 sqlite3_column_int(pSql
, 1),
5108 sqlite3_column_text(pSql
, 2),
5109 sqlite3_column_text(pSql
, 3)
5112 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
5116 shellFinalize(&rc
, pSql
);
5122 ** Implementation of .ar "eXtract" command.
5124 static int arExtractCommand(ArCommand
*pAr
){
5128 " writefile(($dir || name), %s, mode, mtime) "
5129 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)";
5131 const char *azExtraArg
[] = {
5132 "sqlar_uncompress(data, sz)",
5136 sqlite3_stmt
*pSql
= 0;
5142 /* If arguments are specified, check that they actually exist within
5143 ** the archive before proceeding. And formulate a WHERE clause to
5145 rc
= arCheckEntries(pAr
);
5146 arWhereClause(&rc
, pAr
, &zWhere
);
5148 if( rc
==SQLITE_OK
){
5150 zDir
= sqlite3_mprintf("%s/", pAr
->zDir
);
5152 zDir
= sqlite3_mprintf("");
5154 if( zDir
==0 ) rc
= SQLITE_NOMEM
;
5157 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql1
,
5158 azExtraArg
[pAr
->bZip
], pAr
->zSrcTable
, zWhere
5161 if( rc
==SQLITE_OK
){
5162 j
= sqlite3_bind_parameter_index(pSql
, "$dir");
5163 sqlite3_bind_text(pSql
, j
, zDir
, -1, SQLITE_STATIC
);
5165 /* Run the SELECT statement twice. The first time, writefile() is called
5166 ** for all archive members that should be extracted. The second time,
5167 ** only for the directories. This is because the timestamps for
5168 ** extracted directories must be reset after they are populated (as
5169 ** populating them changes the timestamp). */
5171 j
= sqlite3_bind_parameter_index(pSql
, "$dirOnly");
5172 sqlite3_bind_int(pSql
, j
, i
);
5174 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
5176 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
5177 if( i
==0 && pAr
->bVerbose
){
5178 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
5182 shellReset(&rc
, pSql
);
5184 shellFinalize(&rc
, pSql
);
5188 sqlite3_free(zWhere
);
5193 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5195 static int arExecSql(ArCommand
*pAr
, const char *zSql
){
5198 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
5202 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
5204 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
5213 ** Implementation of .ar "create" and "update" commands.
5215 ** Create the "sqlar" table in the database if it does not already exist.
5216 ** Then add each file in the azFile[] array to the archive. Directories
5217 ** are added recursively. If argument bVerbose is non-zero, a message is
5218 ** printed on stdout for each file archived.
5220 ** The create command is the same as update, except that it drops
5221 ** any existing "sqlar" table before beginning.
5223 static int arCreateOrUpdateCommand(
5224 ArCommand
*pAr
, /* Command arguments and options */
5225 int bUpdate
/* true for a --create. false for --update */
5227 const char *zCreate
=
5228 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5229 " name TEXT PRIMARY KEY, -- name of the file\n"
5230 " mode INT, -- access permissions\n"
5231 " mtime INT, -- last modification time\n"
5232 " sz INT, -- original file size\n"
5233 " data BLOB -- compressed content\n"
5235 const char *zDrop
= "DROP TABLE IF EXISTS sqlar";
5236 const char *zInsertFmt
=
5237 "REPLACE INTO sqlar(name,mode,mtime,sz,data)\n"
5242 " CASE substr(lsmode(mode),1,1)\n"
5243 " WHEN '-' THEN length(data)\n"
5244 " WHEN 'd' THEN 0\n"
5246 " CASE WHEN lsmode(mode) LIKE 'd%%' THEN NULL else data END\n"
5247 " FROM fsdir(%Q,%Q)\n"
5248 " WHERE lsmode(mode) NOT LIKE '?%%';";
5249 int i
; /* For iterating through azFile[] */
5250 int rc
; /* Return code */
5252 rc
= arExecSql(pAr
, "SAVEPOINT ar;");
5253 if( rc
!=SQLITE_OK
) return rc
;
5255 rc
= arExecSql(pAr
, zDrop
);
5256 if( rc
!=SQLITE_OK
) return rc
;
5258 rc
= arExecSql(pAr
, zCreate
);
5259 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
5260 char *zSql
= sqlite3_mprintf(zInsertFmt
,
5261 pAr
->bVerbose
? "shell_putsnl(name)" : "name",
5262 pAr
->azArg
[i
], pAr
->zDir
);
5263 rc
= arExecSql(pAr
, zSql
);
5266 if( rc
!=SQLITE_OK
){
5267 arExecSql(pAr
, "ROLLBACK TO ar; RELEASE ar;");
5269 rc
= arExecSql(pAr
, "RELEASE ar;");
5275 ** Implementation of ".ar" dot command.
5277 static int arDotCommand(
5278 ShellState
*pState
, /* Current shell tool state */
5279 char **azArg
, /* Array of arguments passed to dot command */
5280 int nArg
/* Number of entries in azArg[] */
5284 memset(&cmd
, 0, sizeof(cmd
));
5285 rc
= arParseCommand(azArg
, nArg
, &cmd
);
5286 if( rc
==SQLITE_OK
){
5287 int eDbType
= SHELL_OPEN_UNSPEC
;
5289 cmd
.db
= pState
->db
;
5291 eDbType
= deduceDatabaseType(cmd
.zFile
);
5293 eDbType
= pState
->openMode
;
5295 if( eDbType
==SHELL_OPEN_ZIPFILE
){
5297 cmd
.zSrcTable
= sqlite3_mprintf("zip");
5299 cmd
.zSrcTable
= sqlite3_mprintf("zipfile(%Q)", cmd
.zFile
);
5301 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
5302 utf8_printf(stderr
, "zip archives are read-only\n");
5304 goto end_ar_command
;
5307 }else if( cmd
.zFile
){
5309 if( cmd
.bAppend
) eDbType
= SHELL_OPEN_APPENDVFS
;
5310 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
5311 flags
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
5313 flags
= SQLITE_OPEN_READONLY
;
5317 utf8_printf(pState
->out
, "-- open database '%s'%s\n", cmd
.zFile
,
5318 eDbType
==SHELL_OPEN_APPENDVFS
? " using 'apndvfs'" : "");
5320 rc
= sqlite3_open_v2(cmd
.zFile
, &cmd
.db
, flags
,
5321 eDbType
==SHELL_OPEN_APPENDVFS
? "apndvfs" : 0);
5322 if( rc
!=SQLITE_OK
){
5323 utf8_printf(stderr
, "cannot open file: %s (%s)\n",
5324 cmd
.zFile
, sqlite3_errmsg(cmd
.db
)
5326 goto end_ar_command
;
5328 sqlite3_fileio_init(cmd
.db
, 0, 0);
5329 #ifdef SQLITE_HAVE_ZLIB
5330 sqlite3_sqlar_init(cmd
.db
, 0, 0);
5332 sqlite3_create_function(cmd
.db
, "shell_putsnl", 1, SQLITE_UTF8
, cmd
.p
,
5333 shellPutsFunc
, 0, 0);
5336 if( cmd
.zSrcTable
==0 ){
5337 if( cmd
.eCmd
!=AR_CMD_CREATE
5338 && sqlite3_table_column_metadata(cmd
.db
,0,"sqlar","name",0,0,0,0,0)
5340 utf8_printf(stderr
, "database does not contain an 'sqlar' table\n");
5342 goto end_ar_command
;
5344 cmd
.zSrcTable
= sqlite3_mprintf("sqlar");
5349 rc
= arCreateOrUpdateCommand(&cmd
, 0);
5352 case AR_CMD_EXTRACT
:
5353 rc
= arExtractCommand(&cmd
);
5357 rc
= arListCommand(&cmd
);
5361 arUsage(pState
->out
);
5365 assert( cmd
.eCmd
==AR_CMD_UPDATE
);
5366 rc
= arCreateOrUpdateCommand(&cmd
, 1);
5371 if( cmd
.db
!=pState
->db
){
5372 sqlite3_close(cmd
.db
);
5374 sqlite3_free(cmd
.zSrcTable
);
5378 /* End of the ".archive" or ".ar" command logic
5379 **********************************************************************************/
5380 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
5384 ** If an input line begins with "." then invoke this routine to
5385 ** process that line.
5387 ** Return 1 on error, 2 to exit, and 0 otherwise.
5389 static int do_meta_command(char *zLine
, ShellState
*p
){
5396 #ifndef SQLITE_OMIT_VIRTUALTABLE
5397 if( p
->expert
.pExpert
){
5398 expertFinish(p
, 1, 0);
5402 /* Parse the input line into tokens.
5404 while( zLine
[h
] && nArg
<ArraySize(azArg
) ){
5405 while( IsSpace(zLine
[h
]) ){ h
++; }
5406 if( zLine
[h
]==0 ) break;
5407 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
5408 int delim
= zLine
[h
++];
5409 azArg
[nArg
++] = &zLine
[h
];
5410 while( zLine
[h
] && zLine
[h
]!=delim
){
5411 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
5414 if( zLine
[h
]==delim
){
5417 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
5419 azArg
[nArg
++] = &zLine
[h
];
5420 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
5421 if( zLine
[h
] ) zLine
[h
++] = 0;
5422 resolve_backslashes(azArg
[nArg
-1]);
5426 /* Process the input line.
5428 if( nArg
==0 ) return 0; /* no tokens, no error */
5429 n
= strlen30(azArg
[0]);
5433 #ifndef SQLITE_OMIT_AUTHORIZATION
5434 if( c
=='a' && strncmp(azArg
[0], "auth", n
)==0 ){
5436 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
5438 goto meta_command_exit
;
5441 if( booleanValue(azArg
[1]) ){
5442 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
5444 sqlite3_set_authorizer(p
->db
, 0, 0);
5449 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5450 if( c
=='a' && strncmp(azArg
[0], "archive", n
)==0 ){
5452 rc
= arDotCommand(p
, azArg
, nArg
);
5456 if( (c
=='b' && n
>=3 && strncmp(azArg
[0], "backup", n
)==0)
5457 || (c
=='s' && n
>=3 && strncmp(azArg
[0], "save", n
)==0)
5459 const char *zDestFile
= 0;
5460 const char *zDb
= 0;
5462 sqlite3_backup
*pBackup
;
5464 for(j
=1; j
<nArg
; j
++){
5465 const char *z
= azArg
[j
];
5467 while( z
[0]=='-' ) z
++;
5468 /* No options to process at this time */
5470 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
5473 }else if( zDestFile
==0 ){
5474 zDestFile
= azArg
[j
];
5477 zDestFile
= azArg
[j
];
5479 raw_printf(stderr
, "too many arguments to .backup\n");
5484 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
5487 if( zDb
==0 ) zDb
= "main";
5488 rc
= sqlite3_open(zDestFile
, &pDest
);
5489 if( rc
!=SQLITE_OK
){
5490 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
5491 sqlite3_close(pDest
);
5495 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
5497 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
5498 sqlite3_close(pDest
);
5501 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
5502 sqlite3_backup_finish(pBackup
);
5503 if( rc
==SQLITE_DONE
){
5506 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
5509 sqlite3_close(pDest
);
5512 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "bail", n
)==0 ){
5514 bail_on_error
= booleanValue(azArg
[1]);
5516 raw_printf(stderr
, "Usage: .bail on|off\n");
5521 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "binary", n
)==0 ){
5523 if( booleanValue(azArg
[1]) ){
5524 setBinaryMode(p
->out
, 1);
5526 setTextMode(p
->out
, 1);
5529 raw_printf(stderr
, "Usage: .binary on|off\n");
5534 if( c
=='c' && strcmp(azArg
[0],"cd")==0 ){
5536 #if defined(_WIN32) || defined(WIN32)
5537 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
5538 rc
= !SetCurrentDirectoryW(z
);
5541 rc
= chdir(azArg
[1]);
5544 utf8_printf(stderr
, "Cannot change to directory \"%s\"\n", azArg
[1]);
5548 raw_printf(stderr
, "Usage: .cd DIRECTORY\n");
5553 /* The undocumented ".breakpoint" command causes a call to the no-op
5554 ** routine named test_breakpoint().
5556 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "breakpoint", n
)==0 ){
5560 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "changes", n
)==0 ){
5562 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
5564 raw_printf(stderr
, "Usage: .changes on|off\n");
5569 /* Cancel output redirection, if it is currently set (by .testcase)
5570 ** Then read the content of the testcase-out.txt file and compare against
5571 ** azArg[1]. If there are differences, report an error and exit.
5573 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "check", n
)==0 ){
5577 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
5579 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
5580 raw_printf(stderr
, "Error: cannot read 'testcase-out.txt'\n");
5582 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
5584 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5585 p
->zTestcase
, azArg
[1], zRes
);
5588 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
5594 if( c
=='c' && strncmp(azArg
[0], "clone", n
)==0 ){
5596 tryToClone(p
, azArg
[1]);
5598 raw_printf(stderr
, "Usage: .clone FILENAME\n");
5603 if( c
=='d' && n
>1 && strncmp(azArg
[0], "databases", n
)==0 ){
5607 memcpy(&data
, p
, sizeof(data
));
5608 data
.showHeader
= 0;
5609 data
.cMode
= data
.mode
= MODE_List
;
5610 sqlite3_snprintf(sizeof(data
.colSeparator
),data
.colSeparator
,": ");
5612 sqlite3_exec(p
->db
, "SELECT name, file FROM pragma_database_list",
5613 callback
, &data
, &zErrMsg
);
5615 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
5616 sqlite3_free(zErrMsg
);
5621 if( c
=='d' && strncmp(azArg
[0], "dbinfo", n
)==0 ){
5622 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
5625 if( c
=='d' && strncmp(azArg
[0], "dump", n
)==0 ){
5626 const char *zLike
= 0;
5628 int savedShowHeader
= p
->showHeader
;
5629 ShellClearFlag(p
, SHFLG_PreserveRowid
|SHFLG_Newlines
);
5630 for(i
=1; i
<nArg
; i
++){
5631 if( azArg
[i
][0]=='-' ){
5632 const char *z
= azArg
[i
]+1;
5633 if( z
[0]=='-' ) z
++;
5634 if( strcmp(z
,"preserve-rowids")==0 ){
5635 #ifdef SQLITE_OMIT_VIRTUALTABLE
5636 raw_printf(stderr
, "The --preserve-rowids option is not compatible"
5637 " with SQLITE_OMIT_VIRTUALTABLE\n");
5639 goto meta_command_exit
;
5641 ShellSetFlag(p
, SHFLG_PreserveRowid
);
5644 if( strcmp(z
,"newlines")==0 ){
5645 ShellSetFlag(p
, SHFLG_Newlines
);
5648 raw_printf(stderr
, "Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
5650 goto meta_command_exit
;
5653 raw_printf(stderr
, "Usage: .dump ?--preserve-rowids? "
5654 "?--newlines? ?LIKE-PATTERN?\n");
5656 goto meta_command_exit
;
5662 /* When playing back a "dump", the content might appear in an order
5663 ** which causes immediate foreign key constraints to be violated.
5664 ** So disable foreign-key constraint enforcement to prevent problems. */
5665 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
5666 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
5667 p
->writableSchema
= 0;
5669 /* Set writable_schema=ON since doing so forces SQLite to initialize
5670 ** as much of the schema as it can even if the sqlite_master table is
5672 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5675 run_schema_dump_query(p
,
5676 "SELECT name, type, sql FROM sqlite_master "
5677 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5679 run_schema_dump_query(p
,
5680 "SELECT name, type, sql FROM sqlite_master "
5681 "WHERE name=='sqlite_sequence'"
5683 run_table_dump_query(p
,
5684 "SELECT sql FROM sqlite_master "
5685 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5689 zSql
= sqlite3_mprintf(
5690 "SELECT name, type, sql FROM sqlite_master "
5691 "WHERE tbl_name LIKE %Q AND type=='table'"
5692 " AND sql NOT NULL", zLike
);
5693 run_schema_dump_query(p
,zSql
);
5695 zSql
= sqlite3_mprintf(
5696 "SELECT sql FROM sqlite_master "
5697 "WHERE sql NOT NULL"
5698 " AND type IN ('index','trigger','view')"
5699 " AND tbl_name LIKE %Q", zLike
);
5700 run_table_dump_query(p
, zSql
, 0);
5703 if( p
->writableSchema
){
5704 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
5705 p
->writableSchema
= 0;
5707 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5708 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
5709 raw_printf(p
->out
, p
->nErr
? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5710 p
->showHeader
= savedShowHeader
;
5713 if( c
=='e' && strncmp(azArg
[0], "echo", n
)==0 ){
5715 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
5717 raw_printf(stderr
, "Usage: .echo on|off\n");
5722 if( c
=='e' && strncmp(azArg
[0], "eqp", n
)==0 ){
5724 if( strcmp(azArg
[1],"full")==0 ){
5725 p
->autoEQP
= AUTOEQP_full
;
5726 }else if( strcmp(azArg
[1],"trigger")==0 ){
5727 p
->autoEQP
= AUTOEQP_trigger
;
5729 p
->autoEQP
= (u8
)booleanValue(azArg
[1]);
5732 raw_printf(stderr
, "Usage: .eqp off|on|trigger|full\n");
5737 if( c
=='e' && strncmp(azArg
[0], "exit", n
)==0 ){
5738 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
5742 /* The ".explain" command is automatic now. It is largely pointless. It
5743 ** retained purely for backwards compatibility */
5744 if( c
=='e' && strncmp(azArg
[0], "explain", n
)==0 ){
5747 if( strcmp(azArg
[1],"auto")==0 ){
5750 val
= booleanValue(azArg
[1]);
5753 if( val
==1 && p
->mode
!=MODE_Explain
){
5754 p
->normalMode
= p
->mode
;
5755 p
->mode
= MODE_Explain
;
5758 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
5760 }else if( val
==99 ){
5761 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
5766 #ifndef SQLITE_OMIT_VIRTUALTABLE
5767 if( c
=='e' && strncmp(azArg
[0], "expert", n
)==0 ){
5769 expertDotCommand(p
, azArg
, nArg
);
5773 if( c
=='f' && strncmp(azArg
[0], "fullschema", n
)==0 ){
5777 memcpy(&data
, p
, sizeof(data
));
5778 data
.showHeader
= 0;
5779 data
.cMode
= data
.mode
= MODE_Semi
;
5780 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
5781 data
.cMode
= data
.mode
= MODE_Pretty
;
5785 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
5787 goto meta_command_exit
;
5790 rc
= sqlite3_exec(p
->db
,
5792 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5793 " FROM sqlite_master UNION ALL"
5794 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5795 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
5797 callback
, &data
, &zErrMsg
5799 if( rc
==SQLITE_OK
){
5800 sqlite3_stmt
*pStmt
;
5801 rc
= sqlite3_prepare_v2(p
->db
,
5802 "SELECT rowid FROM sqlite_master"
5803 " WHERE name GLOB 'sqlite_stat[134]'",
5805 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
5806 sqlite3_finalize(pStmt
);
5809 raw_printf(p
->out
, "/* No STAT tables available */\n");
5811 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
5812 sqlite3_exec(p
->db
, "SELECT 'ANALYZE sqlite_master'",
5813 callback
, &data
, &zErrMsg
);
5814 data
.cMode
= data
.mode
= MODE_Insert
;
5815 data
.zDestTable
= "sqlite_stat1";
5816 shell_exec(p
->db
, "SELECT * FROM sqlite_stat1",
5817 shell_callback
, &data
,&zErrMsg
);
5818 data
.zDestTable
= "sqlite_stat3";
5819 shell_exec(p
->db
, "SELECT * FROM sqlite_stat3",
5820 shell_callback
, &data
,&zErrMsg
);
5821 data
.zDestTable
= "sqlite_stat4";
5822 shell_exec(p
->db
, "SELECT * FROM sqlite_stat4",
5823 shell_callback
, &data
, &zErrMsg
);
5824 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
5828 if( c
=='h' && strncmp(azArg
[0], "headers", n
)==0 ){
5830 p
->showHeader
= booleanValue(azArg
[1]);
5832 raw_printf(stderr
, "Usage: .headers on|off\n");
5837 if( c
=='h' && strncmp(azArg
[0], "help", n
)==0 ){
5838 utf8_printf(p
->out
, "%s", zHelp
);
5841 if( c
=='i' && strncmp(azArg
[0], "import", n
)==0 ){
5842 char *zTable
; /* Insert data into this table */
5843 char *zFile
; /* Name of file to extra content from */
5844 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
5845 int nCol
; /* Number of columns in the table */
5846 int nByte
; /* Number of bytes in an SQL string */
5847 int i
, j
; /* Loop counters */
5848 int needCommit
; /* True to COMMIT or ROLLBACK at end */
5849 int nSep
; /* Number of bytes in p->colSeparator[] */
5850 char *zSql
; /* An SQL statement */
5851 ImportCtx sCtx
; /* Reader context */
5852 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
5853 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close file */
5856 raw_printf(stderr
, "Usage: .import FILE TABLE\n");
5857 goto meta_command_exit
;
5862 memset(&sCtx
, 0, sizeof(sCtx
));
5864 nSep
= strlen30(p
->colSeparator
);
5867 "Error: non-null column separator required for import\n");
5871 raw_printf(stderr
, "Error: multi-character column separators not allowed"
5875 nSep
= strlen30(p
->rowSeparator
);
5877 raw_printf(stderr
, "Error: non-null row separator required for import\n");
5880 if( nSep
==2 && p
->mode
==MODE_Csv
&& strcmp(p
->rowSeparator
, SEP_CrLf
)==0 ){
5881 /* When importing CSV (only), if the row separator is set to the
5882 ** default output row separator, change it to the default input
5883 ** row separator. This avoids having to maintain different input
5884 ** and output row separators. */
5885 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
5886 nSep
= strlen30(p
->rowSeparator
);
5889 raw_printf(stderr
, "Error: multi-character row separators not allowed"
5895 if( sCtx
.zFile
[0]=='|' ){
5896 #ifdef SQLITE_OMIT_POPEN
5897 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
5900 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
5901 sCtx
.zFile
= "<pipe>";
5905 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
5908 if( p
->mode
==MODE_Ascii
){
5909 xRead
= ascii_read_one_field
;
5911 xRead
= csv_read_one_field
;
5914 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
5917 sCtx
.cColSep
= p
->colSeparator
[0];
5918 sCtx
.cRowSep
= p
->rowSeparator
[0];
5919 zSql
= sqlite3_mprintf("SELECT * FROM %s", zTable
);
5921 raw_printf(stderr
, "Error: out of memory\n");
5925 nByte
= strlen30(zSql
);
5926 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
5927 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
5928 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
5929 char *zCreate
= sqlite3_mprintf("CREATE TABLE %s", zTable
);
5931 while( xRead(&sCtx
) ){
5932 zCreate
= sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate
, cSep
, sCtx
.z
);
5934 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
5937 sqlite3_free(zCreate
);
5938 sqlite3_free(sCtx
.z
);
5940 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
5943 zCreate
= sqlite3_mprintf("%z\n)", zCreate
);
5944 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
5945 sqlite3_free(zCreate
);
5947 utf8_printf(stderr
, "CREATE TABLE %s(...) failed: %s\n", zTable
,
5948 sqlite3_errmsg(p
->db
));
5949 sqlite3_free(sCtx
.z
);
5953 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
5957 if (pStmt
) sqlite3_finalize(pStmt
);
5958 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
5962 nCol
= sqlite3_column_count(pStmt
);
5963 sqlite3_finalize(pStmt
);
5965 if( nCol
==0 ) return 0; /* no columns, no error */
5966 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
5968 raw_printf(stderr
, "Error: out of memory\n");
5972 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO \"%w\" VALUES(?", zTable
);
5974 for(i
=1; i
<nCol
; i
++){
5980 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
5983 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
5984 if (pStmt
) sqlite3_finalize(pStmt
);
5988 needCommit
= sqlite3_get_autocommit(p
->db
);
5989 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
5991 int startLine
= sCtx
.nLine
;
5992 for(i
=0; i
<nCol
; i
++){
5993 char *z
= xRead(&sCtx
);
5995 ** Did we reach end-of-file before finding any columns?
5996 ** If so, stop instead of NULL filling the remaining columns.
5998 if( z
==0 && i
==0 ) break;
6000 ** Did we reach end-of-file OR end-of-line before finding any
6001 ** columns in ASCII mode? If so, stop instead of NULL filling
6002 ** the remaining columns.
6004 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
6005 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
6006 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
6007 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
6008 "filling the rest with NULL\n",
6009 sCtx
.zFile
, startLine
, nCol
, i
+1);
6011 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
6014 if( sCtx
.cTerm
==sCtx
.cColSep
){
6018 }while( sCtx
.cTerm
==sCtx
.cColSep
);
6019 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
6021 sCtx
.zFile
, startLine
, nCol
, i
);
6024 sqlite3_step(pStmt
);
6025 rc
= sqlite3_reset(pStmt
);
6026 if( rc
!=SQLITE_OK
){
6027 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
6028 startLine
, sqlite3_errmsg(p
->db
));
6031 }while( sCtx
.cTerm
!=EOF
);
6034 sqlite3_free(sCtx
.z
);
6035 sqlite3_finalize(pStmt
);
6036 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
6039 #ifndef SQLITE_UNTESTABLE
6040 if( c
=='i' && strncmp(azArg
[0], "imposter", n
)==0 ){
6043 sqlite3_stmt
*pStmt
;
6047 utf8_printf(stderr
, "Usage: .imposter INDEX IMPOSTER\n");
6049 goto meta_command_exit
;
6052 zSql
= sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6053 " WHERE name='%q' AND type='index'", azArg
[1]);
6054 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6056 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
6057 tnum
= sqlite3_column_int(pStmt
, 0);
6059 sqlite3_finalize(pStmt
);
6061 utf8_printf(stderr
, "no such index: \"%s\"\n", azArg
[1]);
6063 goto meta_command_exit
;
6065 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
6066 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6069 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6071 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
6074 if( sqlite3_column_int(pStmt
,1)==-1 ){
6077 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
6082 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
6084 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
6087 sqlite3_finalize(pStmt
);
6088 zSql
= sqlite3_mprintf(
6089 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6090 azArg
[2], zCollist
, zCollist
);
6091 sqlite3_free(zCollist
);
6092 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
6093 if( rc
==SQLITE_OK
){
6094 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
6095 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
6097 utf8_printf(stderr
, "Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
6099 utf8_printf(stdout
, "%s;\n", zSql
);
6101 "WARNING: writing to an imposter table will corrupt the index!\n"
6105 raw_printf(stderr
, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
6110 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6112 #ifdef SQLITE_ENABLE_IOTRACE
6113 if( c
=='i' && strncmp(azArg
[0], "iotrace", n
)==0 ){
6114 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
6115 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
6119 }else if( strcmp(azArg
[1], "-")==0 ){
6120 sqlite3IoTrace
= iotracePrintf
;
6123 iotrace
= fopen(azArg
[1], "w");
6125 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
6129 sqlite3IoTrace
= iotracePrintf
;
6135 if( c
=='l' && n
>=5 && strncmp(azArg
[0], "limits", n
)==0 ){
6136 static const struct {
6137 const char *zLimitName
; /* Name of a limit */
6138 int limitCode
; /* Integer code for that limit */
6140 { "length", SQLITE_LIMIT_LENGTH
},
6141 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
6142 { "column", SQLITE_LIMIT_COLUMN
},
6143 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
6144 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
6145 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
6146 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
6147 { "attached", SQLITE_LIMIT_ATTACHED
},
6148 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
6149 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
6150 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
6151 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
6156 for(i
=0; i
<ArraySize(aLimit
); i
++){
6157 printf("%20s %d\n", aLimit
[i
].zLimitName
,
6158 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
6161 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
6163 goto meta_command_exit
;
6166 n2
= strlen30(azArg
[1]);
6167 for(i
=0; i
<ArraySize(aLimit
); i
++){
6168 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
6172 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
6174 goto meta_command_exit
;
6179 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
6180 "enter \".limits\" with no arguments for a list.\n",
6183 goto meta_command_exit
;
6186 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
6187 (int)integerValue(azArg
[2]));
6189 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
6190 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
6194 if( c
=='l' && n
>2 && strncmp(azArg
[0], "lint", n
)==0 ){
6196 lintDotCommand(p
, azArg
, nArg
);
6199 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6200 if( c
=='l' && strncmp(azArg
[0], "load", n
)==0 ){
6201 const char *zFile
, *zProc
;
6204 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
6206 goto meta_command_exit
;
6209 zProc
= nArg
>=3 ? azArg
[2] : 0;
6211 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
6212 if( rc
!=SQLITE_OK
){
6213 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
6214 sqlite3_free(zErrMsg
);
6220 if( c
=='l' && strncmp(azArg
[0], "log", n
)==0 ){
6222 raw_printf(stderr
, "Usage: .log FILENAME\n");
6225 const char *zFile
= azArg
[1];
6226 output_file_close(p
->pLog
);
6227 p
->pLog
= output_file_open(zFile
, 0);
6231 if( c
=='m' && strncmp(azArg
[0], "mode", n
)==0 ){
6232 const char *zMode
= nArg
>=2 ? azArg
[1] : "";
6233 int n2
= strlen30(zMode
);
6235 if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"lines",n2
)==0 ){
6236 p
->mode
= MODE_Line
;
6237 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6238 }else if( c2
=='c' && strncmp(azArg
[1],"columns",n2
)==0 ){
6239 p
->mode
= MODE_Column
;
6240 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6241 }else if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"list",n2
)==0 ){
6242 p
->mode
= MODE_List
;
6243 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
6244 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6245 }else if( c2
=='h' && strncmp(azArg
[1],"html",n2
)==0 ){
6246 p
->mode
= MODE_Html
;
6247 }else if( c2
=='t' && strncmp(azArg
[1],"tcl",n2
)==0 ){
6249 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
6250 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6251 }else if( c2
=='c' && strncmp(azArg
[1],"csv",n2
)==0 ){
6253 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
6254 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
6255 }else if( c2
=='t' && strncmp(azArg
[1],"tabs",n2
)==0 ){
6256 p
->mode
= MODE_List
;
6257 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
6258 }else if( c2
=='i' && strncmp(azArg
[1],"insert",n2
)==0 ){
6259 p
->mode
= MODE_Insert
;
6260 set_table_name(p
, nArg
>=3 ? azArg
[2] : "table");
6261 }else if( c2
=='q' && strncmp(azArg
[1],"quote",n2
)==0 ){
6262 p
->mode
= MODE_Quote
;
6263 }else if( c2
=='a' && strncmp(azArg
[1],"ascii",n2
)==0 ){
6264 p
->mode
= MODE_Ascii
;
6265 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
6266 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
6267 }else if( nArg
==1 ){
6268 raw_printf(p
->out
, "current output mode: %s\n", modeDescr
[p
->mode
]);
6270 raw_printf(stderr
, "Error: mode should be one of: "
6271 "ascii column csv html insert line list quote tabs tcl\n");
6277 if( c
=='n' && strncmp(azArg
[0], "nullvalue", n
)==0 ){
6279 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
6280 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
6282 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
6287 if( c
=='o' && strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
6288 char *zNewFilename
; /* Name of the database file to open */
6289 int iName
= 1; /* Index in azArg[] of the filename */
6290 int newFlag
= 0; /* True to delete file before opening */
6291 /* Close the existing database */
6292 session_close_all(p
);
6293 sqlite3_close(p
->db
);
6296 sqlite3_free(p
->zFreeOnClose
);
6297 p
->zFreeOnClose
= 0;
6298 p
->openMode
= SHELL_OPEN_UNSPEC
;
6299 /* Check for command-line arguments */
6300 for(iName
=1; iName
<nArg
&& azArg
[iName
][0]=='-'; iName
++){
6301 const char *z
= azArg
[iName
];
6302 if( optionMatch(z
,"new") ){
6304 #ifdef SQLITE_HAVE_ZIP
6305 }else if( optionMatch(z
, "zip") ){
6306 p
->openMode
= SHELL_OPEN_ZIPFILE
;
6308 }else if( optionMatch(z
, "append") ){
6309 p
->openMode
= SHELL_OPEN_APPENDVFS
;
6310 }else if( z
[0]=='-' ){
6311 utf8_printf(stderr
, "unknown option: %s\n", z
);
6313 goto meta_command_exit
;
6316 /* If a filename is specified, try to open it first */
6317 zNewFilename
= nArg
>iName
? sqlite3_mprintf("%s", azArg
[iName
]) : 0;
6319 if( newFlag
) shellDeleteFile(zNewFilename
);
6320 p
->zDbFilename
= zNewFilename
;
6323 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
6324 sqlite3_free(zNewFilename
);
6326 p
->zFreeOnClose
= zNewFilename
;
6330 /* As a fall-back open a TEMP database */
6337 && (strncmp(azArg
[0], "output", n
)==0||strncmp(azArg
[0], "once", n
)==0))
6338 || (c
=='e' && n
==5 && strcmp(azArg
[0],"excel")==0)
6340 const char *zFile
= nArg
>=2 ? azArg
[1] : "stdout";
6342 if( azArg
[0][0]=='e' ){
6343 /* Transform the ".excel" command into ".once -x" */
6346 zFile
= azArg
[1] = "-x";
6350 utf8_printf(stderr
, "Usage: .%s [-e|-x|FILE]\n", azArg
[0]);
6352 goto meta_command_exit
;
6354 if( n
>1 && strncmp(azArg
[0], "once", n
)==0 ){
6356 raw_printf(stderr
, "Usage: .once (-e|-x|FILE)\n");
6358 goto meta_command_exit
;
6365 if( zFile
[0]=='-' && zFile
[1]=='-' ) zFile
++;
6366 #ifndef SQLITE_NOHAVE_SYSTEM
6367 if( strcmp(zFile
, "-e")==0 || strcmp(zFile
, "-x")==0 ){
6370 if( zFile
[1]=='x' ){
6371 newTempFile(p
, "csv");
6373 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
6374 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
6376 newTempFile(p
, "txt");
6379 zFile
= p
->zTempFile
;
6381 #endif /* SQLITE_NOHAVE_SYSTEM */
6382 if( zFile
[0]=='|' ){
6383 #ifdef SQLITE_OMIT_POPEN
6384 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
6388 p
->out
= popen(zFile
+ 1, "w");
6390 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
6394 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
6398 p
->out
= output_file_open(zFile
, bTxtMode
);
6400 if( strcmp(zFile
,"off")!=0 ){
6401 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
6406 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
6411 if( c
=='p' && n
>=3 && strncmp(azArg
[0], "print", n
)==0 ){
6413 for(i
=1; i
<nArg
; i
++){
6414 if( i
>1 ) raw_printf(p
->out
, " ");
6415 utf8_printf(p
->out
, "%s", azArg
[i
]);
6417 raw_printf(p
->out
, "\n");
6420 if( c
=='p' && strncmp(azArg
[0], "prompt", n
)==0 ){
6422 strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
6425 strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
6429 if( c
=='q' && strncmp(azArg
[0], "quit", n
)==0 ){
6433 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "read", n
)==0 ){
6436 raw_printf(stderr
, "Usage: .read FILE\n");
6438 goto meta_command_exit
;
6440 alt
= fopen(azArg
[1], "rb");
6442 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
6445 rc
= process_input(p
, alt
);
6450 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "restore", n
)==0 ){
6451 const char *zSrcFile
;
6454 sqlite3_backup
*pBackup
;
6458 zSrcFile
= azArg
[1];
6460 }else if( nArg
==3 ){
6461 zSrcFile
= azArg
[2];
6464 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
6466 goto meta_command_exit
;
6468 rc
= sqlite3_open(zSrcFile
, &pSrc
);
6469 if( rc
!=SQLITE_OK
){
6470 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
6471 sqlite3_close(pSrc
);
6475 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
6477 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6478 sqlite3_close(pSrc
);
6481 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
6482 || rc
==SQLITE_BUSY
){
6483 if( rc
==SQLITE_BUSY
){
6484 if( nTimeout
++ >= 3 ) break;
6488 sqlite3_backup_finish(pBackup
);
6489 if( rc
==SQLITE_DONE
){
6491 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
6492 raw_printf(stderr
, "Error: source database is busy\n");
6495 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6498 sqlite3_close(pSrc
);
6501 if( c
=='s' && strncmp(azArg
[0], "scanstats", n
)==0 ){
6503 p
->scanstatsOn
= (u8
)booleanValue(azArg
[1]);
6504 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6505 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
6508 raw_printf(stderr
, "Usage: .scanstats on|off\n");
6513 if( c
=='s' && strncmp(azArg
[0], "schema", n
)==0 ){
6517 const char *zDiv
= "(";
6518 const char *zName
= 0;
6524 memcpy(&data
, p
, sizeof(data
));
6525 data
.showHeader
= 0;
6526 data
.cMode
= data
.mode
= MODE_Semi
;
6528 for(ii
=1; ii
<nArg
; ii
++){
6529 if( optionMatch(azArg
[ii
],"indent") ){
6530 data
.cMode
= data
.mode
= MODE_Pretty
;
6531 }else if( optionMatch(azArg
[ii
],"debug") ){
6533 }else if( zName
==0 ){
6536 raw_printf(stderr
, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6538 goto meta_command_exit
;
6542 int isMaster
= sqlite3_strlike(zName
, "sqlite_master", 0)==0;
6543 if( isMaster
|| sqlite3_strlike(zName
,"sqlite_temp_master",0)==0 ){
6544 char *new_argv
[2], *new_colv
[2];
6545 new_argv
[0] = sqlite3_mprintf(
6546 "CREATE TABLE %s (\n"
6550 " rootpage integer,\n"
6552 ")", isMaster
? "sqlite_master" : "sqlite_temp_master");
6554 new_colv
[0] = "sql";
6556 callback(&data
, 1, new_argv
, new_colv
);
6557 sqlite3_free(new_argv
[0]);
6561 sqlite3_stmt
*pStmt
= 0;
6562 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
6565 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6566 sqlite3_finalize(pStmt
);
6568 goto meta_command_exit
;
6570 appendText(&sSelect
, "SELECT sql FROM", 0);
6572 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6573 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
6575 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
6576 appendText(&sSelect
, zDiv
, 0);
6577 zDiv
= " UNION ALL ";
6578 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
6579 if( sqlite3_stricmp(zDb
, "main")!=0 ){
6580 appendText(&sSelect
, zDb
, '"');
6582 appendText(&sSelect
, "NULL", 0);
6584 appendText(&sSelect
, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6585 appendText(&sSelect
, zScNum
, 0);
6586 appendText(&sSelect
, " AS snum, ", 0);
6587 appendText(&sSelect
, zDb
, '\'');
6588 appendText(&sSelect
, " AS sname FROM ", 0);
6589 appendText(&sSelect
, zDb
, '"');
6590 appendText(&sSelect
, ".sqlite_master", 0);
6592 sqlite3_finalize(pStmt
);
6593 #ifdef SQLITE_INTROSPECTION_PRAGMAS
6595 appendText(&sSelect
,
6596 " UNION ALL SELECT shell_module_schema(name),"
6597 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6600 appendText(&sSelect
, ") WHERE ", 0);
6602 char *zQarg
= sqlite3_mprintf("%Q", zName
);
6603 if( strchr(zName
, '.') ){
6604 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
6606 appendText(&sSelect
, "lower(tbl_name)", 0);
6608 appendText(&sSelect
, strchr(zName
, '*') ? " GLOB " : " LIKE ", 0);
6609 appendText(&sSelect
, zQarg
, 0);
6610 appendText(&sSelect
, " AND ", 0);
6611 sqlite3_free(zQarg
);
6613 appendText(&sSelect
, "type!='meta' AND sql IS NOT NULL"
6614 " ORDER BY snum, rowid", 0);
6616 utf8_printf(p
->out
, "SQL: %s;\n", sSelect
.z
);
6618 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
6623 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
6624 sqlite3_free(zErrMsg
);
6626 }else if( rc
!= SQLITE_OK
){
6627 raw_printf(stderr
,"Error: querying schema information\n");
6634 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6635 if( c
=='s' && n
==11 && strncmp(azArg
[0], "selecttrace", n
)==0 ){
6636 sqlite3SelectTrace
= (int)integerValue(azArg
[1]);
6640 #if defined(SQLITE_ENABLE_SESSION)
6641 if( c
=='s' && strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
6642 OpenSession
*pSession
= &p
->aSession
[0];
6643 char **azCmd
= &azArg
[1];
6645 int nCmd
= nArg
- 1;
6647 if( nArg
<=1 ) goto session_syntax_error
;
6650 for(iSes
=0; iSes
<p
->nSession
; iSes
++){
6651 if( strcmp(p
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
6653 if( iSes
<p
->nSession
){
6654 pSession
= &p
->aSession
[iSes
];
6658 pSession
= &p
->aSession
[0];
6663 /* .session attach TABLE
6664 ** Invoke the sqlite3session_attach() interface to attach a particular
6665 ** table so that it is never filtered.
6667 if( strcmp(azCmd
[0],"attach")==0 ){
6668 if( nCmd
!=2 ) goto session_syntax_error
;
6669 if( pSession
->p
==0 ){
6671 raw_printf(stderr
, "ERROR: No sessions are open\n");
6673 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
6675 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
6681 /* .session changeset FILE
6682 ** .session patchset FILE
6683 ** Write a changeset or patchset into a file. The file is overwritten.
6685 if( strcmp(azCmd
[0],"changeset")==0 || strcmp(azCmd
[0],"patchset")==0 ){
6687 if( nCmd
!=2 ) goto session_syntax_error
;
6688 if( pSession
->p
==0 ) goto session_not_open
;
6689 out
= fopen(azCmd
[1], "wb");
6691 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n", azCmd
[1]);
6695 if( azCmd
[0][0]=='c' ){
6696 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
6698 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
6701 printf("Error: error code %d\n", rc
);
6705 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
6706 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
6709 sqlite3_free(pChng
);
6715 ** Close the identified session
6717 if( strcmp(azCmd
[0], "close")==0 ){
6718 if( nCmd
!=1 ) goto session_syntax_error
;
6720 session_close(pSession
);
6721 p
->aSession
[iSes
] = p
->aSession
[--p
->nSession
];
6725 /* .session enable ?BOOLEAN?
6726 ** Query or set the enable flag
6728 if( strcmp(azCmd
[0], "enable")==0 ){
6730 if( nCmd
>2 ) goto session_syntax_error
;
6731 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
6733 ii
= sqlite3session_enable(pSession
->p
, ii
);
6734 utf8_printf(p
->out
, "session %s enable flag = %d\n",
6735 pSession
->zName
, ii
);
6739 /* .session filter GLOB ....
6740 ** Set a list of GLOB patterns of table names to be excluded.
6742 if( strcmp(azCmd
[0], "filter")==0 ){
6744 if( nCmd
<2 ) goto session_syntax_error
;
6746 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
6747 sqlite3_free(pSession
->azFilter
[ii
]);
6749 sqlite3_free(pSession
->azFilter
);
6750 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
6751 pSession
->azFilter
= sqlite3_malloc( nByte
);
6752 if( pSession
->azFilter
==0 ){
6753 raw_printf(stderr
, "Error: out or memory\n");
6756 for(ii
=1; ii
<nCmd
; ii
++){
6757 pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
6759 pSession
->nFilter
= ii
-1;
6763 /* .session indirect ?BOOLEAN?
6764 ** Query or set the indirect flag
6766 if( strcmp(azCmd
[0], "indirect")==0 ){
6768 if( nCmd
>2 ) goto session_syntax_error
;
6769 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
6771 ii
= sqlite3session_indirect(pSession
->p
, ii
);
6772 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
6773 pSession
->zName
, ii
);
6778 ** Determine if the session is empty
6780 if( strcmp(azCmd
[0], "isempty")==0 ){
6782 if( nCmd
!=1 ) goto session_syntax_error
;
6784 ii
= sqlite3session_isempty(pSession
->p
);
6785 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
6786 pSession
->zName
, ii
);
6791 ** List all currently open sessions
6793 if( strcmp(azCmd
[0],"list")==0 ){
6794 for(i
=0; i
<p
->nSession
; i
++){
6795 utf8_printf(p
->out
, "%d %s\n", i
, p
->aSession
[i
].zName
);
6799 /* .session open DB NAME
6800 ** Open a new session called NAME on the attached database DB.
6801 ** DB is normally "main".
6803 if( strcmp(azCmd
[0],"open")==0 ){
6805 if( nCmd
!=3 ) goto session_syntax_error
;
6807 if( zName
[0]==0 ) goto session_syntax_error
;
6808 for(i
=0; i
<p
->nSession
; i
++){
6809 if( strcmp(p
->aSession
[i
].zName
,zName
)==0 ){
6810 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
6811 goto meta_command_exit
;
6814 if( p
->nSession
>=ArraySize(p
->aSession
) ){
6815 raw_printf(stderr
, "Maximum of %d sessions\n", ArraySize(p
->aSession
));
6816 goto meta_command_exit
;
6818 pSession
= &p
->aSession
[p
->nSession
];
6819 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
6821 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
6823 goto meta_command_exit
;
6825 pSession
->nFilter
= 0;
6826 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
6828 pSession
->zName
= sqlite3_mprintf("%s", zName
);
6830 /* If no command name matches, show a syntax error */
6831 session_syntax_error
:
6837 /* Undocumented commands for internal testing. Subject to change
6838 ** without notice. */
6839 if( c
=='s' && n
>=10 && strncmp(azArg
[0], "selftest-", 9)==0 ){
6840 if( strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
6842 for(i
=1; i
<nArg
; i
++){
6843 v
= booleanValue(azArg
[i
]);
6844 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
6847 if( strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
6848 int i
; sqlite3_int64 v
;
6849 for(i
=1; i
<nArg
; i
++){
6851 v
= integerValue(azArg
[i
]);
6852 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
6853 utf8_printf(p
->out
, "%s", zBuf
);
6859 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"selftest",n
)==0 ){
6860 int bIsInit
= 0; /* True to initialize the SELFTEST table */
6861 int bVerbose
= 0; /* Verbose output */
6862 int bSelftestExists
; /* True if SELFTEST already exists */
6863 int i
, k
; /* Loop counters */
6864 int nTest
= 0; /* Number of tests runs */
6865 int nErr
= 0; /* Number of errors seen */
6866 ShellText str
; /* Answer for a query */
6867 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
6870 for(i
=1; i
<nArg
; i
++){
6871 const char *z
= azArg
[i
];
6872 if( z
[0]=='-' && z
[1]=='-' ) z
++;
6873 if( strcmp(z
,"-init")==0 ){
6876 if( strcmp(z
,"-v")==0 ){
6880 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
6881 azArg
[i
], azArg
[0]);
6882 raw_printf(stderr
, "Should be one of: --init -v\n");
6884 goto meta_command_exit
;
6887 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
6889 bSelftestExists
= 0;
6891 bSelftestExists
= 1;
6894 createSelftestTable(p
);
6895 bSelftestExists
= 1;
6898 appendText(&str
, "x", 0);
6899 for(k
=bSelftestExists
; k
>=0; k
--){
6901 rc
= sqlite3_prepare_v2(p
->db
,
6902 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6905 rc
= sqlite3_prepare_v2(p
->db
,
6906 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6907 " (1,'run','PRAGMA integrity_check','ok')",
6911 raw_printf(stderr
, "Error querying the selftest table\n");
6913 sqlite3_finalize(pStmt
);
6914 goto meta_command_exit
;
6916 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
6917 int tno
= sqlite3_column_int(pStmt
, 0);
6918 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
6919 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
6920 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
6924 char *zQuote
= sqlite3_mprintf("%q", zSql
);
6925 printf("%d: %s %s\n", tno
, zOp
, zSql
);
6926 sqlite3_free(zQuote
);
6928 if( strcmp(zOp
,"memo")==0 ){
6929 utf8_printf(p
->out
, "%s\n", zSql
);
6931 if( strcmp(zOp
,"run")==0 ){
6935 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
6938 utf8_printf(p
->out
, "Result: %s\n", str
.z
);
6940 if( rc
|| zErrMsg
){
6943 utf8_printf(p
->out
, "%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
6944 sqlite3_free(zErrMsg
);
6945 }else if( strcmp(zAns
,str
.z
)!=0 ){
6948 utf8_printf(p
->out
, "%d: Expected: [%s]\n", tno
, zAns
);
6949 utf8_printf(p
->out
, "%d: Got: [%s]\n", tno
, str
.z
);
6954 "Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
6958 } /* End loop over rows of content from SELFTEST */
6959 sqlite3_finalize(pStmt
);
6960 } /* End loop over k */
6962 utf8_printf(p
->out
, "%d errors out of %d tests\n", nErr
, nTest
);
6965 if( c
=='s' && strncmp(azArg
[0], "separator", n
)==0 ){
6966 if( nArg
<2 || nArg
>3 ){
6967 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
6971 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
6972 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
6975 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
6976 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
6980 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"sha3sum",n
)==0 ){
6981 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
6982 int i
; /* Loop counter */
6983 int bSchema
= 0; /* Also hash the schema */
6984 int bSeparate
= 0; /* Hash each table separately */
6985 int iSize
= 224; /* Hash algorithm to use */
6986 int bDebug
= 0; /* Only show the query that would have run */
6987 sqlite3_stmt
*pStmt
; /* For querying tables names */
6988 char *zSql
; /* SQL to be run */
6989 char *zSep
; /* Separator */
6990 ShellText sSql
; /* Complete SQL for the query to run the hash */
6991 ShellText sQuery
; /* Set of queries used to read all content */
6993 for(i
=1; i
<nArg
; i
++){
6994 const char *z
= azArg
[i
];
6997 if( z
[0]=='-' ) z
++;
6998 if( strcmp(z
,"schema")==0 ){
7001 if( strcmp(z
,"sha3-224")==0 || strcmp(z
,"sha3-256")==0
7002 || strcmp(z
,"sha3-384")==0 || strcmp(z
,"sha3-512")==0
7004 iSize
= atoi(&z
[5]);
7006 if( strcmp(z
,"debug")==0 ){
7010 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
7011 azArg
[i
], azArg
[0]);
7012 raw_printf(stderr
, "Should be one of: --schema"
7013 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
7015 goto meta_command_exit
;
7018 raw_printf(stderr
, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7020 goto meta_command_exit
;
7024 if( sqlite3_strlike("sqlite_%", zLike
, 0)==0 ) bSchema
= 1;
7028 zSql
= "SELECT lower(name) FROM sqlite_master"
7029 " WHERE type='table' AND coalesce(rootpage,0)>1"
7030 " UNION ALL SELECT 'sqlite_master'"
7031 " ORDER BY 1 collate nocase";
7033 zSql
= "SELECT lower(name) FROM sqlite_master"
7034 " WHERE type='table' AND coalesce(rootpage,0)>1"
7035 " AND name NOT LIKE 'sqlite_%'"
7036 " ORDER BY 1 collate nocase";
7038 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
7041 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
7043 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
7044 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
7045 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
7046 if( strncmp(zTab
, "sqlite_",7)!=0 ){
7047 appendText(&sQuery
,"SELECT * FROM ", 0);
7048 appendText(&sQuery
,zTab
,'"');
7049 appendText(&sQuery
," NOT INDEXED;", 0);
7050 }else if( strcmp(zTab
, "sqlite_master")==0 ){
7051 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7052 " ORDER BY name;", 0);
7053 }else if( strcmp(zTab
, "sqlite_sequence")==0 ){
7054 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
7055 " ORDER BY name;", 0);
7056 }else if( strcmp(zTab
, "sqlite_stat1")==0 ){
7057 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
7058 " ORDER BY tbl,idx;", 0);
7059 }else if( strcmp(zTab
, "sqlite_stat3")==0
7060 || strcmp(zTab
, "sqlite_stat4")==0 ){
7061 appendText(&sQuery
, "SELECT * FROM ", 0);
7062 appendText(&sQuery
, zTab
, 0);
7063 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
7065 appendText(&sSql
, zSep
, 0);
7066 appendText(&sSql
, sQuery
.z
, '\'');
7068 appendText(&sSql
, ",", 0);
7069 appendText(&sSql
, zTab
, '\'');
7072 sqlite3_finalize(pStmt
);
7074 zSql
= sqlite3_mprintf(
7076 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7077 " FROM [sha3sum$query]",
7080 zSql
= sqlite3_mprintf(
7082 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7083 " FROM [sha3sum$query]",
7089 utf8_printf(p
->out
, "%s\n", zSql
);
7091 shell_exec(p
->db
, zSql
, shell_callback
, p
, 0);
7096 #ifndef SQLITE_NOHAVE_SYSTEM
7098 && (strncmp(azArg
[0], "shell", n
)==0 || strncmp(azArg
[0],"system",n
)==0)
7103 raw_printf(stderr
, "Usage: .system COMMAND\n");
7105 goto meta_command_exit
;
7107 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
7108 for(i
=2; i
<nArg
; i
++){
7109 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
7114 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
7116 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
7118 if( c
=='s' && strncmp(azArg
[0], "show", n
)==0 ){
7119 static const char *azBool
[] = { "off", "on", "trigger", "full"};
7122 raw_printf(stderr
, "Usage: .show\n");
7124 goto meta_command_exit
;
7126 utf8_printf(p
->out
, "%12.12s: %s\n","echo",
7127 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
7128 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
7129 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
7130 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
7131 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
7132 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
7133 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
7134 output_c_string(p
->out
, p
->nullValue
);
7135 raw_printf(p
->out
, "\n");
7136 utf8_printf(p
->out
,"%12.12s: %s\n","output",
7137 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
7138 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
7139 output_c_string(p
->out
, p
->colSeparator
);
7140 raw_printf(p
->out
, "\n");
7141 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
7142 output_c_string(p
->out
, p
->rowSeparator
);
7143 raw_printf(p
->out
, "\n");
7144 utf8_printf(p
->out
, "%12.12s: %s\n","stats", azBool
[p
->statsOn
!=0]);
7145 utf8_printf(p
->out
, "%12.12s: ", "width");
7146 for (i
=0;i
<(int)ArraySize(p
->colWidth
) && p
->colWidth
[i
] != 0;i
++) {
7147 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
7149 raw_printf(p
->out
, "\n");
7150 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
7151 p
->zDbFilename
? p
->zDbFilename
: "");
7154 if( c
=='s' && strncmp(azArg
[0], "stats", n
)==0 ){
7156 p
->statsOn
= (u8
)booleanValue(azArg
[1]);
7157 }else if( nArg
==1 ){
7158 display_stats(p
->db
, p
, 0);
7160 raw_printf(stderr
, "Usage: .stats ?on|off?\n");
7165 if( (c
=='t' && n
>1 && strncmp(azArg
[0], "tables", n
)==0)
7166 || (c
=='i' && (strncmp(azArg
[0], "indices", n
)==0
7167 || strncmp(azArg
[0], "indexes", n
)==0) )
7169 sqlite3_stmt
*pStmt
;
7176 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
7177 if( rc
) return shellDatabaseError(p
->db
);
7179 if( nArg
>2 && c
=='i' ){
7180 /* It is an historical accident that the .indexes command shows an error
7181 ** when called with the wrong number of arguments whereas the .tables
7182 ** command does not. */
7183 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
7185 goto meta_command_exit
;
7187 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
7188 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
7189 if( zDbName
==0 ) continue;
7190 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
7191 if( sqlite3_stricmp(zDbName
, "main")==0 ){
7192 appendText(&s
, "SELECT name FROM ", 0);
7194 appendText(&s
, "SELECT ", 0);
7195 appendText(&s
, zDbName
, '\'');
7196 appendText(&s
, "||'.'||name FROM ", 0);
7198 appendText(&s
, zDbName
, '"');
7199 appendText(&s
, ".sqlite_master ", 0);
7201 appendText(&s
," WHERE type IN ('table','view')"
7202 " AND name NOT LIKE 'sqlite_%'"
7203 " AND name LIKE ?1", 0);
7205 appendText(&s
," WHERE type='index'"
7206 " AND tbl_name LIKE ?1", 0);
7209 rc
= sqlite3_finalize(pStmt
);
7210 appendText(&s
, " ORDER BY 1", 0);
7211 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
7213 if( rc
) return shellDatabaseError(p
->db
);
7215 /* Run the SQL statement prepared by the above block. Store the results
7216 ** as an array of nul-terminated strings in azResult[]. */
7220 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
7222 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
7224 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
7227 int n2
= nAlloc
*2 + 10;
7228 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
7230 rc
= shellNomemError();
7236 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7237 if( 0==azResult
[nRow
] ){
7238 rc
= shellNomemError();
7243 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
7244 rc
= shellDatabaseError(p
->db
);
7247 /* Pretty-print the contents of array azResult[] to the output */
7248 if( rc
==0 && nRow
>0 ){
7249 int len
, maxlen
= 0;
7251 int nPrintCol
, nPrintRow
;
7252 for(i
=0; i
<nRow
; i
++){
7253 len
= strlen30(azResult
[i
]);
7254 if( len
>maxlen
) maxlen
= len
;
7256 nPrintCol
= 80/(maxlen
+2);
7257 if( nPrintCol
<1 ) nPrintCol
= 1;
7258 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
7259 for(i
=0; i
<nPrintRow
; i
++){
7260 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
7261 char *zSp
= j
<nPrintRow
? "" : " ";
7262 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
7263 azResult
[j
] ? azResult
[j
]:"");
7265 raw_printf(p
->out
, "\n");
7269 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
7270 sqlite3_free(azResult
);
7273 /* Begin redirecting output to the file "testcase-out.txt" */
7274 if( c
=='t' && strcmp(azArg
[0],"testcase")==0 ){
7276 p
->out
= output_file_open("testcase-out.txt", 0);
7278 raw_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
7281 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
7283 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
7287 #ifndef SQLITE_UNTESTABLE
7288 if( c
=='t' && n
>=8 && strncmp(azArg
[0], "testctrl", n
)==0 ){
7289 static const struct {
7290 const char *zCtrlName
; /* Name of a test-control option */
7291 int ctrlCode
; /* Integer code for that option */
7292 const char *zUsage
; /* Usage notes */
7294 { "always", SQLITE_TESTCTRL_ALWAYS
, "BOOLEAN" },
7295 { "assert", SQLITE_TESTCTRL_ASSERT
, "BOOLEAN" },
7296 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7297 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7298 { "byteorder", SQLITE_TESTCTRL_BYTEORDER
, "" },
7299 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7300 { "imposter", SQLITE_TESTCTRL_IMPOSTER
, "SCHEMA ON/OFF ROOTPAGE"},
7301 #ifdef SQLITE_N_KEYWORD
7302 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD
, "IDENTIFIER" },
7304 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,"BOOLEAN" },
7305 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
, "BOOLEAN" },
7306 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
, "DISABLE-MASK" },
7308 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE
, "" },
7310 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
, "OFFSET " },
7311 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET
, "" },
7312 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
, "" },
7313 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, "" },
7314 { "reserve", SQLITE_TESTCTRL_RESERVE
, "BYTES-OF-RESERVE" },
7318 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7321 const char *zCmd
= 0;
7324 zCmd
= nArg
>=2 ? azArg
[1] : "help";
7326 /* The argument can optionally begin with "-" or "--" */
7327 if( zCmd
[0]=='-' && zCmd
[1] ){
7329 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
7332 /* --help lists all test-controls */
7333 if( strcmp(zCmd
,"help")==0 ){
7334 utf8_printf(p
->out
, "Available test-controls:\n");
7335 for(i
=0; i
<ArraySize(aCtrl
); i
++){
7336 utf8_printf(p
->out
, " .testctrl %s %s\n",
7337 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
7340 goto meta_command_exit
;
7343 /* convert testctrl text option to value. allow any unique prefix
7344 ** of the option name, or a numerical value. */
7345 n2
= strlen30(zCmd
);
7346 for(i
=0; i
<ArraySize(aCtrl
); i
++){
7347 if( strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
7349 testctrl
= aCtrl
[i
].ctrlCode
;
7352 utf8_printf(stderr
, "Error: ambiguous test-control: \"%s\"\n"
7353 "Use \".testctrl --help\" for help\n", zCmd
);
7355 goto meta_command_exit
;
7360 utf8_printf(stderr
,"Error: unknown test-control: %s\n"
7361 "Use \".testctrl --help\" for help\n", zCmd
);
7365 /* sqlite3_test_control(int, db, int) */
7366 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
7367 case SQLITE_TESTCTRL_RESERVE
:
7369 int opt
= (int)strtol(azArg
[2], 0, 0);
7370 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
7375 /* sqlite3_test_control(int) */
7376 case SQLITE_TESTCTRL_PRNG_SAVE
:
7377 case SQLITE_TESTCTRL_PRNG_RESTORE
:
7378 case SQLITE_TESTCTRL_PRNG_RESET
:
7379 case SQLITE_TESTCTRL_BYTEORDER
:
7381 rc2
= sqlite3_test_control(testctrl
);
7382 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
7386 /* sqlite3_test_control(int, uint) */
7387 case SQLITE_TESTCTRL_PENDING_BYTE
:
7389 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
7390 rc2
= sqlite3_test_control(testctrl
, opt
);
7395 /* sqlite3_test_control(int, int) */
7396 case SQLITE_TESTCTRL_ASSERT
:
7397 case SQLITE_TESTCTRL_ALWAYS
:
7399 int opt
= booleanValue(azArg
[2]);
7400 rc2
= sqlite3_test_control(testctrl
, opt
);
7405 /* sqlite3_test_control(int, int) */
7406 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
7407 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
7409 int opt
= booleanValue(azArg
[2]);
7410 rc2
= sqlite3_test_control(testctrl
, opt
);
7415 /* sqlite3_test_control(int, char *) */
7416 #ifdef SQLITE_N_KEYWORD
7417 case SQLITE_TESTCTRL_ISKEYWORD
:
7419 const char *opt
= azArg
[2];
7420 rc2
= sqlite3_test_control(testctrl
, opt
);
7426 case SQLITE_TESTCTRL_IMPOSTER
:
7428 rc2
= sqlite3_test_control(testctrl
, p
->db
,
7430 integerValue(azArg
[3]),
7431 integerValue(azArg
[4]));
7437 case SQLITE_TESTCTRL_PARSER_COVERAGE
:
7439 sqlite3_test_control(testctrl
, p
->out
);
7445 if( isOk
==0 && iCtrl
>=0 ){
7446 utf8_printf(p
->out
, "Usage: .testctrl %s %s\n", zCmd
, aCtrl
[iCtrl
].zUsage
);
7448 }else if( isOk
==1 ){
7449 raw_printf(p
->out
, "%d\n", rc2
);
7450 }else if( isOk
==2 ){
7451 raw_printf(p
->out
, "0x%08x\n", rc2
);
7454 #endif /* !defined(SQLITE_UNTESTABLE) */
7456 if( c
=='t' && n
>4 && strncmp(azArg
[0], "timeout", n
)==0 ){
7458 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
7461 if( c
=='t' && n
>=5 && strncmp(azArg
[0], "timer", n
)==0 ){
7463 enableTimer
= booleanValue(azArg
[1]);
7464 if( enableTimer
&& !HAS_TIMER
){
7465 raw_printf(stderr
, "Error: timer not available on this system.\n");
7469 raw_printf(stderr
, "Usage: .timer on|off\n");
7474 if( c
=='t' && strncmp(azArg
[0], "trace", n
)==0 ){
7477 raw_printf(stderr
, "Usage: .trace FILE|off\n");
7479 goto meta_command_exit
;
7481 output_file_close(p
->traceOut
);
7482 p
->traceOut
= output_file_open(azArg
[1], 0);
7483 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7484 if( p
->traceOut
==0 ){
7485 sqlite3_trace_v2(p
->db
, 0, 0, 0);
7487 sqlite3_trace_v2(p
->db
, SQLITE_TRACE_STMT
, sql_trace_callback
,p
->traceOut
);
7492 #if SQLITE_USER_AUTHENTICATION
7493 if( c
=='u' && strncmp(azArg
[0], "user", n
)==0 ){
7495 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
7497 goto meta_command_exit
;
7500 if( strcmp(azArg
[1],"login")==0 ){
7502 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
7504 goto meta_command_exit
;
7506 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]));
7508 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
7511 }else if( strcmp(azArg
[1],"add")==0 ){
7513 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
7515 goto meta_command_exit
;
7517 rc
= sqlite3_user_add(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
7518 booleanValue(azArg
[4]));
7520 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
7523 }else if( strcmp(azArg
[1],"edit")==0 ){
7525 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
7527 goto meta_command_exit
;
7529 rc
= sqlite3_user_change(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
7530 booleanValue(azArg
[4]));
7532 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
7535 }else if( strcmp(azArg
[1],"delete")==0 ){
7537 raw_printf(stderr
, "Usage: .user delete USER\n");
7539 goto meta_command_exit
;
7541 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
7543 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
7547 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
7549 goto meta_command_exit
;
7552 #endif /* SQLITE_USER_AUTHENTICATION */
7554 if( c
=='v' && strncmp(azArg
[0], "version", n
)==0 ){
7555 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
7556 sqlite3_libversion(), sqlite3_sourceid());
7557 #if SQLITE_HAVE_ZLIB
7558 utf8_printf(p
->out
, "zlib version %s\n", zlibVersion());
7560 #define CTIMEOPT_VAL_(opt) #opt
7561 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
7562 #if defined(__clang__) && defined(__clang_major__)
7563 utf8_printf(p
->out
, "clang-" CTIMEOPT_VAL(__clang_major__
) "."
7564 CTIMEOPT_VAL(__clang_minor__
) "."
7565 CTIMEOPT_VAL(__clang_patchlevel__
) "\n");
7566 #elif defined(_MSC_VER)
7567 utf8_printf(p
->out
, "msvc-" CTIMEOPT_VAL(_MSC_VER
) "\n");
7568 #elif defined(__GNUC__) && defined(__VERSION__)
7569 utf8_printf(p
->out
, "gcc-" __VERSION__
"\n");
7573 if( c
=='v' && strncmp(azArg
[0], "vfsinfo", n
)==0 ){
7574 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
7575 sqlite3_vfs
*pVfs
= 0;
7577 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
7579 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
7580 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
7581 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
7582 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
7587 if( c
=='v' && strncmp(azArg
[0], "vfslist", n
)==0 ){
7589 sqlite3_vfs
*pCurrent
= 0;
7591 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
7593 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
7594 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
7595 pVfs
==pCurrent
? " <--- CURRENT" : "");
7596 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
7597 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
7598 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
7600 raw_printf(p
->out
, "-----------------------------------\n");
7605 if( c
=='v' && strncmp(azArg
[0], "vfsname", n
)==0 ){
7606 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
7609 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
7611 utf8_printf(p
->out
, "%s\n", zVfsName
);
7612 sqlite3_free(zVfsName
);
7617 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7618 if( c
=='w' && strncmp(azArg
[0], "wheretrace", n
)==0 ){
7619 sqlite3WhereTrace
= nArg
>=2 ? booleanValue(azArg
[1]) : 0xff;
7623 if( c
=='w' && strncmp(azArg
[0], "width", n
)==0 ){
7625 assert( nArg
<=ArraySize(azArg
) );
7626 for(j
=1; j
<nArg
&& j
<ArraySize(p
->colWidth
); j
++){
7627 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
7632 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
7633 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
7640 if( p
->outCount
==0 ) output_reset(p
);
7646 ** Return TRUE if a semicolon occurs anywhere in the first N characters
7649 static int line_contains_semicolon(const char *z
, int N
){
7651 for(i
=0; i
<N
; i
++){ if( z
[i
]==';' ) return 1; }
7656 ** Test to see if a line consists entirely of whitespace.
7658 static int _all_whitespace(const char *z
){
7660 if( IsSpace(z
[0]) ) continue;
7661 if( *z
=='/' && z
[1]=='*' ){
7663 while( *z
&& (*z
!='*' || z
[1]!='/') ){ z
++; }
7664 if( *z
==0 ) return 0;
7668 if( *z
=='-' && z
[1]=='-' ){
7670 while( *z
&& *z
!='\n' ){ z
++; }
7671 if( *z
==0 ) return 1;
7680 ** Return TRUE if the line typed in is an SQL command terminator other
7681 ** than a semi-colon. The SQL Server style "go" command is understood
7682 ** as is the Oracle "/".
7684 static int line_is_command_terminator(const char *zLine
){
7685 while( IsSpace(zLine
[0]) ){ zLine
++; };
7686 if( zLine
[0]=='/' && _all_whitespace(&zLine
[1]) ){
7687 return 1; /* Oracle */
7689 if( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o'
7690 && _all_whitespace(&zLine
[2]) ){
7691 return 1; /* SQL Server */
7697 ** We need a default sqlite3_complete() implementation to use in case
7698 ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
7699 ** any arbitrary text is a complete SQL statement. This is not very
7700 ** user-friendly, but it does seem to work.
7702 #ifdef SQLITE_OMIT_COMPLETE
7703 int sqlite3_complete(const char *zSql
){ return 1; }
7707 ** Return true if zSql is a complete SQL statement. Return false if it
7708 ** ends in the middle of a string literal or C-style comment.
7710 static int line_is_complete(char *zSql
, int nSql
){
7712 if( zSql
==0 ) return 1;
7715 rc
= sqlite3_complete(zSql
);
7721 ** Run a single line of SQL
7723 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
7728 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
7730 rc
= shell_exec(p
->db
, zSql
, shell_callback
, p
, &zErrMsg
);
7732 if( rc
|| zErrMsg
){
7734 if( in
!=0 || !stdin_is_interactive
){
7735 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
7736 "Error: near line %d:", startline
);
7738 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "Error:");
7741 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrMsg
);
7742 sqlite3_free(zErrMsg
);
7745 utf8_printf(stderr
, "%s %s\n", zPrefix
, sqlite3_errmsg(p
->db
));
7748 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
7749 raw_printf(p
->out
, "changes: %3d total_changes: %d\n",
7750 sqlite3_changes(p
->db
), sqlite3_total_changes(p
->db
));
7757 ** Read input from *in and process it. If *in==0 then input
7758 ** is interactive - the user is typing it it. Otherwise, input
7759 ** is coming from a file or device. A prompt is issued and history
7760 ** is saved only if input is interactive. An interrupt signal will
7761 ** cause this routine to exit immediately, unless input is interactive.
7763 ** Return the number of errors.
7765 static int process_input(ShellState
*p
, FILE *in
){
7766 char *zLine
= 0; /* A single input line */
7767 char *zSql
= 0; /* Accumulated SQL text */
7768 int nLine
; /* Length of current line */
7769 int nSql
= 0; /* Bytes of zSql[] used */
7770 int nAlloc
= 0; /* Allocated zSql[] space */
7771 int nSqlPrior
= 0; /* Bytes of zSql[] used by prior line */
7772 int rc
; /* Error code */
7773 int errCnt
= 0; /* Number of errors seen */
7774 int lineno
= 0; /* Current line number */
7775 int startline
= 0; /* Line number for start of current input */
7777 while( errCnt
==0 || !bail_on_error
|| (in
==0 && stdin_is_interactive
) ){
7779 zLine
= one_input_line(in
, zLine
, nSql
>0);
7782 if( in
==0 && stdin_is_interactive
) printf("\n");
7785 if( seenInterrupt
){
7790 if( nSql
==0 && _all_whitespace(zLine
) ){
7791 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
7794 if( zLine
&& zLine
[0]=='.' && nSql
==0 ){
7795 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
7796 rc
= do_meta_command(zLine
, p
);
7797 if( rc
==2 ){ /* exit requested */
7804 if( line_is_command_terminator(zLine
) && line_is_complete(zSql
, nSql
) ){
7805 memcpy(zLine
,";",2);
7807 nLine
= strlen30(zLine
);
7808 if( nSql
+nLine
+2>=nAlloc
){
7809 nAlloc
= nSql
+nLine
+100;
7810 zSql
= realloc(zSql
, nAlloc
);
7812 raw_printf(stderr
, "Error: out of memory\n");
7819 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
7820 assert( nAlloc
>0 && zSql
!=0 );
7821 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
7825 zSql
[nSql
++] = '\n';
7826 memcpy(zSql
+nSql
, zLine
, nLine
+1);
7829 if( nSql
&& line_contains_semicolon(&zSql
[nSqlPrior
], nSql
-nSqlPrior
)
7830 && sqlite3_complete(zSql
) ){
7831 errCnt
+= runOneSqlLine(p
, zSql
, in
, startline
);
7839 }else if( nSql
&& _all_whitespace(zSql
) ){
7840 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zSql
);
7844 if( nSql
&& !_all_whitespace(zSql
) ){
7845 runOneSqlLine(p
, zSql
, in
, startline
);
7853 ** Return a pathname which is the user's home directory. A
7854 ** 0 return indicates an error of some kind.
7856 static char *find_home_dir(int clearFlag
){
7857 static char *home_dir
= NULL
;
7863 if( home_dir
) return home_dir
;
7865 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7866 && !defined(__RTP__) && !defined(_WRS_KERNEL)
7868 struct passwd
*pwent
;
7869 uid_t uid
= getuid();
7870 if( (pwent
=getpwuid(uid
)) != NULL
) {
7871 home_dir
= pwent
->pw_dir
;
7876 #if defined(_WIN32_WCE)
7877 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7882 #if defined(_WIN32) || defined(WIN32)
7884 home_dir
= getenv("USERPROFILE");
7889 home_dir
= getenv("HOME");
7892 #if defined(_WIN32) || defined(WIN32)
7894 char *zDrive
, *zPath
;
7896 zDrive
= getenv("HOMEDRIVE");
7897 zPath
= getenv("HOMEPATH");
7898 if( zDrive
&& zPath
){
7899 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
7900 home_dir
= malloc( n
);
7901 if( home_dir
==0 ) return 0;
7902 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
7909 #endif /* !_WIN32_WCE */
7912 int n
= strlen30(home_dir
) + 1;
7913 char *z
= malloc( n
);
7914 if( z
) memcpy(z
, home_dir
, n
);
7922 ** Read input from the file given by sqliterc_override. Or if that
7923 ** parameter is NULL, take input from ~/.sqliterc
7925 ** Returns the number of errors.
7927 static void process_sqliterc(
7928 ShellState
*p
, /* Configuration data */
7929 const char *sqliterc_override
/* Name of config file. NULL to use default */
7931 char *home_dir
= NULL
;
7932 const char *sqliterc
= sqliterc_override
;
7936 if (sqliterc
== NULL
) {
7937 home_dir
= find_home_dir(0);
7939 raw_printf(stderr
, "-- warning: cannot find home directory;"
7940 " cannot read ~/.sqliterc\n");
7943 sqlite3_initialize();
7944 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
7947 in
= fopen(sqliterc
,"rb");
7949 if( stdin_is_interactive
){
7950 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
7952 process_input(p
,in
);
7959 ** Show available command line options
7961 static const char zOptions
[] =
7962 " -ascii set output mode to 'ascii'\n"
7963 " -bail stop after hitting an error\n"
7964 " -batch force batch I/O\n"
7965 " -column set output mode to 'column'\n"
7966 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
7967 " -csv set output mode to 'csv'\n"
7968 " -echo print commands before execution\n"
7969 " -init FILENAME read/process named file\n"
7970 " -[no]header turn headers on or off\n"
7971 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7972 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7974 " -help show this message\n"
7975 " -html set output mode to HTML\n"
7976 " -interactive force interactive I/O\n"
7977 " -line set output mode to 'line'\n"
7978 " -list set output mode to 'list'\n"
7979 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
7980 " -mmap N default mmap size set to N\n"
7981 #ifdef SQLITE_ENABLE_MULTIPLEX
7982 " -multiplex enable the multiplexor VFS\n"
7984 " -newline SEP set output row separator. Default: '\\n'\n"
7985 " -nullvalue TEXT set text string for NULL values. Default ''\n"
7986 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7987 " -quote set output mode to 'quote'\n"
7988 " -separator SEP set output column separator. Default: '|'\n"
7989 " -stats print memory stats before each finalize\n"
7990 " -version show SQLite version\n"
7991 " -vfs NAME use NAME as the default VFS\n"
7992 #ifdef SQLITE_ENABLE_VFSTRACE
7993 " -vfstrace enable tracing of all VFS calls\n"
7996 static void usage(int showDetail
){
7998 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
7999 "FILENAME is the name of an SQLite database. A new database is created\n"
8000 "if the file does not previously exist.\n", Argv0
);
8002 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
8004 raw_printf(stderr
, "Use the -help option for additional information\n");
8010 ** Initialize the state information in data
8012 static void main_init(ShellState
*data
) {
8013 memset(data
, 0, sizeof(*data
));
8014 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
8015 data
->autoExplain
= 1;
8016 memcpy(data
->colSeparator
,SEP_Column
, 2);
8017 memcpy(data
->rowSeparator
,SEP_Row
, 2);
8018 data
->showHeader
= 0;
8019 data
->shellFlgs
= SHFLG_Lookaside
;
8020 sqlite3_config(SQLITE_CONFIG_URI
, 1);
8021 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
8022 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
8023 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
8024 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
8028 ** Output text to the console in a font that attracts extra attention.
8031 static void printBold(const char *zText
){
8032 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
8033 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
8034 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
8035 SetConsoleTextAttribute(out
,
8036 FOREGROUND_RED
|FOREGROUND_INTENSITY
8038 printf("%s", zText
);
8039 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
8042 static void printBold(const char *zText
){
8043 printf("\033[1m%s\033[0m", zText
);
8048 ** Get the argument to an --option. Throw an error and die if no argument
8051 static char *cmdline_option_value(int argc
, char **argv
, int i
){
8053 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
8054 argv
[0], argv
[argc
-1]);
8060 #ifndef SQLITE_SHELL_IS_UTF8
8061 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8062 # define SQLITE_SHELL_IS_UTF8 (0)
8064 # define SQLITE_SHELL_IS_UTF8 (1)
8068 #if SQLITE_SHELL_IS_UTF8
8069 int SQLITE_CDECL
main(int argc
, char **argv
){
8071 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
8076 const char *zInitFile
= 0;
8079 int warnInmemoryDb
= 0;
8084 setBinaryMode(stdin
, 0);
8085 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
8086 stdin_is_interactive
= isatty(0);
8087 stdout_is_console
= isatty(1);
8089 #if USE_SYSTEM_SQLITE+0!=1
8090 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
8091 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
8092 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
8097 sqlite3_initialize();
8098 #if !SQLITE_SHELL_IS_UTF8
8099 argv
= sqlite3_malloc64(sizeof(argv
[0])*argc
);
8101 raw_printf(stderr
, "out of memory\n");
8104 for(i
=0; i
<argc
; i
++){
8105 argv
[i
] = sqlite3_win32_unicode_to_utf8(wargv
[i
]);
8107 raw_printf(stderr
, "out of memory\n");
8112 assert( argc
>=1 && argv
&& argv
[0] );
8115 /* Make sure we have a valid signal handler early, before anything
8119 signal(SIGINT
, interrupt_handler
);
8120 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
8121 SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
);
8124 #ifdef SQLITE_SHELL_DBNAME_PROC
8126 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8127 ** of a C-function that will provide the name of the database file. Use
8128 ** this compile-time option to embed this shell program in larger
8130 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8131 SQLITE_SHELL_DBNAME_PROC(&data
.zDbFilename
);
8136 /* Do an initial pass through the command-line argument to locate
8137 ** the name of the database file, the name of the initialization file,
8138 ** the size of the alternative malloc heap,
8139 ** and the first command to execute.
8141 for(i
=1; i
<argc
; i
++){
8145 if( data
.zDbFilename
==0 ){
8146 data
.zDbFilename
= z
;
8148 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8149 ** mean that nothing is read from stdin */
8152 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
8154 raw_printf(stderr
, "out of memory\n");
8160 if( z
[1]=='-' ) z
++;
8161 if( strcmp(z
,"-separator")==0
8162 || strcmp(z
,"-nullvalue")==0
8163 || strcmp(z
,"-newline")==0
8164 || strcmp(z
,"-cmd")==0
8166 (void)cmdline_option_value(argc
, argv
, ++i
);
8167 }else if( strcmp(z
,"-init")==0 ){
8168 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
8169 }else if( strcmp(z
,"-batch")==0 ){
8170 /* Need to check for batch mode here to so we can avoid printing
8171 ** informational messages (like from process_sqliterc) before
8172 ** we do the actual processing of arguments later in a second pass.
8174 stdin_is_interactive
= 0;
8175 }else if( strcmp(z
,"-heap")==0 ){
8176 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8178 sqlite3_int64 szHeap
;
8180 zSize
= cmdline_option_value(argc
, argv
, ++i
);
8181 szHeap
= integerValue(zSize
);
8182 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
8183 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
8185 (void)cmdline_option_value(argc
, argv
, ++i
);
8187 }else if( strcmp(z
,"-pagecache")==0 ){
8189 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8190 if( sz
>70000 ) sz
= 70000;
8192 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8193 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
8194 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
8195 data
.shellFlgs
|= SHFLG_Pagecache
;
8196 }else if( strcmp(z
,"-lookaside")==0 ){
8198 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8200 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8202 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
8203 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
8204 #ifdef SQLITE_ENABLE_VFSTRACE
8205 }else if( strcmp(z
,"-vfstrace")==0 ){
8206 extern int vfstrace_register(
8207 const char *zTraceName
,
8208 const char *zOldVfsName
,
8209 int (*xOut
)(const char*,void*),
8213 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
8215 #ifdef SQLITE_ENABLE_MULTIPLEX
8216 }else if( strcmp(z
,"-multiplex")==0 ){
8217 extern int sqlite3_multiple_initialize(const char*,int);
8218 sqlite3_multiplex_initialize(0, 1);
8220 }else if( strcmp(z
,"-mmap")==0 ){
8221 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
8222 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
8223 }else if( strcmp(z
,"-vfs")==0 ){
8224 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(cmdline_option_value(argc
,argv
,++i
));
8226 sqlite3_vfs_register(pVfs
, 1);
8228 utf8_printf(stderr
, "no such VFS: \"%s\"\n", argv
[i
]);
8231 #ifdef SQLITE_HAVE_ZIP
8232 }else if( strcmp(z
,"-zip")==0 ){
8233 data
.openMode
= SHELL_OPEN_ZIPFILE
;
8235 }else if( strcmp(z
,"-append")==0 ){
8236 data
.openMode
= SHELL_OPEN_APPENDVFS
;
8239 if( data
.zDbFilename
==0 ){
8240 #ifndef SQLITE_OMIT_MEMORYDB
8241 data
.zDbFilename
= ":memory:";
8242 warnInmemoryDb
= argc
==1;
8244 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
8249 sqlite3_appendvfs_init(0,0,0);
8251 /* Go ahead and open the database file if it already exists. If the
8252 ** file does not exist, delay opening it. This prevents empty database
8253 ** files from being created if a user mistypes the database name argument
8254 ** to the sqlite command-line tool.
8256 if( access(data
.zDbFilename
, 0)==0 ){
8260 /* Process the initialization file if there is one. If no -init option
8261 ** is given on the command line, look for a file named ~/.sqliterc and
8262 ** try to process it.
8264 process_sqliterc(&data
,zInitFile
);
8266 /* Make a second pass through the command-line argument and set
8267 ** options. This second pass is delayed until after the initialization
8268 ** file is processed so that the command-line arguments will override
8269 ** settings in the initialization file.
8271 for(i
=1; i
<argc
; i
++){
8273 if( z
[0]!='-' ) continue;
8274 if( z
[1]=='-' ){ z
++; }
8275 if( strcmp(z
,"-init")==0 ){
8277 }else if( strcmp(z
,"-html")==0 ){
8278 data
.mode
= MODE_Html
;
8279 }else if( strcmp(z
,"-list")==0 ){
8280 data
.mode
= MODE_List
;
8281 }else if( strcmp(z
,"-quote")==0 ){
8282 data
.mode
= MODE_Quote
;
8283 }else if( strcmp(z
,"-line")==0 ){
8284 data
.mode
= MODE_Line
;
8285 }else if( strcmp(z
,"-column")==0 ){
8286 data
.mode
= MODE_Column
;
8287 }else if( strcmp(z
,"-csv")==0 ){
8288 data
.mode
= MODE_Csv
;
8289 memcpy(data
.colSeparator
,",",2);
8290 #ifdef SQLITE_HAVE_ZIP
8291 }else if( strcmp(z
,"-zip")==0 ){
8292 data
.openMode
= SHELL_OPEN_ZIPFILE
;
8294 }else if( strcmp(z
,"-append")==0 ){
8295 data
.openMode
= SHELL_OPEN_APPENDVFS
;
8296 }else if( strcmp(z
,"-ascii")==0 ){
8297 data
.mode
= MODE_Ascii
;
8298 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
8300 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
8302 }else if( strcmp(z
,"-separator")==0 ){
8303 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
8304 "%s",cmdline_option_value(argc
,argv
,++i
));
8305 }else if( strcmp(z
,"-newline")==0 ){
8306 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
8307 "%s",cmdline_option_value(argc
,argv
,++i
));
8308 }else if( strcmp(z
,"-nullvalue")==0 ){
8309 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
8310 "%s",cmdline_option_value(argc
,argv
,++i
));
8311 }else if( strcmp(z
,"-header")==0 ){
8312 data
.showHeader
= 1;
8313 }else if( strcmp(z
,"-noheader")==0 ){
8314 data
.showHeader
= 0;
8315 }else if( strcmp(z
,"-echo")==0 ){
8316 ShellSetFlag(&data
, SHFLG_Echo
);
8317 }else if( strcmp(z
,"-eqp")==0 ){
8318 data
.autoEQP
= AUTOEQP_on
;
8319 }else if( strcmp(z
,"-eqpfull")==0 ){
8320 data
.autoEQP
= AUTOEQP_full
;
8321 }else if( strcmp(z
,"-stats")==0 ){
8323 }else if( strcmp(z
,"-scanstats")==0 ){
8324 data
.scanstatsOn
= 1;
8325 }else if( strcmp(z
,"-backslash")==0 ){
8326 /* Undocumented command-line option: -backslash
8327 ** Causes C-style backslash escapes to be evaluated in SQL statements
8328 ** prior to sending the SQL into SQLite. Useful for injecting
8329 ** crazy bytes in the middle of SQL statements for testing and debugging.
8331 ShellSetFlag(&data
, SHFLG_Backslash
);
8332 }else if( strcmp(z
,"-bail")==0 ){
8334 }else if( strcmp(z
,"-version")==0 ){
8335 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8337 }else if( strcmp(z
,"-interactive")==0 ){
8338 stdin_is_interactive
= 1;
8339 }else if( strcmp(z
,"-batch")==0 ){
8340 stdin_is_interactive
= 0;
8341 }else if( strcmp(z
,"-heap")==0 ){
8343 }else if( strcmp(z
,"-pagecache")==0 ){
8345 }else if( strcmp(z
,"-lookaside")==0 ){
8347 }else if( strcmp(z
,"-mmap")==0 ){
8349 }else if( strcmp(z
,"-vfs")==0 ){
8351 #ifdef SQLITE_ENABLE_VFSTRACE
8352 }else if( strcmp(z
,"-vfstrace")==0 ){
8355 #ifdef SQLITE_ENABLE_MULTIPLEX
8356 }else if( strcmp(z
,"-multiplex")==0 ){
8359 }else if( strcmp(z
,"-help")==0 ){
8361 }else if( strcmp(z
,"-cmd")==0 ){
8362 /* Run commands that follow -cmd first and separately from commands
8363 ** that simply appear on the command-line. This seems goofy. It would
8364 ** be better if all commands ran in the order that they appear. But
8365 ** we retain the goofy behavior for historical compatibility. */
8366 if( i
==argc
-1 ) break;
8367 z
= cmdline_option_value(argc
,argv
,++i
);
8369 rc
= do_meta_command(z
, &data
);
8370 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
8373 rc
= shell_exec(data
.db
, z
, shell_callback
, &data
, &zErrMsg
);
8375 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
8376 if( bail_on_error
) return rc
!=0 ? rc
: 1;
8378 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
8379 if( bail_on_error
) return rc
;
8383 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
8384 raw_printf(stderr
,"Use -help for a list of options.\n");
8387 data
.cMode
= data
.mode
;
8391 /* Run all arguments that do not begin with '-' as if they were separate
8392 ** command-line inputs, except for the argToSkip argument which contains
8393 ** the database filename.
8395 for(i
=0; i
<nCmd
; i
++){
8396 if( azCmd
[i
][0]=='.' ){
8397 rc
= do_meta_command(azCmd
[i
], &data
);
8398 if( rc
) return rc
==2 ? 0 : rc
;
8401 rc
= shell_exec(data
.db
, azCmd
[i
], shell_callback
, &data
, &zErrMsg
);
8403 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
8404 return rc
!=0 ? rc
: 1;
8406 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
8413 /* Run commands received from standard input
8415 if( stdin_is_interactive
){
8420 "SQLite version %s %.19s\n" /*extra-version-info*/
8421 "Enter \".help\" for usage hints.\n",
8422 sqlite3_libversion(), sqlite3_sourceid()
8424 if( warnInmemoryDb
){
8425 printf("Connected to a ");
8426 printBold("transient in-memory database");
8427 printf(".\nUse \".open FILENAME\" to reopen on a "
8428 "persistent database.\n");
8430 zHome
= find_home_dir(0);
8432 nHistory
= strlen30(zHome
) + 20;
8433 if( (zHistory
= malloc(nHistory
))!=0 ){
8434 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
8437 if( zHistory
){ shell_read_history(zHistory
); }
8438 #if HAVE_READLINE || HAVE_EDITLINE
8439 rl_attempted_completion_function
= readline_completion
;
8440 #elif HAVE_LINENOISE
8441 linenoiseSetCompletionCallback(linenoise_completion
);
8443 rc
= process_input(&data
, 0);
8445 shell_stifle_history(2000);
8446 shell_write_history(zHistory
);
8450 rc
= process_input(&data
, stdin
);
8453 set_table_name(&data
, 0);
8455 session_close_all(&data
);
8456 sqlite3_close(data
.db
);
8458 sqlite3_free(data
.zFreeOnClose
);
8460 output_reset(&data
);
8462 clearTempFile(&data
);
8463 #if !SQLITE_SHELL_IS_UTF8
8464 for(i
=0; i
<argc
; i
++) sqlite3_free(argv
[i
]);