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
);
869 sqlite3_result_text(pCtx
, sqlite3_mprintf("/* %s */", zFake
),
876 ** SQL function: shell_add_schema(S,X)
878 ** Add the schema name X to the CREATE statement in S and return the result.
881 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
886 ** CREATE UNIQUE INDEX
889 ** CREATE VIRTUAL TABLE
891 ** This UDF is used by the .schema command to insert the schema name of
892 ** attached databases into the middle of the sqlite_master.sql field.
894 static void shellAddSchemaName(
895 sqlite3_context
*pCtx
,
897 sqlite3_value
**apVal
899 static const char *aPrefix
[] = {
908 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
909 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
910 const char *zName
= (const char*)sqlite3_value_text(apVal
[2]);
911 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
912 if( zIn
!=0 && strncmp(zIn
, "CREATE ", 7)==0 ){
913 for(i
=0; i
<(int)(sizeof(aPrefix
)/sizeof(aPrefix
[0])); i
++){
914 int n
= strlen30(aPrefix
[i
]);
915 if( strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
919 char cQuote
= quoteChar(zSchema
);
920 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")!=0 ){
921 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
923 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
927 && aPrefix
[i
][0]=='V'
928 && (zFake
= shellFakeSchema(db
, zSchema
, zName
))!=0
931 z
= sqlite3_mprintf("%s\n/* %s */", zIn
, zFake
);
933 z
= sqlite3_mprintf("%z\n/* %s */", z
, zFake
);
938 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
944 sqlite3_result_value(pCtx
, apVal
[0]);
948 ** The source code for several run-time loadable extensions is inserted
949 ** below by the ../tool/mkshellc.tcl script. Before processing that included
950 ** code, we need to override some macros to make the included program code
951 ** work here in the middle of this regular program.
953 #define SQLITE_EXTENSION_INIT1
954 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
956 #if defined(_WIN32) && defined(_MSC_VER)
957 INCLUDE test_windirent
.h
958 INCLUDE test_windirent
.c
959 #define dirent DIRENT
961 INCLUDE
../ext
/misc
/shathree
.c
962 INCLUDE
../ext
/misc
/fileio
.c
963 INCLUDE
../ext
/misc
/completion
.c
964 INCLUDE
../ext
/misc
/appendvfs
.c
965 #ifdef SQLITE_HAVE_ZLIB
966 INCLUDE
../ext
/misc
/zipfile
.c
967 INCLUDE
../ext
/misc
/sqlar
.c
969 INCLUDE
../ext
/expert
/sqlite3expert
.h
970 INCLUDE
../ext
/expert
/sqlite3expert
.c
972 #if defined(SQLITE_ENABLE_SESSION)
974 ** State information for a single open session
976 typedef struct OpenSession OpenSession
;
978 char *zName
; /* Symbolic name for this session */
979 int nFilter
; /* Number of xFilter rejection GLOB patterns */
980 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
981 sqlite3_session
*p
; /* The open session */
986 ** Shell output mode information from before ".explain on",
987 ** saved so that it can be restored by ".explain off"
989 typedef struct SavedModeInfo SavedModeInfo
;
990 struct SavedModeInfo
{
991 int valid
; /* Is there legit data in here? */
992 int mode
; /* Mode prior to ".explain on" */
993 int showHeader
; /* The ".header" setting prior to ".explain on" */
994 int colWidth
[100]; /* Column widths prior to ".explain on" */
997 typedef struct ExpertInfo ExpertInfo
;
999 sqlite3expert
*pExpert
;
1004 ** State information about the database connection is contained in an
1005 ** instance of the following structure.
1007 typedef struct ShellState ShellState
;
1009 sqlite3
*db
; /* The database */
1010 u8 autoExplain
; /* Automatically turn on .explain mode */
1011 u8 autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1012 u8 statsOn
; /* True to display memory stats before each finalize */
1013 u8 scanstatsOn
; /* True to display scan stats before each finalize */
1014 u8 openMode
; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1015 int outCount
; /* Revert to stdout when reaching zero */
1016 int cnt
; /* Number of records displayed so far */
1017 FILE *out
; /* Write results here */
1018 FILE *traceOut
; /* Output for sqlite3_trace() */
1019 int nErr
; /* Number of errors seen */
1020 int mode
; /* An output mode setting */
1021 int cMode
; /* temporary output mode for the current query */
1022 int normalMode
; /* Output mode before ".explain on" */
1023 int writableSchema
; /* True if PRAGMA writable_schema=ON */
1024 int showHeader
; /* True to show column names in List or Column mode */
1025 int nCheck
; /* Number of ".check" commands run */
1026 unsigned shellFlgs
; /* Various flags */
1027 char *zDestTable
; /* Name of destination table when MODE_Insert */
1028 char zTestcase
[30]; /* Name of current test case */
1029 char colSeparator
[20]; /* Column separator character for several modes */
1030 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
1031 int colWidth
[100]; /* Requested width of each column when in column mode*/
1032 int actualWidth
[100]; /* Actual width of each column */
1033 char nullValue
[20]; /* The text to print when a NULL comes back from
1035 char outfile
[FILENAME_MAX
]; /* Filename for *out */
1036 const char *zDbFilename
; /* name of the database file */
1037 char *zFreeOnClose
; /* Filename to free when closing */
1038 const char *zVfs
; /* Name of VFS to use */
1039 sqlite3_stmt
*pStmt
; /* Current statement if any. */
1040 FILE *pLog
; /* Write log output here */
1041 int *aiIndent
; /* Array of indents used in MODE_Explain */
1042 int nIndent
; /* Size of array aiIndent[] */
1043 int iIndent
; /* Index of current op in aiIndent[] */
1044 #if defined(SQLITE_ENABLE_SESSION)
1045 int nSession
; /* Number of active sessions */
1046 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
1048 ExpertInfo expert
; /* Valid if previous command was ".expert OPT..." */
1052 /* Allowed values for ShellState.autoEQP
1054 #define AUTOEQP_off 0
1055 #define AUTOEQP_on 1
1056 #define AUTOEQP_trigger 2
1057 #define AUTOEQP_full 3
1059 /* Allowed values for ShellState.openMode
1061 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1062 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1063 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1064 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1067 ** These are the allowed shellFlgs values
1069 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1070 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1071 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1072 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1073 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1074 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1075 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1078 ** Macros for testing and setting shellFlgs
1080 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1081 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1082 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1085 ** These are the allowed modes.
1087 #define MODE_Line 0 /* One column per line. Blank line between records */
1088 #define MODE_Column 1 /* One record per line in neat columns */
1089 #define MODE_List 2 /* One record per line with a separator */
1090 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1091 #define MODE_Html 4 /* Generate an XHTML table */
1092 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1093 #define MODE_Quote 6 /* Quote values as for SQL */
1094 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1095 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1096 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1097 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1098 #define MODE_Pretty 11 /* Pretty-print schemas */
1100 static const char *modeDescr
[] = {
1116 ** These are the column/row/line separators used by the various
1117 ** import/export modes.
1119 #define SEP_Column "|"
1120 #define SEP_Row "\n"
1121 #define SEP_Tab "\t"
1122 #define SEP_Space " "
1123 #define SEP_Comma ","
1124 #define SEP_CrLf "\r\n"
1125 #define SEP_Unit "\x1F"
1126 #define SEP_Record "\x1E"
1129 ** A callback for the sqlite3_log() interface.
1131 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
1132 ShellState
*p
= (ShellState
*)pArg
;
1133 if( p
->pLog
==0 ) return;
1134 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
1139 ** SQL function: shell_putsnl(X)
1141 ** Write the text X to the screen (or whatever output is being directed)
1142 ** adding a newline at the end, and then return X.
1144 static void shellPutsFunc(
1145 sqlite3_context
*pCtx
,
1147 sqlite3_value
**apVal
1149 ShellState
*p
= (ShellState
*)sqlite3_user_data(pCtx
);
1150 utf8_printf(p
->out
, "%s\n", sqlite3_value_text(apVal
[0]));
1151 sqlite3_result_value(pCtx
, apVal
[0]);
1155 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1157 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
1159 char *zBlob
= (char *)pBlob
;
1160 raw_printf(out
,"X'");
1161 for(i
=0; i
<nBlob
; i
++){ raw_printf(out
,"%02x",zBlob
[i
]&0xff); }
1162 raw_printf(out
,"'");
1166 ** Find a string that is not found anywhere in z[]. Return a pointer
1169 ** Try to use zA and zB first. If both of those are already found in z[]
1170 ** then make up some string and store it in the buffer zBuf.
1172 static const char *unused_string(
1173 const char *z
, /* Result must not appear anywhere in z */
1174 const char *zA
, const char *zB
, /* Try these first */
1175 char *zBuf
/* Space to store a generated string */
1178 if( strstr(z
, zA
)==0 ) return zA
;
1179 if( strstr(z
, zB
)==0 ) return zB
;
1181 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
1182 }while( strstr(z
,zBuf
)!=0 );
1187 ** Output the given string as a quoted string using SQL quoting conventions.
1189 ** See also: output_quoted_escaped_string()
1191 static void output_quoted_string(FILE *out
, const char *z
){
1194 setBinaryMode(out
, 1);
1195 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1197 utf8_printf(out
,"'%s'",z
);
1199 raw_printf(out
, "'");
1201 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1204 utf8_printf(out
, "%.*s", i
, z
);
1208 raw_printf(out
, "'");
1216 raw_printf(out
, "'");
1218 setTextMode(out
, 1);
1222 ** Output the given string as a quoted string using SQL quoting conventions.
1223 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1224 ** get corrupted by end-of-line translation facilities in some operating
1227 ** This is like output_quoted_string() but with the addition of the \r\n
1228 ** escape mechanism.
1230 static void output_quoted_escaped_string(FILE *out
, const char *z
){
1233 setBinaryMode(out
, 1);
1234 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1236 utf8_printf(out
,"'%s'",z
);
1238 const char *zNL
= 0;
1239 const char *zCR
= 0;
1242 char zBuf1
[20], zBuf2
[20];
1243 for(i
=0; z
[i
]; i
++){
1244 if( z
[i
]=='\n' ) nNL
++;
1245 if( z
[i
]=='\r' ) nCR
++;
1248 raw_printf(out
, "replace(");
1249 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1252 raw_printf(out
, "replace(");
1253 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1255 raw_printf(out
, "'");
1257 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1260 utf8_printf(out
, "%.*s", i
, z
);
1264 raw_printf(out
, "'");
1272 raw_printf(out
, "%s", zNL
);
1275 raw_printf(out
, "%s", zCR
);
1277 raw_printf(out
, "'");
1279 raw_printf(out
, ",'%s',char(13))", zCR
);
1282 raw_printf(out
, ",'%s',char(10))", zNL
);
1285 setTextMode(out
, 1);
1289 ** Output the given string as a quoted according to C or TCL quoting rules.
1291 static void output_c_string(FILE *out
, const char *z
){
1294 while( (c
= *(z
++))!=0 ){
1301 }else if( c
=='\t' ){
1304 }else if( c
=='\n' ){
1307 }else if( c
=='\r' ){
1310 }else if( !isprint(c
&0xff) ){
1311 raw_printf(out
, "\\%03o", c
&0xff);
1320 ** Output the given string with characters that are special to
1323 static void output_html_string(FILE *out
, const char *z
){
1335 utf8_printf(out
,"%.*s",i
,z
);
1338 raw_printf(out
,"<");
1339 }else if( z
[i
]=='&' ){
1340 raw_printf(out
,"&");
1341 }else if( z
[i
]=='>' ){
1342 raw_printf(out
,">");
1343 }else if( z
[i
]=='\"' ){
1344 raw_printf(out
,""");
1345 }else if( z
[i
]=='\'' ){
1346 raw_printf(out
,"'");
1355 ** If a field contains any character identified by a 1 in the following
1356 ** array, then the string must be quoted for CSV.
1358 static const char needCsvQuote
[] = {
1359 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1360 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1361 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1362 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1363 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1364 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1365 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1366 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1367 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1368 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1369 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1370 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1371 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1372 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1373 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1374 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1378 ** Output a single term of CSV. Actually, p->colSeparator is used for
1379 ** the separator, which may or may not be a comma. p->nullValue is
1380 ** the null value. Strings are quoted if necessary. The separator
1381 ** is only issued if bSep is true.
1383 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
1386 utf8_printf(out
,"%s",p
->nullValue
);
1389 int nSep
= strlen30(p
->colSeparator
);
1390 for(i
=0; z
[i
]; i
++){
1391 if( needCsvQuote
[((unsigned char*)z
)[i
]]
1392 || (z
[i
]==p
->colSeparator
[0] &&
1393 (nSep
==1 || memcmp(z
, p
->colSeparator
, nSep
)==0)) ){
1399 char *zQuoted
= sqlite3_mprintf("\"%w\"", z
);
1400 utf8_printf(out
, "%s", zQuoted
);
1401 sqlite3_free(zQuoted
);
1403 utf8_printf(out
, "%s", z
);
1407 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1412 ** This routine runs when the user presses Ctrl-C
1414 static void interrupt_handler(int NotUsed
){
1415 UNUSED_PARAMETER(NotUsed
);
1417 if( seenInterrupt
>2 ) exit(1);
1418 if( globalDb
) sqlite3_interrupt(globalDb
);
1421 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1423 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1425 static BOOL WINAPI
ConsoleCtrlHandler(
1426 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
1428 if( dwCtrlType
==CTRL_C_EVENT
){
1429 interrupt_handler(0);
1436 #ifndef SQLITE_OMIT_AUTHORIZATION
1438 ** When the ".auth ON" is set, the following authorizer callback is
1439 ** invoked. It always returns SQLITE_OK.
1441 static int shellAuth(
1449 ShellState
*p
= (ShellState
*)pClientData
;
1450 static const char *azAction
[] = { 0,
1451 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1452 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1453 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1454 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1455 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1456 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1457 "PRAGMA", "READ", "SELECT",
1458 "TRANSACTION", "UPDATE", "ATTACH",
1459 "DETACH", "ALTER_TABLE", "REINDEX",
1460 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1461 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1469 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
1471 raw_printf(p
->out
, " ");
1473 output_c_string(p
->out
, az
[i
]);
1475 raw_printf(p
->out
, "NULL");
1478 raw_printf(p
->out
, "\n");
1484 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1486 ** This routine converts some CREATE TABLE statements for shadow tables
1487 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1489 static void printSchemaLine(FILE *out
, const char *z
, const char *zTail
){
1490 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
1491 utf8_printf(out
, "CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
1493 utf8_printf(out
, "%s%s", z
, zTail
);
1496 static void printSchemaLineN(FILE *out
, char *z
, int n
, const char *zTail
){
1499 printSchemaLine(out
, z
, zTail
);
1504 ** Return true if string z[] has nothing but whitespace and comments to the
1505 ** end of the first line.
1507 static int wsToEol(const char *z
){
1509 for(i
=0; z
[i
]; i
++){
1510 if( z
[i
]=='\n' ) return 1;
1511 if( IsSpace(z
[i
]) ) continue;
1512 if( z
[i
]=='-' && z
[i
+1]=='-' ) return 1;
1520 ** This is the callback routine that the shell
1521 ** invokes for each row of a query result.
1523 static int shell_callback(
1525 int nArg
, /* Number of result columns */
1526 char **azArg
, /* Text of each result column */
1527 char **azCol
, /* Column names */
1528 int *aiType
/* Column types */
1531 ShellState
*p
= (ShellState
*)pArg
;
1533 if( azArg
==0 ) return 0;
1537 if( azArg
==0 ) break;
1538 for(i
=0; i
<nArg
; i
++){
1539 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
1540 if( len
>w
) w
= len
;
1542 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1543 for(i
=0; i
<nArg
; i
++){
1544 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
1545 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
1551 static const int aExplainWidths
[] = {4, 13, 4, 4, 4, 13, 2, 13};
1552 const int *colWidth
;
1555 if( p
->cMode
==MODE_Column
){
1556 colWidth
= p
->colWidth
;
1557 showHdr
= p
->showHeader
;
1558 rowSep
= p
->rowSeparator
;
1560 colWidth
= aExplainWidths
;
1565 for(i
=0; i
<nArg
; i
++){
1567 if( i
<ArraySize(p
->colWidth
) ){
1573 w
= strlenChar(azCol
[i
] ? azCol
[i
] : "");
1575 n
= strlenChar(azArg
&& azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1578 if( i
<ArraySize(p
->actualWidth
) ){
1579 p
->actualWidth
[i
] = w
;
1582 utf8_width_print(p
->out
, w
, azCol
[i
]);
1583 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1587 for(i
=0; i
<nArg
; i
++){
1589 if( i
<ArraySize(p
->actualWidth
) ){
1590 w
= p
->actualWidth
[i
];
1595 utf8_printf(p
->out
,"%-*.*s%s",w
,w
,
1596 "----------------------------------------------------------"
1597 "----------------------------------------------------------",
1598 i
==nArg
-1 ? rowSep
: " ");
1602 if( azArg
==0 ) break;
1603 for(i
=0; i
<nArg
; i
++){
1605 if( i
<ArraySize(p
->actualWidth
) ){
1606 w
= p
->actualWidth
[i
];
1610 if( p
->cMode
==MODE_Explain
&& azArg
[i
] && strlenChar(azArg
[i
])>w
){
1611 w
= strlenChar(azArg
[i
]);
1613 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
1614 if( p
->iIndent
<p
->nIndent
){
1615 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
1619 utf8_width_print(p
->out
, w
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1620 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1624 case MODE_Semi
: { /* .schema and .fullschema output */
1625 printSchemaLine(p
->out
, azArg
[0], ";\n");
1628 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
1636 if( azArg
[0]==0 ) break;
1637 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
1638 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
1640 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
1643 z
= sqlite3_mprintf("%s", azArg
[0]);
1645 for(i
=0; IsSpace(z
[i
]); i
++){}
1646 for(; (c
= z
[i
])!=0; i
++){
1648 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
1649 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
1650 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
1655 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
1657 if( strlen30(z
)>=79 ){
1658 for(i
=j
=0; (c
= z
[i
])!=0; i
++){ /* Copy changes from z[i] back to z[j] */
1661 }else if( c
=='"' || c
=='\'' || c
=='`' ){
1665 }else if( c
=='-' && z
[i
+1]=='-' ){
1671 if( nLine
>0 && nParen
==0 && j
>0 ){
1672 printSchemaLineN(p
->out
, z
, j
, "\n");
1677 if( nParen
==1 && cEnd
==0
1678 && (c
=='(' || c
=='\n' || (c
==',' && !wsToEol(z
+i
+1)))
1681 printSchemaLineN(p
->out
, z
, j
, "\n ");
1684 while( IsSpace(z
[i
+1]) ){ i
++; }
1689 printSchemaLine(p
->out
, z
, ";\n");
1694 if( p
->cnt
++==0 && p
->showHeader
){
1695 for(i
=0; i
<nArg
; i
++){
1696 utf8_printf(p
->out
,"%s%s",azCol
[i
],
1697 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
1700 if( azArg
==0 ) break;
1701 for(i
=0; i
<nArg
; i
++){
1703 if( z
==0 ) z
= p
->nullValue
;
1704 utf8_printf(p
->out
, "%s", z
);
1706 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1708 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1714 if( p
->cnt
++==0 && p
->showHeader
){
1715 raw_printf(p
->out
,"<TR>");
1716 for(i
=0; i
<nArg
; i
++){
1717 raw_printf(p
->out
,"<TH>");
1718 output_html_string(p
->out
, azCol
[i
]);
1719 raw_printf(p
->out
,"</TH>\n");
1721 raw_printf(p
->out
,"</TR>\n");
1723 if( azArg
==0 ) break;
1724 raw_printf(p
->out
,"<TR>");
1725 for(i
=0; i
<nArg
; i
++){
1726 raw_printf(p
->out
,"<TD>");
1727 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1728 raw_printf(p
->out
,"</TD>\n");
1730 raw_printf(p
->out
,"</TR>\n");
1734 if( p
->cnt
++==0 && p
->showHeader
){
1735 for(i
=0; i
<nArg
; i
++){
1736 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
1737 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1739 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1741 if( azArg
==0 ) break;
1742 for(i
=0; i
<nArg
; i
++){
1743 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1744 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1746 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1750 setBinaryMode(p
->out
, 1);
1751 if( p
->cnt
++==0 && p
->showHeader
){
1752 for(i
=0; i
<nArg
; i
++){
1753 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
1755 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1758 for(i
=0; i
<nArg
; i
++){
1759 output_csv(p
, azArg
[i
], i
<nArg
-1);
1761 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1763 setTextMode(p
->out
, 1);
1767 if( azArg
==0 ) break;
1768 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
1769 if( p
->showHeader
){
1770 raw_printf(p
->out
,"(");
1771 for(i
=0; i
<nArg
; i
++){
1772 if( i
>0 ) raw_printf(p
->out
, ",");
1773 if( quoteChar(azCol
[i
]) ){
1774 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
1775 utf8_printf(p
->out
, "%s", z
);
1778 raw_printf(p
->out
, "%s", azCol
[i
]);
1781 raw_printf(p
->out
,")");
1784 for(i
=0; i
<nArg
; i
++){
1785 raw_printf(p
->out
, i
>0 ? "," : " VALUES(");
1786 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
1787 utf8_printf(p
->out
,"NULL");
1788 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
1789 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
1790 output_quoted_string(p
->out
, azArg
[i
]);
1792 output_quoted_escaped_string(p
->out
, azArg
[i
]);
1794 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
1795 utf8_printf(p
->out
,"%s", azArg
[i
]);
1796 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
1798 double r
= sqlite3_column_double(p
->pStmt
, i
);
1799 sqlite3_snprintf(50,z
,"%!.20g", r
);
1800 raw_printf(p
->out
, "%s", z
);
1801 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
1802 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
1803 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
1804 output_hex_blob(p
->out
, pBlob
, nBlob
);
1805 }else if( isNumber(azArg
[i
], 0) ){
1806 utf8_printf(p
->out
,"%s", azArg
[i
]);
1807 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
1808 output_quoted_string(p
->out
, azArg
[i
]);
1810 output_quoted_escaped_string(p
->out
, azArg
[i
]);
1813 raw_printf(p
->out
,");\n");
1817 if( azArg
==0 ) break;
1818 if( p
->cnt
==0 && p
->showHeader
){
1819 for(i
=0; i
<nArg
; i
++){
1820 if( i
>0 ) raw_printf(p
->out
, ",");
1821 output_quoted_string(p
->out
, azCol
[i
]);
1823 raw_printf(p
->out
,"\n");
1826 for(i
=0; i
<nArg
; i
++){
1827 if( i
>0 ) raw_printf(p
->out
, ",");
1828 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
1829 utf8_printf(p
->out
,"NULL");
1830 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
1831 output_quoted_string(p
->out
, azArg
[i
]);
1832 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
1833 utf8_printf(p
->out
,"%s", azArg
[i
]);
1834 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
1836 double r
= sqlite3_column_double(p
->pStmt
, i
);
1837 sqlite3_snprintf(50,z
,"%!.20g", r
);
1838 raw_printf(p
->out
, "%s", z
);
1839 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
1840 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
1841 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
1842 output_hex_blob(p
->out
, pBlob
, nBlob
);
1843 }else if( isNumber(azArg
[i
], 0) ){
1844 utf8_printf(p
->out
,"%s", azArg
[i
]);
1846 output_quoted_string(p
->out
, azArg
[i
]);
1849 raw_printf(p
->out
,"\n");
1853 if( p
->cnt
++==0 && p
->showHeader
){
1854 for(i
=0; i
<nArg
; i
++){
1855 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1856 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
1858 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1860 if( azArg
==0 ) break;
1861 for(i
=0; i
<nArg
; i
++){
1862 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1863 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1865 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1873 ** This is the callback routine that the SQLite library
1874 ** invokes for each row of a query result.
1876 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
1877 /* since we don't have type info, call the shell_callback with a NULL value */
1878 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
1882 ** This is the callback routine from sqlite3_exec() that appends all
1883 ** output onto the end of a ShellText object.
1885 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
1886 ShellText
*p
= (ShellText
*)pArg
;
1888 UNUSED_PARAMETER(az
);
1889 if( azArg
==0 ) return 0;
1890 if( p
->n
) appendText(p
, "|", 0);
1891 for(i
=0; i
<nArg
; i
++){
1892 if( i
) appendText(p
, ",", 0);
1893 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
1899 ** Generate an appropriate SELFTEST table in the main database.
1901 static void createSelftestTable(ShellState
*p
){
1904 "SAVEPOINT selftest_init;\n"
1905 "CREATE TABLE IF NOT EXISTS selftest(\n"
1906 " tno INTEGER PRIMARY KEY,\n" /* Test number */
1907 " op TEXT,\n" /* Operator: memo run */
1908 " cmd TEXT,\n" /* Command text */
1909 " ans TEXT\n" /* Desired answer */
1911 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
1912 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
1913 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
1914 " 'memo','Tests generated by --init');\n"
1915 "INSERT INTO [_shell$self]\n"
1917 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
1918 "FROM sqlite_master ORDER BY 2'',224))',\n"
1919 " hex(sha3_query('SELECT type,name,tbl_name,sql "
1920 "FROM sqlite_master ORDER BY 2',224));\n"
1921 "INSERT INTO [_shell$self]\n"
1923 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
1924 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
1925 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
1927 " SELECT name FROM sqlite_master\n"
1928 " WHERE type='table'\n"
1929 " AND name<>'selftest'\n"
1930 " AND coalesce(rootpage,0)>0\n"
1933 "INSERT INTO [_shell$self]\n"
1934 " VALUES('run','PRAGMA integrity_check','ok');\n"
1935 "INSERT INTO selftest(tno,op,cmd,ans)"
1936 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
1937 "DROP TABLE [_shell$self];"
1940 utf8_printf(stderr
, "SELFTEST initialization failure: %s\n", zErrMsg
);
1941 sqlite3_free(zErrMsg
);
1943 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
1948 ** Set the destination table field of the ShellState structure to
1949 ** the name of the table given. Escape any quote characters in the
1952 static void set_table_name(ShellState
*p
, const char *zName
){
1957 if( p
->zDestTable
){
1958 free(p
->zDestTable
);
1961 if( zName
==0 ) return;
1962 cQuote
= quoteChar(zName
);
1963 n
= strlen30(zName
);
1964 if( cQuote
) n
+= n
+2;
1965 z
= p
->zDestTable
= malloc( n
+1 );
1967 raw_printf(stderr
,"Error: out of memory\n");
1971 if( cQuote
) z
[n
++] = cQuote
;
1972 for(i
=0; zName
[i
]; i
++){
1974 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
1976 if( cQuote
) z
[n
++] = cQuote
;
1982 ** Execute a query statement that will generate SQL output. Print
1983 ** the result columns, comma-separated, on a line and then add a
1984 ** semicolon terminator to the end of that line.
1986 ** If the number of columns is 1 and that column contains text "--"
1987 ** then write the semicolon on a separate line. That way, if a
1988 ** "--" comment occurs at the end of the statement, the comment
1989 ** won't consume the semicolon terminator.
1991 static int run_table_dump_query(
1992 ShellState
*p
, /* Query context */
1993 const char *zSelect
, /* SELECT statement to extract content */
1994 const char *zFirstRow
/* Print before first row, if not NULL */
1996 sqlite3_stmt
*pSelect
;
2001 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
2002 if( rc
!=SQLITE_OK
|| !pSelect
){
2003 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2004 sqlite3_errmsg(p
->db
));
2005 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2008 rc
= sqlite3_step(pSelect
);
2009 nResult
= sqlite3_column_count(pSelect
);
2010 while( rc
==SQLITE_ROW
){
2012 utf8_printf(p
->out
, "%s", zFirstRow
);
2015 z
= (const char*)sqlite3_column_text(pSelect
, 0);
2016 utf8_printf(p
->out
, "%s", z
);
2017 for(i
=1; i
<nResult
; i
++){
2018 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
2021 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
2023 raw_printf(p
->out
, "\n;\n");
2025 raw_printf(p
->out
, ";\n");
2027 rc
= sqlite3_step(pSelect
);
2029 rc
= sqlite3_finalize(pSelect
);
2030 if( rc
!=SQLITE_OK
){
2031 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2032 sqlite3_errmsg(p
->db
));
2033 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2039 ** Allocate space and save off current error string.
2041 static char *save_err_msg(
2042 sqlite3
*db
/* Database to query */
2044 int nErrMsg
= 1+strlen30(sqlite3_errmsg(db
));
2045 char *zErrMsg
= sqlite3_malloc64(nErrMsg
);
2047 memcpy(zErrMsg
, sqlite3_errmsg(db
), nErrMsg
);
2054 ** Attempt to display I/O stats on Linux using /proc/PID/io
2056 static void displayLinuxIoStats(FILE *out
){
2059 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
2060 in
= fopen(z
, "rb");
2062 while( fgets(z
, sizeof(z
), in
)!=0 ){
2063 static const struct {
2064 const char *zPattern
;
2067 { "rchar: ", "Bytes received by read():" },
2068 { "wchar: ", "Bytes sent to write():" },
2069 { "syscr: ", "Read() system calls:" },
2070 { "syscw: ", "Write() system calls:" },
2071 { "read_bytes: ", "Bytes read from storage:" },
2072 { "write_bytes: ", "Bytes written to storage:" },
2073 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2076 for(i
=0; i
<ArraySize(aTrans
); i
++){
2077 int n
= strlen30(aTrans
[i
].zPattern
);
2078 if( strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
2079 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
2089 ** Display a single line of status using 64-bit values.
2091 static void displayStatLine(
2092 ShellState
*p
, /* The shell context */
2093 char *zLabel
, /* Label for this one line */
2094 char *zFormat
, /* Format for the result */
2095 int iStatusCtrl
, /* Which status to display */
2096 int bReset
/* True to reset the stats */
2098 sqlite3_int64 iCur
= -1;
2099 sqlite3_int64 iHiwtr
= -1;
2102 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
2103 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
2104 if( zFormat
[i
]=='%' ) nPercent
++;
2107 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
2109 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
2111 raw_printf(p
->out
, "%-36s %s\n", zLabel
, zLine
);
2115 ** Display memory stats.
2117 static int display_stats(
2118 sqlite3
*db
, /* Database to query */
2119 ShellState
*pArg
, /* Pointer to ShellState */
2120 int bReset
/* True to reset the stats */
2125 if( pArg
&& pArg
->out
){
2126 displayStatLine(pArg
, "Memory Used:",
2127 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
2128 displayStatLine(pArg
, "Number of Outstanding Allocations:",
2129 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
2130 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
2131 displayStatLine(pArg
, "Number of Pcache Pages Used:",
2132 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
2134 displayStatLine(pArg
, "Number of Pcache Overflow Bytes:",
2135 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
2136 displayStatLine(pArg
, "Largest Allocation:",
2137 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
2138 displayStatLine(pArg
, "Largest Pcache Allocation:",
2139 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
2140 #ifdef YYTRACKMAXSTACKDEPTH
2141 displayStatLine(pArg
, "Deepest Parser Stack:",
2142 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
2146 if( pArg
&& pArg
->out
&& db
){
2147 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
2149 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
2150 &iCur
, &iHiwtr
, bReset
);
2151 raw_printf(pArg
->out
,
2152 "Lookaside Slots Used: %d (max %d)\n",
2154 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
2155 &iCur
, &iHiwtr
, bReset
);
2156 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
2158 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
2159 &iCur
, &iHiwtr
, bReset
);
2160 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
2162 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
2163 &iCur
, &iHiwtr
, bReset
);
2164 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
2168 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
2169 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
2172 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
2173 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
2175 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
2176 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
2178 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
2179 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
2181 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
2182 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
2185 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
2186 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
2190 if( pArg
&& pArg
->out
&& db
&& pArg
->pStmt
){
2191 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
2193 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
2194 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
2195 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
2196 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
2197 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
2198 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
2199 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
2203 displayLinuxIoStats(pArg
->out
);
2206 /* Do not remove this machine readable comment: extra-stats-output-here */
2212 ** Display scan stats.
2214 static void display_scanstats(
2215 sqlite3
*db
, /* Database to query */
2216 ShellState
*pArg
/* Pointer to ShellState */
2218 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2219 UNUSED_PARAMETER(db
);
2220 UNUSED_PARAMETER(pArg
);
2223 raw_printf(pArg
->out
, "-------- scanstats --------\n");
2225 for(k
=0; k
<=mx
; k
++){
2226 double rEstLoop
= 1.0;
2228 sqlite3_stmt
*p
= pArg
->pStmt
;
2229 sqlite3_int64 nLoop
, nVisit
;
2232 const char *zExplain
;
2233 if( sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NLOOP
, (void*)&nLoop
) ){
2236 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_SELECTID
, (void*)&iSid
);
2237 if( iSid
>mx
) mx
= iSid
;
2238 if( iSid
!=k
) continue;
2240 rEstLoop
= (double)nLoop
;
2241 if( k
>0 ) raw_printf(pArg
->out
, "-------- subquery %d -------\n", k
);
2244 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NVISIT
, (void*)&nVisit
);
2245 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EST
, (void*)&rEst
);
2246 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EXPLAIN
, (void*)&zExplain
);
2247 utf8_printf(pArg
->out
, "Loop %2d: %s\n", n
, zExplain
);
2249 raw_printf(pArg
->out
,
2250 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2251 nLoop
, nVisit
, (sqlite3_int64
)(rEstLoop
+0.5), rEst
2255 raw_printf(pArg
->out
, "---------------------------\n");
2260 ** Parameter azArray points to a zero-terminated array of strings. zStr
2261 ** points to a single nul-terminated string. Return non-zero if zStr
2262 ** is equal, according to strcmp(), to any of the strings in the array.
2263 ** Otherwise, return zero.
2265 static int str_in_array(const char *zStr
, const char **azArray
){
2267 for(i
=0; azArray
[i
]; i
++){
2268 if( 0==strcmp(zStr
, azArray
[i
]) ) return 1;
2274 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2275 ** and populate the ShellState.aiIndent[] array with the number of
2276 ** spaces each opcode should be indented before it is output.
2278 ** The indenting rules are:
2280 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2281 ** all opcodes that occur between the p2 jump destination and the opcode
2282 ** itself by 2 spaces.
2284 ** * For each "Goto", if the jump destination is earlier in the program
2285 ** and ends on one of:
2286 ** Yield SeekGt SeekLt RowSetRead Rewind
2287 ** or if the P1 parameter is one instead of zero,
2288 ** then indent all opcodes between the earlier instruction
2289 ** and "Goto" by 2 spaces.
2291 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
2292 const char *zSql
; /* The text of the SQL statement */
2293 const char *z
; /* Used to check if this is an EXPLAIN */
2294 int *abYield
= 0; /* True if op is an OP_Yield */
2295 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
2296 int iOp
; /* Index of operation in p->aiIndent[] */
2298 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2299 "NextIfOpen", "PrevIfOpen", 0 };
2300 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2302 const char *azGoto
[] = { "Goto", 0 };
2304 /* Try to figure out if this is really an EXPLAIN statement. If this
2305 ** cannot be verified, return early. */
2306 if( sqlite3_column_count(pSql
)!=8 ){
2310 zSql
= sqlite3_sql(pSql
);
2311 if( zSql
==0 ) return;
2312 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
2313 if( sqlite3_strnicmp(z
, "explain", 7) ){
2318 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
2320 int iAddr
= sqlite3_column_int(pSql
, 0);
2321 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
2323 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2324 ** p2 is an instruction address, set variable p2op to the index of that
2325 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2326 ** the current instruction is part of a sub-program generated by an
2327 ** SQL trigger or foreign key. */
2328 int p2
= sqlite3_column_int(pSql
, 3);
2329 int p2op
= (p2
+ (iOp
-iAddr
));
2331 /* Grow the p->aiIndent array as required */
2334 /* Do further verfication that this is explain output. Abort if
2336 static const char *explainCols
[] = {
2337 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2339 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
2340 if( strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
2342 sqlite3_reset(pSql
);
2348 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
2349 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
2351 abYield
[iOp
] = str_in_array(zOp
, azYield
);
2352 p
->aiIndent
[iOp
] = 0;
2355 if( str_in_array(zOp
, azNext
) ){
2356 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2358 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
2359 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
2361 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2366 sqlite3_free(abYield
);
2367 sqlite3_reset(pSql
);
2371 ** Free the array allocated by explain_data_prepare().
2373 static void explain_data_delete(ShellState
*p
){
2374 sqlite3_free(p
->aiIndent
);
2381 ** Disable and restore .wheretrace and .selecttrace settings.
2383 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2384 extern int sqlite3SelectTrace
;
2385 static int savedSelectTrace
;
2387 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2388 extern int sqlite3WhereTrace
;
2389 static int savedWhereTrace
;
2391 static void disable_debug_trace_modes(void){
2392 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2393 savedSelectTrace
= sqlite3SelectTrace
;
2394 sqlite3SelectTrace
= 0;
2396 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2397 savedWhereTrace
= sqlite3WhereTrace
;
2398 sqlite3WhereTrace
= 0;
2401 static void restore_debug_trace_modes(void){
2402 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2403 sqlite3SelectTrace
= savedSelectTrace
;
2405 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2406 sqlite3WhereTrace
= savedWhereTrace
;
2411 ** Run a prepared statement
2413 static void exec_prepared_stmt(
2414 ShellState
*pArg
, /* Pointer to ShellState */
2415 sqlite3_stmt
*pStmt
, /* Statment to run */
2416 int (*xCallback
)(void*,int,char**,char**,int*) /* Callback function */
2420 /* perform the first step. this will tell us if we
2421 ** have a result set or not and how wide it is.
2423 rc
= sqlite3_step(pStmt
);
2424 /* if we have a result set... */
2425 if( SQLITE_ROW
== rc
){
2426 /* if we have a callback... */
2428 /* allocate space for col name ptr, value ptr, and type */
2429 int nCol
= sqlite3_column_count(pStmt
);
2430 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
2434 char **azCols
= (char **)pData
; /* Names of result columns */
2435 char **azVals
= &azCols
[nCol
]; /* Results */
2436 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
2438 assert(sizeof(int) <= sizeof(char *));
2439 /* save off ptrs to column names */
2440 for(i
=0; i
<nCol
; i
++){
2441 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
2444 /* extract the data and data types */
2445 for(i
=0; i
<nCol
; i
++){
2446 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
2447 if( x
==SQLITE_BLOB
&& pArg
&& pArg
->cMode
==MODE_Insert
){
2450 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
2452 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
2454 break; /* from for */
2458 /* if data and types extracted successfully... */
2459 if( SQLITE_ROW
== rc
){
2460 /* call the supplied callback with the result row data */
2461 if( xCallback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
2464 rc
= sqlite3_step(pStmt
);
2467 } while( SQLITE_ROW
== rc
);
2468 sqlite3_free(pData
);
2472 rc
= sqlite3_step(pStmt
);
2473 } while( rc
== SQLITE_ROW
);
2478 #ifndef SQLITE_OMIT_VIRTUALTABLE
2480 ** This function is called to process SQL if the previous shell command
2481 ** was ".expert". It passes the SQL in the second argument directly to
2482 ** the sqlite3expert object.
2484 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2485 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2486 ** an English language error message. It is the responsibility of the
2487 ** caller to eventually free this buffer using sqlite3_free().
2489 static int expertHandleSQL(
2494 assert( pState
->expert
.pExpert
);
2495 assert( pzErr
==0 || *pzErr
==0 );
2496 return sqlite3_expert_sql(pState
->expert
.pExpert
, zSql
, pzErr
);
2500 ** This function is called either to silently clean up the object
2501 ** created by the ".expert" command (if bCancel==1), or to generate a
2502 ** report from it and then clean it up (if bCancel==0).
2504 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2505 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2506 ** an English language error message. It is the responsibility of the
2507 ** caller to eventually free this buffer using sqlite3_free().
2509 static int expertFinish(
2515 sqlite3expert
*p
= pState
->expert
.pExpert
;
2517 assert( bCancel
|| pzErr
==0 || *pzErr
==0 );
2519 FILE *out
= pState
->out
;
2520 int bVerbose
= pState
->expert
.bVerbose
;
2522 rc
= sqlite3_expert_analyze(p
, pzErr
);
2523 if( rc
==SQLITE_OK
){
2524 int nQuery
= sqlite3_expert_count(p
);
2528 const char *zCand
= sqlite3_expert_report(p
,0,EXPERT_REPORT_CANDIDATES
);
2529 raw_printf(out
, "-- Candidates -----------------------------\n");
2530 raw_printf(out
, "%s\n", zCand
);
2532 for(i
=0; i
<nQuery
; i
++){
2533 const char *zSql
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_SQL
);
2534 const char *zIdx
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_INDEXES
);
2535 const char *zEQP
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_PLAN
);
2536 if( zIdx
==0 ) zIdx
= "(no new indexes)\n";
2538 raw_printf(out
, "-- Query %d --------------------------------\n",i
+1);
2539 raw_printf(out
, "%s\n\n", zSql
);
2541 raw_printf(out
, "%s\n", zIdx
);
2542 raw_printf(out
, "%s\n", zEQP
);
2546 sqlite3_expert_destroy(p
);
2547 pState
->expert
.pExpert
= 0;
2552 ** Implementation of ".expert" dot command.
2554 static int expertDotCommand(
2555 ShellState
*pState
, /* Current shell tool state */
2556 char **azArg
, /* Array of arguments passed to dot command */
2557 int nArg
/* Number of entries in azArg[] */
2564 assert( pState
->expert
.pExpert
==0 );
2565 memset(&pState
->expert
, 0, sizeof(ExpertInfo
));
2567 for(i
=1; rc
==SQLITE_OK
&& i
<nArg
; i
++){
2570 if( z
[0]=='-' && z
[1]=='-' ) z
++;
2572 if( n
>=2 && 0==strncmp(z
, "-verbose", n
) ){
2573 pState
->expert
.bVerbose
= 1;
2575 else if( n
>=2 && 0==strncmp(z
, "-sample", n
) ){
2577 raw_printf(stderr
, "option requires an argument: %s\n", z
);
2580 iSample
= (int)integerValue(azArg
[++i
]);
2581 if( iSample
<0 || iSample
>100 ){
2582 raw_printf(stderr
, "value out of range: %s\n", azArg
[i
]);
2588 raw_printf(stderr
, "unknown option: %s\n", z
);
2593 if( rc
==SQLITE_OK
){
2594 pState
->expert
.pExpert
= sqlite3_expert_new(pState
->db
, &zErr
);
2595 if( pState
->expert
.pExpert
==0 ){
2596 raw_printf(stderr
, "sqlite3_expert_new: %s\n", zErr
);
2599 sqlite3_expert_config(
2600 pState
->expert
.pExpert
, EXPERT_CONFIG_SAMPLE
, iSample
2607 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2610 ** Execute a statement or set of statements. Print
2611 ** any result rows/columns depending on the current mode
2612 ** set via the supplied callback.
2614 ** This is very similar to SQLite's built-in sqlite3_exec()
2615 ** function except it takes a slightly different callback
2616 ** and callback data argument.
2618 static int shell_exec(
2619 sqlite3
*db
, /* An open database */
2620 const char *zSql
, /* SQL to be evaluated */
2621 int (*xCallback
)(void*,int,char**,char**,int*), /* Callback function */
2622 /* (not the same as sqlite3_exec) */
2623 ShellState
*pArg
, /* Pointer to ShellState */
2624 char **pzErrMsg
/* Error msg written here */
2626 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
2627 int rc
= SQLITE_OK
; /* Return Code */
2629 const char *zLeftover
; /* Tail of unprocessed SQL */
2635 #ifndef SQLITE_OMIT_VIRTUALTABLE
2636 if( pArg
->expert
.pExpert
){
2637 rc
= expertHandleSQL(pArg
, zSql
, pzErrMsg
);
2638 return expertFinish(pArg
, (rc
!=SQLITE_OK
), pzErrMsg
);
2642 while( zSql
[0] && (SQLITE_OK
== rc
) ){
2643 static const char *zStmtSql
;
2644 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
2645 if( SQLITE_OK
!= rc
){
2647 *pzErrMsg
= save_err_msg(db
);
2651 /* this happens for a comment or white-space */
2653 while( IsSpace(zSql
[0]) ) zSql
++;
2656 zStmtSql
= sqlite3_sql(pStmt
);
2657 if( zStmtSql
==0 ) zStmtSql
= "";
2658 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
2660 /* save off the prepared statment handle and reset row count */
2662 pArg
->pStmt
= pStmt
;
2666 /* echo the sql statement if echo on */
2667 if( pArg
&& ShellHasFlag(pArg
, SHFLG_Echo
) ){
2668 utf8_printf(pArg
->out
, "%s\n", zStmtSql
? zStmtSql
: zSql
);
2671 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2672 if( pArg
&& pArg
->autoEQP
&& sqlite3_strlike("EXPLAIN%",zStmtSql
,0)!=0 ){
2673 sqlite3_stmt
*pExplain
;
2676 disable_debug_trace_modes();
2677 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, -1, &triggerEQP
);
2678 if( pArg
->autoEQP
>=AUTOEQP_trigger
){
2679 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 1, 0);
2681 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
2682 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2683 if( rc
==SQLITE_OK
){
2684 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
2685 raw_printf(pArg
->out
,"--EQP-- %d,",sqlite3_column_int(pExplain
, 0));
2686 raw_printf(pArg
->out
,"%d,", sqlite3_column_int(pExplain
, 1));
2687 raw_printf(pArg
->out
,"%d,", sqlite3_column_int(pExplain
, 2));
2688 utf8_printf(pArg
->out
,"%s\n", sqlite3_column_text(pExplain
, 3));
2691 sqlite3_finalize(pExplain
);
2693 if( pArg
->autoEQP
>=AUTOEQP_full
){
2694 /* Also do an EXPLAIN for ".eqp full" mode */
2695 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
2696 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2697 if( rc
==SQLITE_OK
){
2698 pArg
->cMode
= MODE_Explain
;
2699 explain_data_prepare(pArg
, pExplain
);
2700 exec_prepared_stmt(pArg
, pExplain
, xCallback
);
2701 explain_data_delete(pArg
);
2703 sqlite3_finalize(pExplain
);
2706 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, triggerEQP
, 0);
2707 restore_debug_trace_modes();
2711 pArg
->cMode
= pArg
->mode
;
2712 if( pArg
->autoExplain
2713 && sqlite3_column_count(pStmt
)==8
2714 && sqlite3_strlike("EXPLAIN%", zStmtSql
,0)==0
2716 pArg
->cMode
= MODE_Explain
;
2719 /* If the shell is currently in ".explain" mode, gather the extra
2720 ** data required to add indents to the output.*/
2721 if( pArg
->cMode
==MODE_Explain
){
2722 explain_data_prepare(pArg
, pStmt
);
2726 exec_prepared_stmt(pArg
, pStmt
, xCallback
);
2727 explain_data_delete(pArg
);
2729 /* print usage stats if stats on */
2730 if( pArg
&& pArg
->statsOn
){
2731 display_stats(db
, pArg
, 0);
2734 /* print loop-counters if required */
2735 if( pArg
&& pArg
->scanstatsOn
){
2736 display_scanstats(db
, pArg
);
2739 /* Finalize the statement just executed. If this fails, save a
2740 ** copy of the error message. Otherwise, set zSql to point to the
2741 ** next statement to execute. */
2742 rc2
= sqlite3_finalize(pStmt
);
2743 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
2744 if( rc
==SQLITE_OK
){
2746 while( IsSpace(zSql
[0]) ) zSql
++;
2747 }else if( pzErrMsg
){
2748 *pzErrMsg
= save_err_msg(db
);
2751 /* clear saved stmt handle */
2762 ** Release memory previously allocated by tableColumnList().
2764 static void freeColumnList(char **azCol
){
2766 for(i
=1; azCol
[i
]; i
++){
2767 sqlite3_free(azCol
[i
]);
2769 /* azCol[0] is a static string */
2770 sqlite3_free(azCol
);
2774 ** Return a list of pointers to strings which are the names of all
2775 ** columns in table zTab. The memory to hold the names is dynamically
2776 ** allocated and must be released by the caller using a subsequent call
2777 ** to freeColumnList().
2779 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2780 ** value that needs to be preserved, then azCol[0] is filled in with the
2781 ** name of the rowid column.
2783 ** The first regular column in the table is azCol[1]. The list is terminated
2784 ** by an entry with azCol[i]==0.
2786 static char **tableColumnList(ShellState
*p
, const char *zTab
){
2788 sqlite3_stmt
*pStmt
;
2792 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
2793 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
2794 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
2797 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
2798 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
2801 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
2802 if( nCol
>=nAlloc
-2 ){
2803 nAlloc
= nAlloc
*2 + nCol
+ 10;
2804 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
2806 raw_printf(stderr
, "Error: out of memory\n");
2810 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
2811 if( sqlite3_column_int(pStmt
, 5) ){
2814 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
2823 sqlite3_finalize(pStmt
);
2824 if( azCol
==0 ) return 0;
2828 /* The decision of whether or not a rowid really needs to be preserved
2829 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2830 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2831 ** rowids on tables where the rowid is inaccessible because there are other
2832 ** columns in the table named "rowid", "_rowid_", and "oid".
2834 if( preserveRowid
&& isIPK
){
2835 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2836 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2837 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2838 ** ROWID aliases. To distinguish these cases, check to see if
2839 ** there is a "pk" entry in "PRAGMA index_list". There will be
2840 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2842 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2843 " WHERE origin='pk'", zTab
);
2844 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
2847 freeColumnList(azCol
);
2850 rc
= sqlite3_step(pStmt
);
2851 sqlite3_finalize(pStmt
);
2852 preserveRowid
= rc
==SQLITE_ROW
;
2854 if( preserveRowid
){
2855 /* Only preserve the rowid if we can find a name to use for the
2857 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
2860 for(i
=1; i
<=nCol
; i
++){
2861 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
2864 /* At this point, we know that azRowid[j] is not the name of any
2865 ** ordinary column in the table. Verify that azRowid[j] is a valid
2866 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2867 ** tables will fail this last check */
2868 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
2869 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
2878 ** Toggle the reverse_unordered_selects setting.
2880 static void toggleSelectOrder(sqlite3
*db
){
2881 sqlite3_stmt
*pStmt
= 0;
2884 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
2885 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
2886 iSetting
= sqlite3_column_int(pStmt
, 0);
2888 sqlite3_finalize(pStmt
);
2889 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
2890 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
2891 sqlite3_exec(db
, zStmt
, 0, 0, 0);
2895 ** This is a different callback routine used for dumping the database.
2896 ** Each row received by this callback consists of a table name,
2897 ** the table type ("index" or "table") and SQL to create the table.
2898 ** This routine should print text sufficient to recreate the table.
2900 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
2905 ShellState
*p
= (ShellState
*)pArg
;
2907 UNUSED_PARAMETER(azNotUsed
);
2908 if( nArg
!=3 || azArg
==0 ) return 0;
2913 if( strcmp(zTable
, "sqlite_sequence")==0 ){
2914 raw_printf(p
->out
, "DELETE FROM sqlite_sequence;\n");
2915 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 ){
2916 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
2917 }else if( strncmp(zTable
, "sqlite_", 7)==0 ){
2919 }else if( strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
2921 if( !p
->writableSchema
){
2922 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
2923 p
->writableSchema
= 1;
2925 zIns
= sqlite3_mprintf(
2926 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2927 "VALUES('table','%q','%q',0,'%q');",
2928 zTable
, zTable
, zSql
);
2929 utf8_printf(p
->out
, "%s\n", zIns
);
2933 printSchemaLine(p
->out
, zSql
, ";\n");
2936 if( strcmp(zType
, "table")==0 ){
2941 char *savedDestTable
;
2944 azCol
= tableColumnList(p
, zTable
);
2950 /* Always quote the table name, even if it appears to be pure ascii,
2951 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2953 appendText(&sTable
, zTable
, quoteChar(zTable
));
2954 /* If preserving the rowid, add a column list after the table name.
2955 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2956 ** instead of the usual "INSERT INTO tab VALUES(...)".
2959 appendText(&sTable
, "(", 0);
2960 appendText(&sTable
, azCol
[0], 0);
2961 for(i
=1; azCol
[i
]; i
++){
2962 appendText(&sTable
, ",", 0);
2963 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
2965 appendText(&sTable
, ")", 0);
2968 /* Build an appropriate SELECT statement */
2970 appendText(&sSelect
, "SELECT ", 0);
2972 appendText(&sSelect
, azCol
[0], 0);
2973 appendText(&sSelect
, ",", 0);
2975 for(i
=1; azCol
[i
]; i
++){
2976 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
2978 appendText(&sSelect
, ",", 0);
2981 freeColumnList(azCol
);
2982 appendText(&sSelect
, " FROM ", 0);
2983 appendText(&sSelect
, zTable
, quoteChar(zTable
));
2985 savedDestTable
= p
->zDestTable
;
2986 savedMode
= p
->mode
;
2987 p
->zDestTable
= sTable
.z
;
2988 p
->mode
= p
->cMode
= MODE_Insert
;
2989 rc
= shell_exec(p
->db
, sSelect
.z
, shell_callback
, p
, 0);
2990 if( (rc
&0xff)==SQLITE_CORRUPT
){
2991 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
2992 toggleSelectOrder(p
->db
);
2993 shell_exec(p
->db
, sSelect
.z
, shell_callback
, p
, 0);
2994 toggleSelectOrder(p
->db
);
2996 p
->zDestTable
= savedDestTable
;
2997 p
->mode
= savedMode
;
3006 ** Run zQuery. Use dump_callback() as the callback routine so that
3007 ** the contents of the query are output as SQL statements.
3009 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3010 ** "ORDER BY rowid DESC" to the end.
3012 static int run_schema_dump_query(
3018 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
3019 if( rc
==SQLITE_CORRUPT
){
3021 int len
= strlen30(zQuery
);
3022 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
3024 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
3028 zQ2
= malloc( len
+100 );
3029 if( zQ2
==0 ) return rc
;
3030 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
3031 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
3033 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
3035 rc
= SQLITE_CORRUPT
;
3044 ** Text of a help message
3046 static char zHelp
[] =
3047 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3048 ".archive ... Manage SQL archives: \".archive --help\" for details\n"
3050 #ifndef SQLITE_OMIT_AUTHORIZATION
3051 ".auth ON|OFF Show authorizer callbacks\n"
3053 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
3054 ".bail on|off Stop after hitting an error. Default OFF\n"
3055 ".binary on|off Turn binary output on or off. Default OFF\n"
3056 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
3057 ".changes on|off Show number of rows changed by SQL\n"
3058 ".check GLOB Fail if output since .testcase does not match\n"
3059 ".clone NEWDB Clone data into NEWDB from the existing database\n"
3060 ".databases List names and files of attached databases\n"
3061 ".dbinfo ?DB? Show status information about the database\n"
3062 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
3063 " If TABLE specified, only dump tables matching\n"
3064 " LIKE pattern TABLE.\n"
3065 ".echo on|off Turn command echo on or off\n"
3066 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
3067 ".exit Exit this program\n"
3068 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
3069 /* Because explain mode comes on automatically now, the ".explain" mode
3070 ** is removed from the help screen. It is still supported for legacy, however */
3071 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
3072 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
3073 ".headers on|off Turn display of headers on or off\n"
3074 ".help Show this message\n"
3075 ".import FILE TABLE Import data from FILE into TABLE\n"
3076 #ifndef SQLITE_OMIT_TEST_CONTROL
3077 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3079 ".indexes ?TABLE? Show names of all indexes\n"
3080 " If TABLE specified, only show indexes for tables\n"
3081 " matching LIKE pattern TABLE.\n"
3082 #ifdef SQLITE_ENABLE_IOTRACE
3083 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3085 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
3086 ".lint OPTIONS Report potential schema issues. Options:\n"
3087 " fkey-indexes Find missing foreign key indexes\n"
3088 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3089 ".load FILE ?ENTRY? Load an extension library\n"
3091 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
3092 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
3093 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
3094 " csv Comma-separated values\n"
3095 " column Left-aligned columns. (See .width)\n"
3096 " html HTML <table> code\n"
3097 " insert SQL insert statements for TABLE\n"
3098 " line One value per line\n"
3099 " list Values delimited by \"|\"\n"
3100 " quote Escape answers as for SQL\n"
3101 " tabs Tab-separated values\n"
3102 " tcl TCL list elements\n"
3103 ".nullvalue STRING Use STRING in place of NULL values\n"
3104 ".once FILENAME Output for the next SQL command only to FILENAME\n"
3105 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3106 " The --new option starts with an empty file\n"
3107 ".output ?FILENAME? Send output to FILENAME or stdout\n"
3108 ".print STRING... Print literal STRING\n"
3109 ".prompt MAIN CONTINUE Replace the standard prompts\n"
3110 ".quit Exit this program\n"
3111 ".read FILENAME Execute SQL in FILENAME\n"
3112 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
3113 ".save FILE Write in-memory database into FILE\n"
3114 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
3115 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3116 " Add --indent for pretty-printing\n"
3117 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
3118 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3119 " separator for both the output mode and .import\n"
3120 #if defined(SQLITE_ENABLE_SESSION)
3121 ".session CMD ... Create or control sessions\n"
3123 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
3124 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
3125 ".show Show the current values for various settings\n"
3126 ".stats ?on|off? Show stats or turn stats on or off\n"
3127 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
3128 ".tables ?TABLE? List names of tables\n"
3129 " If TABLE specified, only list tables matching\n"
3130 " LIKE pattern TABLE.\n"
3131 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
3132 ".timeout MS Try opening locked tables for MS milliseconds\n"
3133 ".timer on|off Turn SQL timer on or off\n"
3134 ".trace FILE|off Output each SQL statement as it is run\n"
3135 ".vfsinfo ?AUX? Information about the top-level VFS\n"
3136 ".vfslist List all available VFSes\n"
3137 ".vfsname ?AUX? Print the name of the VFS stack\n"
3138 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
3139 " Negative values right-justify\n"
3142 #if defined(SQLITE_ENABLE_SESSION)
3144 ** Print help information for the ".sessions" command
3146 void session_help(ShellState
*p
){
3148 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3149 "If ?NAME? is omitted, the first defined session is used.\n"
3151 " attach TABLE Attach TABLE\n"
3152 " changeset FILE Write a changeset into FILE\n"
3153 " close Close one session\n"
3154 " enable ?BOOLEAN? Set or query the enable bit\n"
3155 " filter GLOB... Reject tables matching GLOBs\n"
3156 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3157 " isempty Query whether the session is empty\n"
3158 " list List currently open session names\n"
3159 " open DB NAME Open a new session on DB\n"
3160 " patchset FILE Write a patchset into FILE\n"
3166 /* Forward reference */
3167 static int process_input(ShellState
*p
, FILE *in
);
3170 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
3171 ** and return a pointer to the buffer. The caller is responsible for freeing
3174 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3177 ** For convenience, a nul-terminator byte is always appended to the data read
3178 ** from the file before the buffer is returned. This byte is not included in
3179 ** the final value of (*pnByte), if applicable.
3181 ** NULL is returned if any error is encountered. The final value of *pnByte
3182 ** is undefined in this case.
3184 static char *readFile(const char *zName
, int *pnByte
){
3185 FILE *in
= fopen(zName
, "rb");
3189 if( in
==0 ) return 0;
3190 fseek(in
, 0, SEEK_END
);
3193 pBuf
= sqlite3_malloc64( nIn
+1 );
3194 if( pBuf
==0 ) return 0;
3195 nRead
= fread(pBuf
, nIn
, 1, in
);
3202 if( pnByte
) *pnByte
= nIn
;
3206 #if defined(SQLITE_ENABLE_SESSION)
3208 ** Close a single OpenSession object and release all of its associated
3211 static void session_close(OpenSession
*pSession
){
3213 sqlite3session_delete(pSession
->p
);
3214 sqlite3_free(pSession
->zName
);
3215 for(i
=0; i
<pSession
->nFilter
; i
++){
3216 sqlite3_free(pSession
->azFilter
[i
]);
3218 sqlite3_free(pSession
->azFilter
);
3219 memset(pSession
, 0, sizeof(OpenSession
));
3224 ** Close all OpenSession objects and release all associated resources.
3226 #if defined(SQLITE_ENABLE_SESSION)
3227 static void session_close_all(ShellState
*p
){
3229 for(i
=0; i
<p
->nSession
; i
++){
3230 session_close(&p
->aSession
[i
]);
3235 # define session_close_all(X)
3239 ** Implementation of the xFilter function for an open session. Omit
3240 ** any tables named by ".session filter" but let all other table through.
3242 #if defined(SQLITE_ENABLE_SESSION)
3243 static int session_filter(void *pCtx
, const char *zTab
){
3244 OpenSession
*pSession
= (OpenSession
*)pCtx
;
3246 for(i
=0; i
<pSession
->nFilter
; i
++){
3247 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
3254 ** Try to deduce the type of file for zName based on its content. Return
3255 ** one of the SHELL_OPEN_* constants.
3257 static int deduceDatabaseType(const char *zName
){
3258 FILE *f
= fopen(zName
, "rb");
3260 int rc
= SHELL_OPEN_UNSPEC
;
3262 if( f
==0 ) return SHELL_OPEN_NORMAL
;
3263 fseek(f
, -25, SEEK_END
);
3264 n
= fread(zBuf
, 25, 1, f
);
3265 if( n
==1 && memcmp(zBuf
, "Start-Of-SQLite3-", 17)==0 ){
3266 rc
= SHELL_OPEN_APPENDVFS
;
3268 fseek(f
, -22, SEEK_END
);
3269 n
= fread(zBuf
, 22, 1, f
);
3270 if( n
==1 && zBuf
[0]==0x50 && zBuf
[1]==0x4b && zBuf
[2]==0x05
3272 rc
= SHELL_OPEN_ZIPFILE
;
3280 ** Make sure the database is open. If it is not, then open it. If
3281 ** the database fails to open, print an error message and exit.
3283 static void open_db(ShellState
*p
, int keepAlive
){
3285 sqlite3_initialize();
3286 if( p
->openMode
==SHELL_OPEN_UNSPEC
&& access(p
->zDbFilename
,0)==0 ){
3287 p
->openMode
= deduceDatabaseType(p
->zDbFilename
);
3289 switch( p
->openMode
){
3290 case SHELL_OPEN_APPENDVFS
: {
3291 sqlite3_open_v2(p
->zDbFilename
, &p
->db
,
3292 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, "apndvfs");
3295 case SHELL_OPEN_ZIPFILE
: {
3296 sqlite3_open(":memory:", &p
->db
);
3299 case SHELL_OPEN_UNSPEC
:
3300 case SHELL_OPEN_NORMAL
: {
3301 sqlite3_open(p
->zDbFilename
, &p
->db
);
3306 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3307 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
3308 p
->zDbFilename
, sqlite3_errmsg(p
->db
));
3309 if( keepAlive
) return;
3312 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3313 sqlite3_enable_load_extension(p
->db
, 1);
3315 sqlite3_fileio_init(p
->db
, 0, 0);
3316 sqlite3_shathree_init(p
->db
, 0, 0);
3317 sqlite3_completion_init(p
->db
, 0, 0);
3318 #ifdef SQLITE_HAVE_ZLIB
3319 sqlite3_zipfile_init(p
->db
, 0, 0);
3320 sqlite3_sqlar_init(p
->db
, 0, 0);
3322 sqlite3_create_function(p
->db
, "shell_add_schema", 3, SQLITE_UTF8
, 0,
3323 shellAddSchemaName
, 0, 0);
3324 sqlite3_create_function(p
->db
, "shell_module_schema", 1, SQLITE_UTF8
, 0,
3325 shellModuleSchema
, 0, 0);
3326 sqlite3_create_function(p
->db
, "shell_putsnl", 1, SQLITE_UTF8
, p
,
3327 shellPutsFunc
, 0, 0);
3328 if( p
->openMode
==SHELL_OPEN_ZIPFILE
){
3329 char *zSql
= sqlite3_mprintf(
3330 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p
->zDbFilename
);
3331 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
3337 #if HAVE_READLINE || HAVE_EDITLINE
3339 ** Readline completion callbacks
3341 static char *readline_completion_generator(const char *text
, int state
){
3342 static sqlite3_stmt
*pStmt
= 0;
3346 sqlite3_finalize(pStmt
);
3347 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3348 " FROM completion(%Q) ORDER BY 1", text
);
3349 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3352 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
3353 zRet
= strdup((const char*)sqlite3_column_text(pStmt
, 0));
3355 sqlite3_finalize(pStmt
);
3361 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
3362 rl_attempted_completion_over
= 1;
3363 return rl_completion_matches(zText
, readline_completion_generator
);
3366 #elif HAVE_LINENOISE
3368 ** Linenoise completion callback
3370 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
3371 int nLine
= strlen30(zLine
);
3373 sqlite3_stmt
*pStmt
= 0;
3377 if( nLine
>sizeof(zBuf
)-30 ) return;
3378 if( zLine
[0]=='.' ) return;
3379 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
3380 if( i
==nLine
-1 ) return;
3382 memcpy(zBuf
, zLine
, iStart
);
3383 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3384 " FROM completion(%Q,%Q) ORDER BY 1",
3385 &zLine
[iStart
], zLine
);
3386 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3388 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3389 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
3390 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
3391 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
3392 if( iStart
+nCompletion
< sizeof(zBuf
)-1 ){
3393 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
3394 linenoiseAddCompletion(lc
, zBuf
);
3397 sqlite3_finalize(pStmt
);
3402 ** Do C-language style dequoting.
3408 ** \v -> vertical tab
3410 ** \r -> carriage return
3415 ** \NNN -> ascii character NNN in octal
3417 static void resolve_backslashes(char *z
){
3420 while( *z
&& *z
!='\\' ) z
++;
3421 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
3422 if( c
=='\\' && z
[i
+1]!=0 ){
3440 }else if( c
=='\'' ){
3442 }else if( c
=='\\' ){
3444 }else if( c
>='0' && c
<='7' ){
3446 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3448 c
= (c
<<3) + z
[i
] - '0';
3449 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3451 c
= (c
<<3) + z
[i
] - '0';
3462 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3463 ** for TRUE and FALSE. Return the integer value if appropriate.
3465 static int booleanValue(const char *zArg
){
3467 if( zArg
[0]=='0' && zArg
[1]=='x' ){
3468 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
3470 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
3472 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
3473 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
3476 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
3479 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3485 ** Set or clear a shell flag according to a boolean value.
3487 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
3488 if( booleanValue(zArg
) ){
3489 ShellSetFlag(p
, mFlag
);
3491 ShellClearFlag(p
, mFlag
);
3496 ** Close an output file, assuming it is not stderr or stdout
3498 static void output_file_close(FILE *f
){
3499 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
3503 ** Try to open an output file. The names "stdout" and "stderr" are
3504 ** recognized and do the right thing. NULL is returned if the output
3505 ** filename is "off".
3507 static FILE *output_file_open(const char *zFile
){
3509 if( strcmp(zFile
,"stdout")==0 ){
3511 }else if( strcmp(zFile
, "stderr")==0 ){
3513 }else if( strcmp(zFile
, "off")==0 ){
3516 f
= fopen(zFile
, "wb");
3518 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
3524 #if !defined(SQLITE_UNTESTABLE)
3525 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3527 ** A routine for handling output from sqlite3_trace().
3529 static int sql_trace_callback(
3535 FILE *f
= (FILE*)pArg
;
3536 UNUSED_PARAMETER(mType
);
3537 UNUSED_PARAMETER(pP
);
3539 const char *z
= (const char*)pX
;
3540 int i
= strlen30(z
);
3541 while( i
>0 && z
[i
-1]==';' ){ i
--; }
3542 utf8_printf(f
, "%.*s;\n", i
, z
);
3550 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
3551 ** a useful spot to set a debugger breakpoint.
3553 static void test_breakpoint(void){
3554 static int nCall
= 0;
3559 ** An object used to read a CSV and other files for import.
3561 typedef struct ImportCtx ImportCtx
;
3563 const char *zFile
; /* Name of the input file */
3564 FILE *in
; /* Read the CSV text from this input stream */
3565 char *z
; /* Accumulated text for a field */
3566 int n
; /* Number of bytes in z */
3567 int nAlloc
; /* Space allocated for z[] */
3568 int nLine
; /* Current line number */
3569 int bNotFirst
; /* True if one or more bytes already read */
3570 int cTerm
; /* Character that terminated the most recent field */
3571 int cColSep
; /* The column separator character. (Usually ",") */
3572 int cRowSep
; /* The row separator character. (Usually "\n") */
3575 /* Append a single byte to z[] */
3576 static void import_append_char(ImportCtx
*p
, int c
){
3577 if( p
->n
+1>=p
->nAlloc
){
3578 p
->nAlloc
+= p
->nAlloc
+ 100;
3579 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
3581 raw_printf(stderr
, "out of memory\n");
3585 p
->z
[p
->n
++] = (char)c
;
3588 /* Read a single field of CSV text. Compatible with rfc4180 and extended
3589 ** with the option of having a separator other than ",".
3591 ** + Input comes from p->in.
3592 ** + Store results in p->z of length p->n. Space to hold p->z comes
3593 ** from sqlite3_malloc64().
3594 ** + Use p->cSep as the column separator. The default is ",".
3595 ** + Use p->rSep as the row separator. The default is "\n".
3596 ** + Keep track of the line number in p->nLine.
3597 ** + Store the character that terminates the field in p->cTerm. Store
3598 ** EOF on end-of-file.
3599 ** + Report syntax errors on stderr
3601 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
3603 int cSep
= p
->cColSep
;
3604 int rSep
= p
->cRowSep
;
3607 if( c
==EOF
|| seenInterrupt
){
3613 int startLine
= p
->nLine
;
3618 if( c
==rSep
) p
->nLine
++;
3625 if( (c
==cSep
&& pc
==cQuote
)
3626 || (c
==rSep
&& pc
==cQuote
)
3627 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
3628 || (c
==EOF
&& pc
==cQuote
)
3630 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
3634 if( pc
==cQuote
&& c
!='\r' ){
3635 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
3636 p
->zFile
, p
->nLine
, cQuote
);
3639 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
3640 p
->zFile
, startLine
, cQuote
);
3644 import_append_char(p
, c
);
3649 /* If this is the first field being parsed and it begins with the
3650 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3651 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
3652 import_append_char(p
, c
);
3654 if( (c
&0xff)==0xbb ){
3655 import_append_char(p
, c
);
3657 if( (c
&0xff)==0xbf ){
3660 return csv_read_one_field(p
);
3664 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
3665 import_append_char(p
, c
);
3670 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
3674 if( p
->z
) p
->z
[p
->n
] = 0;
3679 /* Read a single field of ASCII delimited text.
3681 ** + Input comes from p->in.
3682 ** + Store results in p->z of length p->n. Space to hold p->z comes
3683 ** from sqlite3_malloc64().
3684 ** + Use p->cSep as the column separator. The default is "\x1F".
3685 ** + Use p->rSep as the row separator. The default is "\x1E".
3686 ** + Keep track of the row number in p->nLine.
3687 ** + Store the character that terminates the field in p->cTerm. Store
3688 ** EOF on end-of-file.
3689 ** + Report syntax errors on stderr
3691 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
3693 int cSep
= p
->cColSep
;
3694 int rSep
= p
->cRowSep
;
3697 if( c
==EOF
|| seenInterrupt
){
3701 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
3702 import_append_char(p
, c
);
3709 if( p
->z
) p
->z
[p
->n
] = 0;
3714 ** Try to transfer data for table zTable. If an error is seen while
3715 ** moving forward, try to go backwards. The backwards movement won't
3716 ** work for WITHOUT ROWID tables.
3718 static void tryToCloneData(
3723 sqlite3_stmt
*pQuery
= 0;
3724 sqlite3_stmt
*pInsert
= 0;
3729 int nTable
= strlen30(zTable
);
3732 const int spinRate
= 10000;
3734 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
3735 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3737 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
3738 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
3742 n
= sqlite3_column_count(pQuery
);
3743 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
3745 raw_printf(stderr
, "out of memory\n");
3748 sqlite3_snprintf(200+nTable
,zInsert
,
3749 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
3750 i
= strlen30(zInsert
);
3752 memcpy(zInsert
+i
, ",?", 2);
3755 memcpy(zInsert
+i
, ");", 3);
3756 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
3758 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
3759 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
3764 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
3766 switch( sqlite3_column_type(pQuery
, i
) ){
3768 sqlite3_bind_null(pInsert
, i
+1);
3771 case SQLITE_INTEGER
: {
3772 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
3775 case SQLITE_FLOAT
: {
3776 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
3780 sqlite3_bind_text(pInsert
, i
+1,
3781 (const char*)sqlite3_column_text(pQuery
,i
),
3786 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
3787 sqlite3_column_bytes(pQuery
,i
),
3793 rc
= sqlite3_step(pInsert
);
3794 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
3795 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
3796 sqlite3_errmsg(newDb
));
3798 sqlite3_reset(pInsert
);
3800 if( (cnt
%spinRate
)==0 ){
3801 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
3805 if( rc
==SQLITE_DONE
) break;
3806 sqlite3_finalize(pQuery
);
3807 sqlite3_free(zQuery
);
3808 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3810 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3812 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
3815 } /* End for(k=0...) */
3818 sqlite3_finalize(pQuery
);
3819 sqlite3_finalize(pInsert
);
3820 sqlite3_free(zQuery
);
3821 sqlite3_free(zInsert
);
3826 ** Try to transfer all rows of the schema that match zWhere. For
3827 ** each row, invoke xForEach() on the object defined by that row.
3828 ** If an error is encountered while moving forward through the
3829 ** sqlite_master table, try again moving backwards.
3831 static void tryToCloneSchema(
3835 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
3837 sqlite3_stmt
*pQuery
= 0;
3840 const unsigned char *zName
;
3841 const unsigned char *zSql
;
3844 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3845 " WHERE %s", zWhere
);
3846 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3848 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
3849 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
3851 goto end_schema_xfer
;
3853 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
3854 zName
= sqlite3_column_text(pQuery
, 0);
3855 zSql
= sqlite3_column_text(pQuery
, 1);
3856 printf("%s... ", zName
); fflush(stdout
);
3857 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
3859 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
3860 sqlite3_free(zErrMsg
);
3864 xForEach(p
, newDb
, (const char*)zName
);
3868 if( rc
!=SQLITE_DONE
){
3869 sqlite3_finalize(pQuery
);
3870 sqlite3_free(zQuery
);
3871 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3872 " WHERE %s ORDER BY rowid DESC", zWhere
);
3873 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3875 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
3876 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
3878 goto end_schema_xfer
;
3880 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
3881 zName
= sqlite3_column_text(pQuery
, 0);
3882 zSql
= sqlite3_column_text(pQuery
, 1);
3883 printf("%s... ", zName
); fflush(stdout
);
3884 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
3886 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
3887 sqlite3_free(zErrMsg
);
3891 xForEach(p
, newDb
, (const char*)zName
);
3897 sqlite3_finalize(pQuery
);
3898 sqlite3_free(zQuery
);
3902 ** Open a new database file named "zNewDb". Try to recover as much information
3903 ** as possible out of the main database (which might be corrupt) and write it
3906 static void tryToClone(ShellState
*p
, const char *zNewDb
){
3909 if( access(zNewDb
,0)==0 ){
3910 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
3913 rc
= sqlite3_open(zNewDb
, &newDb
);
3915 utf8_printf(stderr
, "Cannot create output database: %s\n",
3916 sqlite3_errmsg(newDb
));
3918 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
3919 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
3920 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
3921 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
3922 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
3923 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3925 sqlite3_close(newDb
);
3929 ** Change the output file back to stdout
3931 static void output_reset(ShellState
*p
){
3932 if( p
->outfile
[0]=='|' ){
3933 #ifndef SQLITE_OMIT_POPEN
3937 output_file_close(p
->out
);
3944 ** Run an SQL command and return the single integer result.
3946 static int db_int(ShellState
*p
, const char *zSql
){
3947 sqlite3_stmt
*pStmt
;
3949 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3950 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
3951 res
= sqlite3_column_int(pStmt
,0);
3953 sqlite3_finalize(pStmt
);
3958 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
3960 static unsigned int get2byteInt(unsigned char *a
){
3961 return (a
[0]<<8) + a
[1];
3963 static unsigned int get4byteInt(unsigned char *a
){
3964 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
3968 ** Implementation of the ".info" command.
3970 ** Return 1 on error, 2 to exit, and 0 otherwise.
3972 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
3973 static const struct { const char *zName
; int ofst
; } aField
[] = {
3974 { "file change counter:", 24 },
3975 { "database page count:", 28 },
3976 { "freelist page count:", 36 },
3977 { "schema cookie:", 40 },
3978 { "schema format:", 44 },
3979 { "default cache size:", 48 },
3980 { "autovacuum top root:", 52 },
3981 { "incremental vacuum:", 64 },
3982 { "text encoding:", 56 },
3983 { "user version:", 60 },
3984 { "application id:", 68 },
3985 { "software version:", 96 },
3987 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
3988 { "number of tables:",
3989 "SELECT count(*) FROM %s WHERE type='table'" },
3990 { "number of indexes:",
3991 "SELECT count(*) FROM %s WHERE type='index'" },
3992 { "number of triggers:",
3993 "SELECT count(*) FROM %s WHERE type='trigger'" },
3994 { "number of views:",
3995 "SELECT count(*) FROM %s WHERE type='view'" },
3997 "SELECT total(length(sql)) FROM %s" },
4001 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
4002 sqlite3_stmt
*pStmt
= 0;
4003 unsigned char aHdr
[100];
4005 if( p
->db
==0 ) return 1;
4006 sqlite3_prepare_v2(p
->db
,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4008 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
4009 if( sqlite3_step(pStmt
)==SQLITE_ROW
4010 && sqlite3_column_bytes(pStmt
,0)>100
4012 memcpy(aHdr
, sqlite3_column_blob(pStmt
,0), 100);
4013 sqlite3_finalize(pStmt
);
4015 raw_printf(stderr
, "unable to read database header\n");
4016 sqlite3_finalize(pStmt
);
4019 i
= get2byteInt(aHdr
+16);
4020 if( i
==1 ) i
= 65536;
4021 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
4022 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
4023 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
4024 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
4025 for(i
=0; i
<ArraySize(aField
); i
++){
4026 int ofst
= aField
[i
].ofst
;
4027 unsigned int val
= get4byteInt(aHdr
+ ofst
);
4028 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
4031 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
4032 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
4033 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
4036 raw_printf(p
->out
, "\n");
4039 zSchemaTab
= sqlite3_mprintf("main.sqlite_master");
4040 }else if( strcmp(zDb
,"temp")==0 ){
4041 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_master");
4043 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_master", zDb
);
4045 for(i
=0; i
<ArraySize(aQuery
); i
++){
4046 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
4047 int val
= db_int(p
, zSql
);
4049 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
4051 sqlite3_free(zSchemaTab
);
4056 ** Print the current sqlite3_errmsg() value to stderr and return 1.
4058 static int shellDatabaseError(sqlite3
*db
){
4059 const char *zErr
= sqlite3_errmsg(db
);
4060 utf8_printf(stderr
, "Error: %s\n", zErr
);
4065 ** Print an out-of-memory message to stderr and return 1.
4067 static int shellNomemError(void){
4068 raw_printf(stderr
, "Error: out of memory\n");
4073 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4074 ** if they match and FALSE (0) if they do not match.
4078 ** '*' Matches any sequence of zero or more characters.
4080 ** '?' Matches exactly one character.
4082 ** [...] Matches one character from the enclosed list of
4085 ** [^...] Matches one character not in the enclosed list.
4087 ** '#' Matches any sequence of one or more digits with an
4088 ** optional + or - sign in front
4090 ** ' ' Any span of whitespace matches any other span of
4093 ** Extra whitespace at the end of z[] is ignored.
4095 static int testcase_glob(const char *zGlob
, const char *z
){
4100 while( (c
= (*(zGlob
++)))!=0 ){
4102 if( !IsSpace(*z
) ) return 0;
4103 while( IsSpace(*zGlob
) ) zGlob
++;
4104 while( IsSpace(*z
) ) z
++;
4106 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
4107 if( c
=='?' && (*(z
++))==0 ) return 0;
4112 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
4117 while( (c2
= (*(z
++)))!=0 ){
4120 if( c2
==0 ) return 0;
4122 if( testcase_glob(zGlob
,z
) ) return 1;
4126 if( (*(z
++))==0 ) return 0;
4132 if( c
==0 ) return 0;
4139 if( c
==']' ) seen
= 1;
4142 while( c2
&& c2
!=']' ){
4143 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
4145 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
4155 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
4157 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
4158 if( !IsDigit(z
[0]) ) return 0;
4160 while( IsDigit(z
[0]) ){ z
++; }
4162 if( c
!=(*(z
++)) ) return 0;
4165 while( IsSpace(*z
) ){ z
++; }
4171 ** Compare the string as a command-line option with either one or two
4172 ** initial "-" characters.
4174 static int optionMatch(const char *zStr
, const char *zOpt
){
4175 if( zStr
[0]!='-' ) return 0;
4177 if( zStr
[0]=='-' ) zStr
++;
4178 return strcmp(zStr
, zOpt
)==0;
4184 int shellDeleteFile(const char *zFilename
){
4187 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
4191 rc
= unlink(zFilename
);
4198 ** The implementation of SQL scalar function fkey_collate_clause(), used
4199 ** by the ".lint fkey-indexes" command. This scalar function is always
4200 ** called with four arguments - the parent table name, the parent column name,
4201 ** the child table name and the child column name.
4203 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4205 ** If either of the named tables or columns do not exist, this function
4206 ** returns an empty string. An empty string is also returned if both tables
4207 ** and columns exist but have the same default collation sequence. Or,
4208 ** if both exist but the default collation sequences are different, this
4209 ** function returns the string " COLLATE <parent-collation>", where
4210 ** <parent-collation> is the default collation sequence of the parent column.
4212 static void shellFkeyCollateClause(
4213 sqlite3_context
*pCtx
,
4215 sqlite3_value
**apVal
4217 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
4218 const char *zParent
;
4219 const char *zParentCol
;
4220 const char *zParentSeq
;
4222 const char *zChildCol
;
4223 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
4227 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
4228 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
4229 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
4230 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
4232 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
4233 rc
= sqlite3_table_column_metadata(
4234 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
4236 if( rc
==SQLITE_OK
){
4237 rc
= sqlite3_table_column_metadata(
4238 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
4242 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
4243 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
4244 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
4251 ** The implementation of dot-command ".lint fkey-indexes".
4253 static int lintFkeyIndexes(
4254 ShellState
*pState
, /* Current shell tool state */
4255 char **azArg
, /* Array of arguments passed to dot command */
4256 int nArg
/* Number of entries in azArg[] */
4258 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
4259 FILE *out
= pState
->out
; /* Stream to write non-error output to */
4260 int bVerbose
= 0; /* If -verbose is present */
4261 int bGroupByParent
= 0; /* If -groupbyparent is present */
4262 int i
; /* To iterate through azArg[] */
4263 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
4264 int rc
; /* Return code */
4265 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
4268 ** This SELECT statement returns one row for each foreign key constraint
4269 ** in the schema of the main database. The column values are:
4271 ** 0. The text of an SQL statement similar to:
4273 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
4275 ** This SELECT is similar to the one that the foreign keys implementation
4276 ** needs to run internally on child tables. If there is an index that can
4277 ** be used to optimize this query, then it can also be used by the FK
4278 ** implementation to optimize DELETE or UPDATE statements on the parent
4281 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4282 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4283 ** contains an index that can be used to optimize the query.
4285 ** 2. Human readable text that describes the child table and columns. e.g.
4287 ** "child_table(child_key1, child_key2)"
4289 ** 3. Human readable text that describes the parent table and columns. e.g.
4291 ** "parent_table(parent_key1, parent_key2)"
4293 ** 4. A full CREATE INDEX statement for an index that could be used to
4294 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4296 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4298 ** 5. The name of the parent table.
4300 ** These six values are used by the C logic below to generate the report.
4304 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
4305 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4306 " || fkey_collate_clause("
4307 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4309 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4310 " || group_concat('*=?', ' AND ') || ')'"
4312 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4314 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4316 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4317 " || ' ON ' || quote(s.name) || '('"
4318 " || group_concat(quote(f.[from]) ||"
4319 " fkey_collate_clause("
4320 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4324 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4325 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4326 "GROUP BY s.name, f.id "
4327 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4329 const char *zGlobIPK
= "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4331 for(i
=2; i
<nArg
; i
++){
4332 int n
= strlen30(azArg
[i
]);
4333 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
4336 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
4341 raw_printf(stderr
, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4344 return SQLITE_ERROR
;
4348 /* Register the fkey_collate_clause() SQL function */
4349 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
4350 0, shellFkeyCollateClause
, 0, 0
4354 if( rc
==SQLITE_OK
){
4355 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
4357 if( rc
==SQLITE_OK
){
4358 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
4361 if( rc
==SQLITE_OK
){
4364 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
4366 sqlite3_stmt
*pExplain
= 0;
4367 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
4368 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
4369 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
4370 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
4371 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
4372 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
4374 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4375 if( rc
!=SQLITE_OK
) break;
4376 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
4377 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
4379 0==sqlite3_strglob(zGlob
, zPlan
)
4380 || 0==sqlite3_strglob(zGlobIPK
, zPlan
)
4383 rc
= sqlite3_finalize(pExplain
);
4384 if( rc
!=SQLITE_OK
) break;
4387 raw_printf(stderr
, "Error: internal error");
4391 && (bVerbose
|| res
==0)
4392 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
4394 raw_printf(out
, "-- Parent table %s\n", zParent
);
4395 sqlite3_free(zPrev
);
4396 zPrev
= sqlite3_mprintf("%s", zParent
);
4400 raw_printf(out
, "%s%s --> %s\n", zIndent
, zCI
, zTarget
);
4401 }else if( bVerbose
){
4402 raw_printf(out
, "%s/* no extra indexes required for %s -> %s */\n",
4403 zIndent
, zFrom
, zTarget
4408 sqlite3_free(zPrev
);
4410 if( rc
!=SQLITE_OK
){
4411 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4414 rc2
= sqlite3_finalize(pSql
);
4415 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
4417 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4420 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4427 ** Implementation of ".lint" dot command.
4429 static int lintDotCommand(
4430 ShellState
*pState
, /* Current shell tool state */
4431 char **azArg
, /* Array of arguments passed to dot command */
4432 int nArg
/* Number of entries in azArg[] */
4435 n
= (nArg
>=2 ? strlen30(azArg
[1]) : 0);
4436 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
4437 return lintFkeyIndexes(pState
, azArg
, nArg
);
4440 raw_printf(stderr
, "Usage %s sub-command ?switches...?\n", azArg
[0]);
4441 raw_printf(stderr
, "Where sub-commands are:\n");
4442 raw_printf(stderr
, " fkey-indexes\n");
4443 return SQLITE_ERROR
;
4446 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4447 /*********************************************************************************
4448 ** The ".archive" or ".ar" command.
4450 static void shellPrepare(
4454 sqlite3_stmt
**ppStmt
4457 if( *pRc
==SQLITE_OK
){
4458 int rc
= sqlite3_prepare_v2(db
, zSql
, -1, ppStmt
, 0);
4459 if( rc
!=SQLITE_OK
){
4460 raw_printf(stderr
, "sql error: %s (%d)\n",
4461 sqlite3_errmsg(db
), sqlite3_errcode(db
)
4468 static void shellPreparePrintf(
4471 sqlite3_stmt
**ppStmt
,
4476 if( *pRc
==SQLITE_OK
){
4480 z
= sqlite3_vmprintf(zFmt
, ap
);
4482 *pRc
= SQLITE_NOMEM
;
4484 shellPrepare(db
, pRc
, z
, ppStmt
);
4490 static void shellFinalize(
4495 sqlite3
*db
= sqlite3_db_handle(pStmt
);
4496 int rc
= sqlite3_finalize(pStmt
);
4497 if( *pRc
==SQLITE_OK
){
4498 if( rc
!=SQLITE_OK
){
4499 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
4506 static void shellReset(
4510 int rc
= sqlite3_reset(pStmt
);
4511 if( *pRc
==SQLITE_OK
){
4512 if( rc
!=SQLITE_OK
){
4513 sqlite3
*db
= sqlite3_db_handle(pStmt
);
4514 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
4520 ** Structure representing a single ".ar" command.
4522 typedef struct ArCommand ArCommand
;
4524 u8 eCmd
; /* An AR_CMD_* value */
4525 u8 bVerbose
; /* True if --verbose */
4526 u8 bZip
; /* True if the archive is a ZIP */
4527 u8 bDryRun
; /* True if --dry-run */
4528 u8 bAppend
; /* True if --append */
4529 int nArg
; /* Number of command arguments */
4530 char *zSrcTable
; /* "sqlar", "zipfile($file)" or "zip" */
4531 const char *zFile
; /* --file argument, or NULL */
4532 const char *zDir
; /* --directory argument, or NULL */
4533 char **azArg
; /* Array of command arguments */
4534 ShellState
*p
; /* Shell state */
4535 sqlite3
*db
; /* Database containing the archive */
4539 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
4541 static int arUsage(FILE *f
){
4544 "Usage: .ar [OPTION...] [FILE...]\n"
4545 "The .ar command manages sqlar archives.\n"
4548 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
4549 " .ar -tf archive.sar # List members of archive.sar\n"
4550 " .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
4552 "Each command line must feature exactly one command option:\n"
4553 " -c, --create Create a new archive\n"
4554 " -u, --update Update or add files to an existing archive\n"
4555 " -t, --list List contents of archive\n"
4556 " -x, --extract Extract files from archive\n"
4558 "And zero or more optional options:\n"
4559 " -v, --verbose Print each filename as it is processed\n"
4560 " -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
4561 " -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
4562 " -n, --dryrun Show the SQL that would have occurred\n"
4563 " -a, --append Append the SQLAR to an existing file\n"
4565 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
4568 return SQLITE_ERROR
;
4572 ** Print an error message for the .ar command to stderr and return
4575 static int arErrorMsg(const char *zFmt
, ...){
4579 z
= sqlite3_vmprintf(zFmt
, ap
);
4581 raw_printf(stderr
, "Error: %s (try \".ar --help\")\n", z
);
4583 return SQLITE_ERROR
;
4587 ** Values for ArCommand.eCmd.
4589 #define AR_CMD_CREATE 1
4590 #define AR_CMD_EXTRACT 2
4591 #define AR_CMD_LIST 3
4592 #define AR_CMD_UPDATE 4
4593 #define AR_CMD_HELP 5
4596 ** Other (non-command) switches.
4598 #define AR_SWITCH_VERBOSE 6
4599 #define AR_SWITCH_FILE 7
4600 #define AR_SWITCH_DIRECTORY 8
4601 #define AR_SWITCH_APPEND 9
4602 #define AR_SWITCH_DRYRUN 10
4604 static int arProcessSwitch(ArCommand
*pAr
, int eSwitch
, const char *zArg
){
4607 case AR_CMD_EXTRACT
:
4612 return arErrorMsg("multiple command options");
4614 pAr
->eCmd
= eSwitch
;
4617 case AR_SWITCH_DRYRUN
:
4620 case AR_SWITCH_VERBOSE
:
4623 case AR_SWITCH_APPEND
:
4627 case AR_SWITCH_FILE
:
4630 case AR_SWITCH_DIRECTORY
:
4639 ** Parse the command line for an ".ar" command. The results are written into
4640 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
4641 ** successfully, otherwise an error message is written to stderr and
4642 ** SQLITE_ERROR returned.
4644 static int arParseCommand(
4645 char **azArg
, /* Array of arguments passed to dot command */
4646 int nArg
, /* Number of entries in azArg[] */
4647 ArCommand
*pAr
/* Populate this object */
4655 { "create", 'c', AR_CMD_CREATE
, 0 },
4656 { "extract", 'x', AR_CMD_EXTRACT
, 0 },
4657 { "list", 't', AR_CMD_LIST
, 0 },
4658 { "update", 'u', AR_CMD_UPDATE
, 0 },
4659 { "help", 'h', AR_CMD_HELP
, 0 },
4660 { "verbose", 'v', AR_SWITCH_VERBOSE
, 0 },
4661 { "file", 'f', AR_SWITCH_FILE
, 1 },
4662 { "directory", 'C', AR_SWITCH_DIRECTORY
, 1 },
4663 { "append", 'a', AR_SWITCH_APPEND
, 0 },
4664 { "dryrun", 'n', AR_SWITCH_DRYRUN
, 0 },
4666 int nSwitch
= sizeof(aSwitch
) / sizeof(struct ArSwitch
);
4667 struct ArSwitch
*pEnd
= &aSwitch
[nSwitch
];
4670 return arUsage(stderr
);
4673 memset(pAr
, 0, sizeof(ArCommand
));
4676 /* Traditional style [tar] invocation */
4679 for(i
=0; z
[i
]; i
++){
4680 const char *zArg
= 0;
4681 struct ArSwitch
*pOpt
;
4682 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
4683 if( z
[i
]==pOpt
->cShort
) break;
4686 return arErrorMsg("unrecognized option: %c", z
[i
]);
4690 return arErrorMsg("option requires an argument: %c",z
[i
]);
4692 zArg
= azArg
[iArg
++];
4694 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
4696 pAr
->nArg
= nArg
-iArg
;
4698 pAr
->azArg
= &azArg
[iArg
];
4701 /* Non-traditional invocation */
4703 for(iArg
=1; iArg
<nArg
; iArg
++){
4707 /* All remaining command line words are command arguments. */
4708 pAr
->azArg
= &azArg
[iArg
];
4709 pAr
->nArg
= nArg
-iArg
;
4716 /* One or more short options */
4718 const char *zArg
= 0;
4719 struct ArSwitch
*pOpt
;
4720 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
4721 if( z
[i
]==pOpt
->cShort
) break;
4724 return arErrorMsg("unrecognized option: %c\n", z
[i
]);
4731 if( iArg
>=(nArg
-1) ){
4732 return arErrorMsg("option requires an argument: %c\n",z
[i
]);
4734 zArg
= azArg
[++iArg
];
4737 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
4739 }else if( z
[2]=='\0' ){
4740 /* A -- option, indicating that all remaining command line words
4741 ** are command arguments. */
4742 pAr
->azArg
= &azArg
[iArg
+1];
4743 pAr
->nArg
= nArg
-iArg
-1;
4747 const char *zArg
= 0; /* Argument for option, if any */
4748 struct ArSwitch
*pMatch
= 0; /* Matching option */
4749 struct ArSwitch
*pOpt
; /* Iterator */
4750 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
4751 const char *zLong
= pOpt
->zLong
;
4752 if( (n
-2)<=strlen30(zLong
) && 0==memcmp(&z
[2], zLong
, n
-2) ){
4754 return arErrorMsg("ambiguous option: %s",z
);
4762 return arErrorMsg("unrecognized option: %s", z
);
4765 if( iArg
>=(nArg
-1) ){
4766 return arErrorMsg("option requires an argument: %s", z
);
4768 zArg
= azArg
[++iArg
];
4770 if( arProcessSwitch(pAr
, pMatch
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
4780 ** This function assumes that all arguments within the ArCommand.azArg[]
4781 ** array refer to archive members, as for the --extract or --list commands.
4782 ** It checks that each of them are present. If any specified file is not
4783 ** present in the archive, an error is printed to stderr and an error
4784 ** code returned. Otherwise, if all specified arguments are present in
4785 ** the archive, SQLITE_OK is returned.
4787 ** This function strips any trailing '/' characters from each argument.
4788 ** This is consistent with the way the [tar] command seems to work on
4791 static int arCheckEntries(ArCommand
*pAr
){
4795 sqlite3_stmt
*pTest
= 0;
4797 shellPreparePrintf(pAr
->db
, &rc
, &pTest
,
4798 "SELECT name FROM %s WHERE name=$name",
4801 j
= sqlite3_bind_parameter_index(pTest
, "$name");
4802 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
4803 char *z
= pAr
->azArg
[i
];
4804 int n
= strlen30(z
);
4806 while( n
>0 && z
[n
-1]=='/' ) n
--;
4808 sqlite3_bind_text(pTest
, j
, z
, -1, SQLITE_STATIC
);
4809 if( SQLITE_ROW
==sqlite3_step(pTest
) ){
4812 shellReset(&rc
, pTest
);
4813 if( rc
==SQLITE_OK
&& bOk
==0 ){
4814 utf8_printf(stderr
, "not found in archive: %s\n", z
);
4818 shellFinalize(&rc
, pTest
);
4824 ** Format a WHERE clause that can be used against the "sqlar" table to
4825 ** identify all archive members that match the command arguments held
4826 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
4827 ** The caller is responsible for eventually calling sqlite3_free() on
4828 ** any non-NULL (*pzWhere) value.
4830 static void arWhereClause(
4833 char **pzWhere
/* OUT: New WHERE clause */
4836 if( *pRc
==SQLITE_OK
){
4838 zWhere
= sqlite3_mprintf("1");
4841 const char *zSep
= "";
4842 for(i
=0; i
<pAr
->nArg
; i
++){
4843 const char *z
= pAr
->azArg
[i
];
4844 zWhere
= sqlite3_mprintf(
4845 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
4846 zWhere
, zSep
, z
, strlen30(z
)+1, z
4849 *pRc
= SQLITE_NOMEM
;
4860 ** Implementation of .ar "lisT" command.
4862 static int arListCommand(ArCommand
*pAr
){
4863 const char *zSql
= "SELECT %s FROM %s WHERE %s";
4864 const char *azCols
[] = {
4866 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
4870 sqlite3_stmt
*pSql
= 0;
4873 rc
= arCheckEntries(pAr
);
4874 arWhereClause(&rc
, pAr
, &zWhere
);
4876 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql
, azCols
[pAr
->bVerbose
],
4877 pAr
->zSrcTable
, zWhere
);
4879 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
4881 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
4882 if( pAr
->bVerbose
){
4883 utf8_printf(pAr
->p
->out
, "%s % 10d %s %s\n",
4884 sqlite3_column_text(pSql
, 0),
4885 sqlite3_column_int(pSql
, 1),
4886 sqlite3_column_text(pSql
, 2),
4887 sqlite3_column_text(pSql
, 3)
4890 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
4894 shellFinalize(&rc
, pSql
);
4900 ** Implementation of .ar "eXtract" command.
4902 static int arExtractCommand(ArCommand
*pAr
){
4906 " writefile(($dir || name), %s, mode, mtime) "
4907 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)";
4909 const char *azExtraArg
[] = {
4910 "sqlar_uncompress(data, sz)",
4914 sqlite3_stmt
*pSql
= 0;
4920 /* If arguments are specified, check that they actually exist within
4921 ** the archive before proceeding. And formulate a WHERE clause to
4923 rc
= arCheckEntries(pAr
);
4924 arWhereClause(&rc
, pAr
, &zWhere
);
4926 if( rc
==SQLITE_OK
){
4928 zDir
= sqlite3_mprintf("%s/", pAr
->zDir
);
4930 zDir
= sqlite3_mprintf("");
4932 if( zDir
==0 ) rc
= SQLITE_NOMEM
;
4935 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql1
,
4936 azExtraArg
[pAr
->bZip
], pAr
->zSrcTable
, zWhere
4939 if( rc
==SQLITE_OK
){
4940 j
= sqlite3_bind_parameter_index(pSql
, "$dir");
4941 sqlite3_bind_text(pSql
, j
, zDir
, -1, SQLITE_STATIC
);
4943 /* Run the SELECT statement twice. The first time, writefile() is called
4944 ** for all archive members that should be extracted. The second time,
4945 ** only for the directories. This is because the timestamps for
4946 ** extracted directories must be reset after they are populated (as
4947 ** populating them changes the timestamp). */
4949 j
= sqlite3_bind_parameter_index(pSql
, "$dirOnly");
4950 sqlite3_bind_int(pSql
, j
, i
);
4952 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
4954 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
4955 if( i
==0 && pAr
->bVerbose
){
4956 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
4960 shellReset(&rc
, pSql
);
4962 shellFinalize(&rc
, pSql
);
4966 sqlite3_free(zWhere
);
4971 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
4973 static int arExecSql(ArCommand
*pAr
, const char *zSql
){
4976 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
4980 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
4982 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
4991 ** Implementation of .ar "create" and "update" commands.
4993 ** Create the "sqlar" table in the database if it does not already exist.
4994 ** Then add each file in the azFile[] array to the archive. Directories
4995 ** are added recursively. If argument bVerbose is non-zero, a message is
4996 ** printed on stdout for each file archived.
4998 ** The create command is the same as update, except that it drops
4999 ** any existing "sqlar" table before beginning.
5001 static int arCreateOrUpdateCommand(
5002 ArCommand
*pAr
, /* Command arguments and options */
5003 int bUpdate
/* true for a --create. false for --update */
5005 const char *zCreate
=
5006 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5007 " name TEXT PRIMARY KEY, -- name of the file\n"
5008 " mode INT, -- access permissions\n"
5009 " mtime INT, -- last modification time\n"
5010 " sz INT, -- original file size\n"
5011 " data BLOB -- compressed content\n"
5013 const char *zDrop
= "DROP TABLE IF EXISTS sqlar";
5014 const char *zInsertFmt
=
5015 "REPLACE INTO sqlar(name,mode,mtime,sz,data)\n"
5020 " CASE substr(lsmode(mode),1,1)\n"
5021 " WHEN '-' THEN length(data)\n"
5022 " WHEN 'd' THEN 0\n"
5024 " CASE WHEN lsmode(mode) LIKE 'd%%' THEN NULL else data END\n"
5025 " FROM fsdir(%Q,%Q)\n"
5026 " WHERE lsmode(mode) NOT LIKE '?%%';";
5027 int i
; /* For iterating through azFile[] */
5028 int rc
; /* Return code */
5030 rc
= arExecSql(pAr
, "SAVEPOINT ar;");
5031 if( rc
!=SQLITE_OK
) return rc
;
5033 rc
= arExecSql(pAr
, zDrop
);
5034 if( rc
!=SQLITE_OK
) return rc
;
5036 rc
= arExecSql(pAr
, zCreate
);
5037 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
5038 char *zSql
= sqlite3_mprintf(zInsertFmt
,
5039 pAr
->bVerbose
? "shell_putsnl(name)" : "name",
5040 pAr
->azArg
[i
], pAr
->zDir
);
5041 rc
= arExecSql(pAr
, zSql
);
5044 if( rc
!=SQLITE_OK
){
5045 arExecSql(pAr
, "ROLLBACK TO ar; RELEASE ar;");
5047 rc
= arExecSql(pAr
, "RELEASE ar;");
5053 ** Implementation of ".ar" dot command.
5055 static int arDotCommand(
5056 ShellState
*pState
, /* Current shell tool state */
5057 char **azArg
, /* Array of arguments passed to dot command */
5058 int nArg
/* Number of entries in azArg[] */
5062 rc
= arParseCommand(azArg
, nArg
, &cmd
);
5063 if( rc
==SQLITE_OK
){
5064 int eDbType
= SHELL_OPEN_UNSPEC
;
5066 cmd
.db
= pState
->db
;
5069 eDbType
= deduceDatabaseType(cmd
.zFile
);
5071 eDbType
= pState
->openMode
;
5073 if( eDbType
==SHELL_OPEN_ZIPFILE
){
5075 cmd
.zSrcTable
= sqlite3_mprintf("zip");
5077 cmd
.zSrcTable
= sqlite3_mprintf("zipfile(%Q)", cmd
.zFile
);
5079 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
5080 utf8_printf(stderr
, "zip archives are read-only\n");
5082 goto end_ar_command
;
5085 }else if( cmd
.zFile
){
5087 if( cmd
.bAppend
) eDbType
= SHELL_OPEN_APPENDVFS
;
5088 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
5089 flags
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
5091 flags
= SQLITE_OPEN_READONLY
;
5095 utf8_printf(pState
->out
, "-- open database '%s'%s\n", cmd
.zFile
,
5096 eDbType
==SHELL_OPEN_APPENDVFS
? " using 'apndvfs'" : "");
5098 rc
= sqlite3_open_v2(cmd
.zFile
, &cmd
.db
, flags
,
5099 eDbType
==SHELL_OPEN_APPENDVFS
? "apndvfs" : 0);
5100 if( rc
!=SQLITE_OK
){
5101 utf8_printf(stderr
, "cannot open file: %s (%s)\n",
5102 cmd
.zFile
, sqlite3_errmsg(cmd
.db
)
5104 goto end_ar_command
;
5106 sqlite3_fileio_init(cmd
.db
, 0, 0);
5107 #ifdef SQLITE_HAVE_ZLIB
5108 sqlite3_sqlar_init(cmd
.db
, 0, 0);
5111 if( cmd
.zSrcTable
==0 ){
5112 if( cmd
.eCmd
!=AR_CMD_CREATE
5113 && sqlite3_table_column_metadata(cmd
.db
,0,"sqlar","name",0,0,0,0,0)
5115 utf8_printf(stderr
, "database does not contain an 'sqlar' table\n");
5117 goto end_ar_command
;
5119 cmd
.zSrcTable
= sqlite3_mprintf("sqlar");
5124 rc
= arCreateOrUpdateCommand(&cmd
, 0);
5127 case AR_CMD_EXTRACT
:
5128 rc
= arExtractCommand(&cmd
);
5132 rc
= arListCommand(&cmd
);
5136 arUsage(pState
->out
);
5140 assert( cmd
.eCmd
==AR_CMD_UPDATE
);
5141 rc
= arCreateOrUpdateCommand(&cmd
, 1);
5146 if( cmd
.db
!=pState
->db
){
5147 sqlite3_close(cmd
.db
);
5149 sqlite3_free(cmd
.zSrcTable
);
5153 /* End of the ".archive" or ".ar" command logic
5154 **********************************************************************************/
5155 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
5159 ** If an input line begins with "." then invoke this routine to
5160 ** process that line.
5162 ** Return 1 on error, 2 to exit, and 0 otherwise.
5164 static int do_meta_command(char *zLine
, ShellState
*p
){
5171 #ifndef SQLITE_OMIT_VIRTUALTABLE
5172 if( p
->expert
.pExpert
){
5173 expertFinish(p
, 1, 0);
5177 /* Parse the input line into tokens.
5179 while( zLine
[h
] && nArg
<ArraySize(azArg
) ){
5180 while( IsSpace(zLine
[h
]) ){ h
++; }
5181 if( zLine
[h
]==0 ) break;
5182 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
5183 int delim
= zLine
[h
++];
5184 azArg
[nArg
++] = &zLine
[h
];
5185 while( zLine
[h
] && zLine
[h
]!=delim
){
5186 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
5189 if( zLine
[h
]==delim
){
5192 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
5194 azArg
[nArg
++] = &zLine
[h
];
5195 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
5196 if( zLine
[h
] ) zLine
[h
++] = 0;
5197 resolve_backslashes(azArg
[nArg
-1]);
5201 /* Process the input line.
5203 if( nArg
==0 ) return 0; /* no tokens, no error */
5204 n
= strlen30(azArg
[0]);
5207 #ifndef SQLITE_OMIT_AUTHORIZATION
5208 if( c
=='a' && strncmp(azArg
[0], "auth", n
)==0 ){
5210 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
5212 goto meta_command_exit
;
5215 if( booleanValue(azArg
[1]) ){
5216 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
5218 sqlite3_set_authorizer(p
->db
, 0, 0);
5223 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5224 if( c
=='a' && strncmp(azArg
[0], "archive", n
)==0 ){
5226 rc
= arDotCommand(p
, azArg
, nArg
);
5230 if( (c
=='b' && n
>=3 && strncmp(azArg
[0], "backup", n
)==0)
5231 || (c
=='s' && n
>=3 && strncmp(azArg
[0], "save", n
)==0)
5233 const char *zDestFile
= 0;
5234 const char *zDb
= 0;
5236 sqlite3_backup
*pBackup
;
5238 for(j
=1; j
<nArg
; j
++){
5239 const char *z
= azArg
[j
];
5241 while( z
[0]=='-' ) z
++;
5242 /* No options to process at this time */
5244 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
5247 }else if( zDestFile
==0 ){
5248 zDestFile
= azArg
[j
];
5251 zDestFile
= azArg
[j
];
5253 raw_printf(stderr
, "too many arguments to .backup\n");
5258 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
5261 if( zDb
==0 ) zDb
= "main";
5262 rc
= sqlite3_open(zDestFile
, &pDest
);
5263 if( rc
!=SQLITE_OK
){
5264 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
5265 sqlite3_close(pDest
);
5269 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
5271 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
5272 sqlite3_close(pDest
);
5275 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
5276 sqlite3_backup_finish(pBackup
);
5277 if( rc
==SQLITE_DONE
){
5280 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
5283 sqlite3_close(pDest
);
5286 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "bail", n
)==0 ){
5288 bail_on_error
= booleanValue(azArg
[1]);
5290 raw_printf(stderr
, "Usage: .bail on|off\n");
5295 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "binary", n
)==0 ){
5297 if( booleanValue(azArg
[1]) ){
5298 setBinaryMode(p
->out
, 1);
5300 setTextMode(p
->out
, 1);
5303 raw_printf(stderr
, "Usage: .binary on|off\n");
5308 if( c
=='c' && strcmp(azArg
[0],"cd")==0 ){
5310 #if defined(_WIN32) || defined(WIN32)
5311 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
5312 rc
= !SetCurrentDirectoryW(z
);
5315 rc
= chdir(azArg
[1]);
5318 utf8_printf(stderr
, "Cannot change to directory \"%s\"\n", azArg
[1]);
5322 raw_printf(stderr
, "Usage: .cd DIRECTORY\n");
5327 /* The undocumented ".breakpoint" command causes a call to the no-op
5328 ** routine named test_breakpoint().
5330 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "breakpoint", n
)==0 ){
5334 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "changes", n
)==0 ){
5336 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
5338 raw_printf(stderr
, "Usage: .changes on|off\n");
5343 /* Cancel output redirection, if it is currently set (by .testcase)
5344 ** Then read the content of the testcase-out.txt file and compare against
5345 ** azArg[1]. If there are differences, report an error and exit.
5347 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "check", n
)==0 ){
5351 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
5353 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
5354 raw_printf(stderr
, "Error: cannot read 'testcase-out.txt'\n");
5356 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
5358 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5359 p
->zTestcase
, azArg
[1], zRes
);
5362 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
5368 if( c
=='c' && strncmp(azArg
[0], "clone", n
)==0 ){
5370 tryToClone(p
, azArg
[1]);
5372 raw_printf(stderr
, "Usage: .clone FILENAME\n");
5377 if( c
=='d' && n
>1 && strncmp(azArg
[0], "databases", n
)==0 ){
5381 memcpy(&data
, p
, sizeof(data
));
5382 data
.showHeader
= 0;
5383 data
.cMode
= data
.mode
= MODE_List
;
5384 sqlite3_snprintf(sizeof(data
.colSeparator
),data
.colSeparator
,": ");
5386 sqlite3_exec(p
->db
, "SELECT name, file FROM pragma_database_list",
5387 callback
, &data
, &zErrMsg
);
5389 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
5390 sqlite3_free(zErrMsg
);
5395 if( c
=='d' && strncmp(azArg
[0], "dbinfo", n
)==0 ){
5396 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
5399 if( c
=='d' && strncmp(azArg
[0], "dump", n
)==0 ){
5400 const char *zLike
= 0;
5402 int savedShowHeader
= p
->showHeader
;
5403 ShellClearFlag(p
, SHFLG_PreserveRowid
|SHFLG_Newlines
);
5404 for(i
=1; i
<nArg
; i
++){
5405 if( azArg
[i
][0]=='-' ){
5406 const char *z
= azArg
[i
]+1;
5407 if( z
[0]=='-' ) z
++;
5408 if( strcmp(z
,"preserve-rowids")==0 ){
5409 #ifdef SQLITE_OMIT_VIRTUALTABLE
5410 raw_printf(stderr
, "The --preserve-rowids option is not compatible"
5411 " with SQLITE_OMIT_VIRTUALTABLE\n");
5413 goto meta_command_exit
;
5415 ShellSetFlag(p
, SHFLG_PreserveRowid
);
5418 if( strcmp(z
,"newlines")==0 ){
5419 ShellSetFlag(p
, SHFLG_Newlines
);
5422 raw_printf(stderr
, "Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
5424 goto meta_command_exit
;
5427 raw_printf(stderr
, "Usage: .dump ?--preserve-rowids? "
5428 "?--newlines? ?LIKE-PATTERN?\n");
5430 goto meta_command_exit
;
5436 /* When playing back a "dump", the content might appear in an order
5437 ** which causes immediate foreign key constraints to be violated.
5438 ** So disable foreign-key constraint enforcement to prevent problems. */
5439 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
5440 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
5441 p
->writableSchema
= 0;
5443 /* Set writable_schema=ON since doing so forces SQLite to initialize
5444 ** as much of the schema as it can even if the sqlite_master table is
5446 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
5449 run_schema_dump_query(p
,
5450 "SELECT name, type, sql FROM sqlite_master "
5451 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
5453 run_schema_dump_query(p
,
5454 "SELECT name, type, sql FROM sqlite_master "
5455 "WHERE name=='sqlite_sequence'"
5457 run_table_dump_query(p
,
5458 "SELECT sql FROM sqlite_master "
5459 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
5463 zSql
= sqlite3_mprintf(
5464 "SELECT name, type, sql FROM sqlite_master "
5465 "WHERE tbl_name LIKE %Q AND type=='table'"
5466 " AND sql NOT NULL", zLike
);
5467 run_schema_dump_query(p
,zSql
);
5469 zSql
= sqlite3_mprintf(
5470 "SELECT sql FROM sqlite_master "
5471 "WHERE sql NOT NULL"
5472 " AND type IN ('index','trigger','view')"
5473 " AND tbl_name LIKE %Q", zLike
);
5474 run_table_dump_query(p
, zSql
, 0);
5477 if( p
->writableSchema
){
5478 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
5479 p
->writableSchema
= 0;
5481 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5482 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
5483 raw_printf(p
->out
, p
->nErr
? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
5484 p
->showHeader
= savedShowHeader
;
5487 if( c
=='e' && strncmp(azArg
[0], "echo", n
)==0 ){
5489 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
5491 raw_printf(stderr
, "Usage: .echo on|off\n");
5496 if( c
=='e' && strncmp(azArg
[0], "eqp", n
)==0 ){
5498 if( strcmp(azArg
[1],"full")==0 ){
5499 p
->autoEQP
= AUTOEQP_full
;
5500 }else if( strcmp(azArg
[1],"trigger")==0 ){
5501 p
->autoEQP
= AUTOEQP_trigger
;
5503 p
->autoEQP
= booleanValue(azArg
[1]);
5506 raw_printf(stderr
, "Usage: .eqp off|on|trigger|full\n");
5511 if( c
=='e' && strncmp(azArg
[0], "exit", n
)==0 ){
5512 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
5516 /* The ".explain" command is automatic now. It is largely pointless. It
5517 ** retained purely for backwards compatibility */
5518 if( c
=='e' && strncmp(azArg
[0], "explain", n
)==0 ){
5521 if( strcmp(azArg
[1],"auto")==0 ){
5524 val
= booleanValue(azArg
[1]);
5527 if( val
==1 && p
->mode
!=MODE_Explain
){
5528 p
->normalMode
= p
->mode
;
5529 p
->mode
= MODE_Explain
;
5532 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
5534 }else if( val
==99 ){
5535 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
5540 #ifndef SQLITE_OMIT_VIRTUALTABLE
5541 if( c
=='e' && strncmp(azArg
[0], "expert", n
)==0 ){
5543 expertDotCommand(p
, azArg
, nArg
);
5547 if( c
=='f' && strncmp(azArg
[0], "fullschema", n
)==0 ){
5551 memcpy(&data
, p
, sizeof(data
));
5552 data
.showHeader
= 0;
5553 data
.cMode
= data
.mode
= MODE_Semi
;
5554 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
5555 data
.cMode
= data
.mode
= MODE_Pretty
;
5559 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
5561 goto meta_command_exit
;
5564 rc
= sqlite3_exec(p
->db
,
5566 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5567 " FROM sqlite_master UNION ALL"
5568 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
5569 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
5571 callback
, &data
, &zErrMsg
5573 if( rc
==SQLITE_OK
){
5574 sqlite3_stmt
*pStmt
;
5575 rc
= sqlite3_prepare_v2(p
->db
,
5576 "SELECT rowid FROM sqlite_master"
5577 " WHERE name GLOB 'sqlite_stat[134]'",
5579 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
5580 sqlite3_finalize(pStmt
);
5583 raw_printf(p
->out
, "/* No STAT tables available */\n");
5585 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
5586 sqlite3_exec(p
->db
, "SELECT 'ANALYZE sqlite_master'",
5587 callback
, &data
, &zErrMsg
);
5588 data
.cMode
= data
.mode
= MODE_Insert
;
5589 data
.zDestTable
= "sqlite_stat1";
5590 shell_exec(p
->db
, "SELECT * FROM sqlite_stat1",
5591 shell_callback
, &data
,&zErrMsg
);
5592 data
.zDestTable
= "sqlite_stat3";
5593 shell_exec(p
->db
, "SELECT * FROM sqlite_stat3",
5594 shell_callback
, &data
,&zErrMsg
);
5595 data
.zDestTable
= "sqlite_stat4";
5596 shell_exec(p
->db
, "SELECT * FROM sqlite_stat4",
5597 shell_callback
, &data
, &zErrMsg
);
5598 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
5602 if( c
=='h' && strncmp(azArg
[0], "headers", n
)==0 ){
5604 p
->showHeader
= booleanValue(azArg
[1]);
5606 raw_printf(stderr
, "Usage: .headers on|off\n");
5611 if( c
=='h' && strncmp(azArg
[0], "help", n
)==0 ){
5612 utf8_printf(p
->out
, "%s", zHelp
);
5615 if( c
=='i' && strncmp(azArg
[0], "import", n
)==0 ){
5616 char *zTable
; /* Insert data into this table */
5617 char *zFile
; /* Name of file to extra content from */
5618 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
5619 int nCol
; /* Number of columns in the table */
5620 int nByte
; /* Number of bytes in an SQL string */
5621 int i
, j
; /* Loop counters */
5622 int needCommit
; /* True to COMMIT or ROLLBACK at end */
5623 int nSep
; /* Number of bytes in p->colSeparator[] */
5624 char *zSql
; /* An SQL statement */
5625 ImportCtx sCtx
; /* Reader context */
5626 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
5627 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close file */
5630 raw_printf(stderr
, "Usage: .import FILE TABLE\n");
5631 goto meta_command_exit
;
5636 memset(&sCtx
, 0, sizeof(sCtx
));
5638 nSep
= strlen30(p
->colSeparator
);
5641 "Error: non-null column separator required for import\n");
5645 raw_printf(stderr
, "Error: multi-character column separators not allowed"
5649 nSep
= strlen30(p
->rowSeparator
);
5651 raw_printf(stderr
, "Error: non-null row separator required for import\n");
5654 if( nSep
==2 && p
->mode
==MODE_Csv
&& strcmp(p
->rowSeparator
, SEP_CrLf
)==0 ){
5655 /* When importing CSV (only), if the row separator is set to the
5656 ** default output row separator, change it to the default input
5657 ** row separator. This avoids having to maintain different input
5658 ** and output row separators. */
5659 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
5660 nSep
= strlen30(p
->rowSeparator
);
5663 raw_printf(stderr
, "Error: multi-character row separators not allowed"
5669 if( sCtx
.zFile
[0]=='|' ){
5670 #ifdef SQLITE_OMIT_POPEN
5671 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
5674 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
5675 sCtx
.zFile
= "<pipe>";
5679 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
5682 if( p
->mode
==MODE_Ascii
){
5683 xRead
= ascii_read_one_field
;
5685 xRead
= csv_read_one_field
;
5688 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
5691 sCtx
.cColSep
= p
->colSeparator
[0];
5692 sCtx
.cRowSep
= p
->rowSeparator
[0];
5693 zSql
= sqlite3_mprintf("SELECT * FROM %s", zTable
);
5695 raw_printf(stderr
, "Error: out of memory\n");
5699 nByte
= strlen30(zSql
);
5700 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
5701 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
5702 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
5703 char *zCreate
= sqlite3_mprintf("CREATE TABLE %s", zTable
);
5705 while( xRead(&sCtx
) ){
5706 zCreate
= sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate
, cSep
, sCtx
.z
);
5708 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
5711 sqlite3_free(zCreate
);
5712 sqlite3_free(sCtx
.z
);
5714 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
5717 zCreate
= sqlite3_mprintf("%z\n)", zCreate
);
5718 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
5719 sqlite3_free(zCreate
);
5721 utf8_printf(stderr
, "CREATE TABLE %s(...) failed: %s\n", zTable
,
5722 sqlite3_errmsg(p
->db
));
5723 sqlite3_free(sCtx
.z
);
5727 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
5731 if (pStmt
) sqlite3_finalize(pStmt
);
5732 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
5736 nCol
= sqlite3_column_count(pStmt
);
5737 sqlite3_finalize(pStmt
);
5739 if( nCol
==0 ) return 0; /* no columns, no error */
5740 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
5742 raw_printf(stderr
, "Error: out of memory\n");
5746 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO \"%w\" VALUES(?", zTable
);
5748 for(i
=1; i
<nCol
; i
++){
5754 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
5757 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
5758 if (pStmt
) sqlite3_finalize(pStmt
);
5762 needCommit
= sqlite3_get_autocommit(p
->db
);
5763 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
5765 int startLine
= sCtx
.nLine
;
5766 for(i
=0; i
<nCol
; i
++){
5767 char *z
= xRead(&sCtx
);
5769 ** Did we reach end-of-file before finding any columns?
5770 ** If so, stop instead of NULL filling the remaining columns.
5772 if( z
==0 && i
==0 ) break;
5774 ** Did we reach end-of-file OR end-of-line before finding any
5775 ** columns in ASCII mode? If so, stop instead of NULL filling
5776 ** the remaining columns.
5778 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
5779 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
5780 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
5781 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
5782 "filling the rest with NULL\n",
5783 sCtx
.zFile
, startLine
, nCol
, i
+1);
5785 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
5788 if( sCtx
.cTerm
==sCtx
.cColSep
){
5792 }while( sCtx
.cTerm
==sCtx
.cColSep
);
5793 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
5795 sCtx
.zFile
, startLine
, nCol
, i
);
5798 sqlite3_step(pStmt
);
5799 rc
= sqlite3_reset(pStmt
);
5800 if( rc
!=SQLITE_OK
){
5801 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
5802 startLine
, sqlite3_errmsg(p
->db
));
5805 }while( sCtx
.cTerm
!=EOF
);
5808 sqlite3_free(sCtx
.z
);
5809 sqlite3_finalize(pStmt
);
5810 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
5813 #ifndef SQLITE_UNTESTABLE
5814 if( c
=='i' && strncmp(azArg
[0], "imposter", n
)==0 ){
5817 sqlite3_stmt
*pStmt
;
5821 utf8_printf(stderr
, "Usage: .imposter INDEX IMPOSTER\n");
5823 goto meta_command_exit
;
5826 zSql
= sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5827 " WHERE name='%q' AND type='index'", azArg
[1]);
5828 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
5830 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
5831 tnum
= sqlite3_column_int(pStmt
, 0);
5833 sqlite3_finalize(pStmt
);
5835 utf8_printf(stderr
, "no such index: \"%s\"\n", azArg
[1]);
5837 goto meta_command_exit
;
5839 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
5840 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
5843 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
5845 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
5848 if( sqlite3_column_int(pStmt
,1)==-1 ){
5851 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
5856 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
5858 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
5861 sqlite3_finalize(pStmt
);
5862 zSql
= sqlite3_mprintf(
5863 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5864 azArg
[2], zCollist
, zCollist
);
5865 sqlite3_free(zCollist
);
5866 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
5867 if( rc
==SQLITE_OK
){
5868 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
5869 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
5871 utf8_printf(stderr
, "Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
5873 utf8_printf(stdout
, "%s;\n", zSql
);
5875 "WARNING: writing to an imposter table will corrupt the index!\n"
5879 raw_printf(stderr
, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
5884 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5886 #ifdef SQLITE_ENABLE_IOTRACE
5887 if( c
=='i' && strncmp(azArg
[0], "iotrace", n
)==0 ){
5888 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
5889 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
5893 }else if( strcmp(azArg
[1], "-")==0 ){
5894 sqlite3IoTrace
= iotracePrintf
;
5897 iotrace
= fopen(azArg
[1], "w");
5899 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
5903 sqlite3IoTrace
= iotracePrintf
;
5909 if( c
=='l' && n
>=5 && strncmp(azArg
[0], "limits", n
)==0 ){
5910 static const struct {
5911 const char *zLimitName
; /* Name of a limit */
5912 int limitCode
; /* Integer code for that limit */
5914 { "length", SQLITE_LIMIT_LENGTH
},
5915 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
5916 { "column", SQLITE_LIMIT_COLUMN
},
5917 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
5918 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
5919 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
5920 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
5921 { "attached", SQLITE_LIMIT_ATTACHED
},
5922 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
5923 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
5924 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
5925 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
5930 for(i
=0; i
<ArraySize(aLimit
); i
++){
5931 printf("%20s %d\n", aLimit
[i
].zLimitName
,
5932 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
5935 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
5937 goto meta_command_exit
;
5940 n2
= strlen30(azArg
[1]);
5941 for(i
=0; i
<ArraySize(aLimit
); i
++){
5942 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
5946 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
5948 goto meta_command_exit
;
5953 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
5954 "enter \".limits\" with no arguments for a list.\n",
5957 goto meta_command_exit
;
5960 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
5961 (int)integerValue(azArg
[2]));
5963 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
5964 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
5968 if( c
=='l' && n
>2 && strncmp(azArg
[0], "lint", n
)==0 ){
5970 lintDotCommand(p
, azArg
, nArg
);
5973 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5974 if( c
=='l' && strncmp(azArg
[0], "load", n
)==0 ){
5975 const char *zFile
, *zProc
;
5978 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
5980 goto meta_command_exit
;
5983 zProc
= nArg
>=3 ? azArg
[2] : 0;
5985 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
5986 if( rc
!=SQLITE_OK
){
5987 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
5988 sqlite3_free(zErrMsg
);
5994 if( c
=='l' && strncmp(azArg
[0], "log", n
)==0 ){
5996 raw_printf(stderr
, "Usage: .log FILENAME\n");
5999 const char *zFile
= azArg
[1];
6000 output_file_close(p
->pLog
);
6001 p
->pLog
= output_file_open(zFile
);
6005 if( c
=='m' && strncmp(azArg
[0], "mode", n
)==0 ){
6006 const char *zMode
= nArg
>=2 ? azArg
[1] : "";
6007 int n2
= strlen30(zMode
);
6009 if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"lines",n2
)==0 ){
6010 p
->mode
= MODE_Line
;
6011 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6012 }else if( c2
=='c' && strncmp(azArg
[1],"columns",n2
)==0 ){
6013 p
->mode
= MODE_Column
;
6014 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6015 }else if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"list",n2
)==0 ){
6016 p
->mode
= MODE_List
;
6017 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
6018 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6019 }else if( c2
=='h' && strncmp(azArg
[1],"html",n2
)==0 ){
6020 p
->mode
= MODE_Html
;
6021 }else if( c2
=='t' && strncmp(azArg
[1],"tcl",n2
)==0 ){
6023 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
6024 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6025 }else if( c2
=='c' && strncmp(azArg
[1],"csv",n2
)==0 ){
6027 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
6028 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
6029 }else if( c2
=='t' && strncmp(azArg
[1],"tabs",n2
)==0 ){
6030 p
->mode
= MODE_List
;
6031 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
6032 }else if( c2
=='i' && strncmp(azArg
[1],"insert",n2
)==0 ){
6033 p
->mode
= MODE_Insert
;
6034 set_table_name(p
, nArg
>=3 ? azArg
[2] : "table");
6035 }else if( c2
=='q' && strncmp(azArg
[1],"quote",n2
)==0 ){
6036 p
->mode
= MODE_Quote
;
6037 }else if( c2
=='a' && strncmp(azArg
[1],"ascii",n2
)==0 ){
6038 p
->mode
= MODE_Ascii
;
6039 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
6040 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
6041 }else if( nArg
==1 ){
6042 raw_printf(p
->out
, "current output mode: %s\n", modeDescr
[p
->mode
]);
6044 raw_printf(stderr
, "Error: mode should be one of: "
6045 "ascii column csv html insert line list quote tabs tcl\n");
6051 if( c
=='n' && strncmp(azArg
[0], "nullvalue", n
)==0 ){
6053 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
6054 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
6056 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
6061 if( c
=='o' && strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
6062 char *zNewFilename
; /* Name of the database file to open */
6063 int iName
= 1; /* Index in azArg[] of the filename */
6064 int newFlag
= 0; /* True to delete file before opening */
6065 /* Close the existing database */
6066 session_close_all(p
);
6067 sqlite3_close(p
->db
);
6070 sqlite3_free(p
->zFreeOnClose
);
6071 p
->zFreeOnClose
= 0;
6072 p
->openMode
= SHELL_OPEN_UNSPEC
;
6073 /* Check for command-line arguments */
6074 for(iName
=1; iName
<nArg
&& azArg
[iName
][0]=='-'; iName
++){
6075 const char *z
= azArg
[iName
];
6076 if( optionMatch(z
,"new") ){
6078 #ifdef SQLITE_HAVE_ZIP
6079 }else if( optionMatch(z
, "zip") ){
6080 p
->openMode
= SHELL_OPEN_ZIPFILE
;
6082 }else if( optionMatch(z
, "append") ){
6083 p
->openMode
= SHELL_OPEN_APPENDVFS
;
6084 }else if( z
[0]=='-' ){
6085 utf8_printf(stderr
, "unknown option: %s\n", z
);
6087 goto meta_command_exit
;
6090 /* If a filename is specified, try to open it first */
6091 zNewFilename
= nArg
>iName
? sqlite3_mprintf("%s", azArg
[iName
]) : 0;
6093 if( newFlag
) shellDeleteFile(zNewFilename
);
6094 p
->zDbFilename
= zNewFilename
;
6097 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
6098 sqlite3_free(zNewFilename
);
6100 p
->zFreeOnClose
= zNewFilename
;
6104 /* As a fall-back open a TEMP database */
6111 && (strncmp(azArg
[0], "output", n
)==0 || strncmp(azArg
[0], "once", n
)==0)
6113 const char *zFile
= nArg
>=2 ? azArg
[1] : "stdout";
6115 utf8_printf(stderr
, "Usage: .%s FILE\n", azArg
[0]);
6117 goto meta_command_exit
;
6119 if( n
>1 && strncmp(azArg
[0], "once", n
)==0 ){
6121 raw_printf(stderr
, "Usage: .once FILE\n");
6123 goto meta_command_exit
;
6130 if( zFile
[0]=='|' ){
6131 #ifdef SQLITE_OMIT_POPEN
6132 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
6136 p
->out
= popen(zFile
+ 1, "w");
6138 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
6142 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
6146 p
->out
= output_file_open(zFile
);
6148 if( strcmp(zFile
,"off")!=0 ){
6149 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
6154 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
6159 if( c
=='p' && n
>=3 && strncmp(azArg
[0], "print", n
)==0 ){
6161 for(i
=1; i
<nArg
; i
++){
6162 if( i
>1 ) raw_printf(p
->out
, " ");
6163 utf8_printf(p
->out
, "%s", azArg
[i
]);
6165 raw_printf(p
->out
, "\n");
6168 if( c
=='p' && strncmp(azArg
[0], "prompt", n
)==0 ){
6170 strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
6173 strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
6177 if( c
=='q' && strncmp(azArg
[0], "quit", n
)==0 ){
6181 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "read", n
)==0 ){
6184 raw_printf(stderr
, "Usage: .read FILE\n");
6186 goto meta_command_exit
;
6188 alt
= fopen(azArg
[1], "rb");
6190 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
6193 rc
= process_input(p
, alt
);
6198 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "restore", n
)==0 ){
6199 const char *zSrcFile
;
6202 sqlite3_backup
*pBackup
;
6206 zSrcFile
= azArg
[1];
6208 }else if( nArg
==3 ){
6209 zSrcFile
= azArg
[2];
6212 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
6214 goto meta_command_exit
;
6216 rc
= sqlite3_open(zSrcFile
, &pSrc
);
6217 if( rc
!=SQLITE_OK
){
6218 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
6219 sqlite3_close(pSrc
);
6223 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
6225 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6226 sqlite3_close(pSrc
);
6229 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
6230 || rc
==SQLITE_BUSY
){
6231 if( rc
==SQLITE_BUSY
){
6232 if( nTimeout
++ >= 3 ) break;
6236 sqlite3_backup_finish(pBackup
);
6237 if( rc
==SQLITE_DONE
){
6239 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
6240 raw_printf(stderr
, "Error: source database is busy\n");
6243 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6246 sqlite3_close(pSrc
);
6250 if( c
=='s' && strncmp(azArg
[0], "scanstats", n
)==0 ){
6252 p
->scanstatsOn
= booleanValue(azArg
[1]);
6253 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6254 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
6257 raw_printf(stderr
, "Usage: .scanstats on|off\n");
6262 if( c
=='s' && strncmp(azArg
[0], "schema", n
)==0 ){
6266 const char *zDiv
= "(";
6267 const char *zName
= 0;
6273 memcpy(&data
, p
, sizeof(data
));
6274 data
.showHeader
= 0;
6275 data
.cMode
= data
.mode
= MODE_Semi
;
6277 for(ii
=1; ii
<nArg
; ii
++){
6278 if( optionMatch(azArg
[ii
],"indent") ){
6279 data
.cMode
= data
.mode
= MODE_Pretty
;
6280 }else if( optionMatch(azArg
[ii
],"debug") ){
6282 }else if( zName
==0 ){
6285 raw_printf(stderr
, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6287 goto meta_command_exit
;
6291 int isMaster
= sqlite3_strlike(zName
, "sqlite_master", 0)==0;
6292 if( isMaster
|| sqlite3_strlike(zName
,"sqlite_temp_master",0)==0 ){
6293 char *new_argv
[2], *new_colv
[2];
6294 new_argv
[0] = sqlite3_mprintf(
6295 "CREATE TABLE %s (\n"
6299 " rootpage integer,\n"
6301 ")", isMaster
? "sqlite_master" : "sqlite_temp_master");
6303 new_colv
[0] = "sql";
6305 callback(&data
, 1, new_argv
, new_colv
);
6306 sqlite3_free(new_argv
[0]);
6310 sqlite3_stmt
*pStmt
= 0;
6311 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
6314 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6315 sqlite3_finalize(pStmt
);
6317 goto meta_command_exit
;
6319 appendText(&sSelect
, "SELECT sql FROM", 0);
6321 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6322 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
6324 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
6325 appendText(&sSelect
, zDiv
, 0);
6326 zDiv
= " UNION ALL ";
6327 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
6328 if( sqlite3_stricmp(zDb
, "main")!=0 ){
6329 appendText(&sSelect
, zDb
, '"');
6331 appendText(&sSelect
, "NULL", 0);
6333 appendText(&sSelect
, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6334 appendText(&sSelect
, zScNum
, 0);
6335 appendText(&sSelect
, " AS snum, ", 0);
6336 appendText(&sSelect
, zDb
, '\'');
6337 appendText(&sSelect
, " AS sname FROM ", 0);
6338 appendText(&sSelect
, zDb
, '"');
6339 appendText(&sSelect
, ".sqlite_master", 0);
6341 sqlite3_finalize(pStmt
);
6342 #ifdef SQLITE_INTROSPECTION_PRAGMAS
6344 appendText(&sSelect
,
6345 " UNION ALL SELECT shell_module_schema(name),"
6346 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6349 appendText(&sSelect
, ") WHERE ", 0);
6351 char *zQarg
= sqlite3_mprintf("%Q", zName
);
6352 if( strchr(zName
, '.') ){
6353 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
6355 appendText(&sSelect
, "lower(tbl_name)", 0);
6357 appendText(&sSelect
, strchr(zName
, '*') ? " GLOB " : " LIKE ", 0);
6358 appendText(&sSelect
, zQarg
, 0);
6359 appendText(&sSelect
, " AND ", 0);
6360 sqlite3_free(zQarg
);
6362 appendText(&sSelect
, "type!='meta' AND sql IS NOT NULL"
6363 " ORDER BY snum, rowid", 0);
6365 utf8_printf(p
->out
, "SQL: %s;\n", sSelect
.z
);
6367 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
6372 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
6373 sqlite3_free(zErrMsg
);
6375 }else if( rc
!= SQLITE_OK
){
6376 raw_printf(stderr
,"Error: querying schema information\n");
6383 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6384 if( c
=='s' && n
==11 && strncmp(azArg
[0], "selecttrace", n
)==0 ){
6385 sqlite3SelectTrace
= (int)integerValue(azArg
[1]);
6389 #if defined(SQLITE_ENABLE_SESSION)
6390 if( c
=='s' && strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
6391 OpenSession
*pSession
= &p
->aSession
[0];
6392 char **azCmd
= &azArg
[1];
6394 int nCmd
= nArg
- 1;
6396 if( nArg
<=1 ) goto session_syntax_error
;
6399 for(iSes
=0; iSes
<p
->nSession
; iSes
++){
6400 if( strcmp(p
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
6402 if( iSes
<p
->nSession
){
6403 pSession
= &p
->aSession
[iSes
];
6407 pSession
= &p
->aSession
[0];
6412 /* .session attach TABLE
6413 ** Invoke the sqlite3session_attach() interface to attach a particular
6414 ** table so that it is never filtered.
6416 if( strcmp(azCmd
[0],"attach")==0 ){
6417 if( nCmd
!=2 ) goto session_syntax_error
;
6418 if( pSession
->p
==0 ){
6420 raw_printf(stderr
, "ERROR: No sessions are open\n");
6422 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
6424 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
6430 /* .session changeset FILE
6431 ** .session patchset FILE
6432 ** Write a changeset or patchset into a file. The file is overwritten.
6434 if( strcmp(azCmd
[0],"changeset")==0 || strcmp(azCmd
[0],"patchset")==0 ){
6436 if( nCmd
!=2 ) goto session_syntax_error
;
6437 if( pSession
->p
==0 ) goto session_not_open
;
6438 out
= fopen(azCmd
[1], "wb");
6440 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n", azCmd
[1]);
6444 if( azCmd
[0][0]=='c' ){
6445 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
6447 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
6450 printf("Error: error code %d\n", rc
);
6454 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
6455 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
6458 sqlite3_free(pChng
);
6464 ** Close the identified session
6466 if( strcmp(azCmd
[0], "close")==0 ){
6467 if( nCmd
!=1 ) goto session_syntax_error
;
6469 session_close(pSession
);
6470 p
->aSession
[iSes
] = p
->aSession
[--p
->nSession
];
6474 /* .session enable ?BOOLEAN?
6475 ** Query or set the enable flag
6477 if( strcmp(azCmd
[0], "enable")==0 ){
6479 if( nCmd
>2 ) goto session_syntax_error
;
6480 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
6482 ii
= sqlite3session_enable(pSession
->p
, ii
);
6483 utf8_printf(p
->out
, "session %s enable flag = %d\n",
6484 pSession
->zName
, ii
);
6488 /* .session filter GLOB ....
6489 ** Set a list of GLOB patterns of table names to be excluded.
6491 if( strcmp(azCmd
[0], "filter")==0 ){
6493 if( nCmd
<2 ) goto session_syntax_error
;
6495 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
6496 sqlite3_free(pSession
->azFilter
[ii
]);
6498 sqlite3_free(pSession
->azFilter
);
6499 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
6500 pSession
->azFilter
= sqlite3_malloc( nByte
);
6501 if( pSession
->azFilter
==0 ){
6502 raw_printf(stderr
, "Error: out or memory\n");
6505 for(ii
=1; ii
<nCmd
; ii
++){
6506 pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
6508 pSession
->nFilter
= ii
-1;
6512 /* .session indirect ?BOOLEAN?
6513 ** Query or set the indirect flag
6515 if( strcmp(azCmd
[0], "indirect")==0 ){
6517 if( nCmd
>2 ) goto session_syntax_error
;
6518 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
6520 ii
= sqlite3session_indirect(pSession
->p
, ii
);
6521 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
6522 pSession
->zName
, ii
);
6527 ** Determine if the session is empty
6529 if( strcmp(azCmd
[0], "isempty")==0 ){
6531 if( nCmd
!=1 ) goto session_syntax_error
;
6533 ii
= sqlite3session_isempty(pSession
->p
);
6534 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
6535 pSession
->zName
, ii
);
6540 ** List all currently open sessions
6542 if( strcmp(azCmd
[0],"list")==0 ){
6543 for(i
=0; i
<p
->nSession
; i
++){
6544 utf8_printf(p
->out
, "%d %s\n", i
, p
->aSession
[i
].zName
);
6548 /* .session open DB NAME
6549 ** Open a new session called NAME on the attached database DB.
6550 ** DB is normally "main".
6552 if( strcmp(azCmd
[0],"open")==0 ){
6554 if( nCmd
!=3 ) goto session_syntax_error
;
6556 if( zName
[0]==0 ) goto session_syntax_error
;
6557 for(i
=0; i
<p
->nSession
; i
++){
6558 if( strcmp(p
->aSession
[i
].zName
,zName
)==0 ){
6559 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
6560 goto meta_command_exit
;
6563 if( p
->nSession
>=ArraySize(p
->aSession
) ){
6564 raw_printf(stderr
, "Maximum of %d sessions\n", ArraySize(p
->aSession
));
6565 goto meta_command_exit
;
6567 pSession
= &p
->aSession
[p
->nSession
];
6568 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
6570 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
6572 goto meta_command_exit
;
6574 pSession
->nFilter
= 0;
6575 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
6577 pSession
->zName
= sqlite3_mprintf("%s", zName
);
6579 /* If no command name matches, show a syntax error */
6580 session_syntax_error
:
6586 /* Undocumented commands for internal testing. Subject to change
6587 ** without notice. */
6588 if( c
=='s' && n
>=10 && strncmp(azArg
[0], "selftest-", 9)==0 ){
6589 if( strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
6591 for(i
=1; i
<nArg
; i
++){
6592 v
= booleanValue(azArg
[i
]);
6593 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
6596 if( strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
6597 int i
; sqlite3_int64 v
;
6598 for(i
=1; i
<nArg
; i
++){
6600 v
= integerValue(azArg
[i
]);
6601 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
6602 utf8_printf(p
->out
, "%s", zBuf
);
6608 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"selftest",n
)==0 ){
6609 int bIsInit
= 0; /* True to initialize the SELFTEST table */
6610 int bVerbose
= 0; /* Verbose output */
6611 int bSelftestExists
; /* True if SELFTEST already exists */
6612 int i
, k
; /* Loop counters */
6613 int nTest
= 0; /* Number of tests runs */
6614 int nErr
= 0; /* Number of errors seen */
6615 ShellText str
; /* Answer for a query */
6616 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
6619 for(i
=1; i
<nArg
; i
++){
6620 const char *z
= azArg
[i
];
6621 if( z
[0]=='-' && z
[1]=='-' ) z
++;
6622 if( strcmp(z
,"-init")==0 ){
6625 if( strcmp(z
,"-v")==0 ){
6629 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
6630 azArg
[i
], azArg
[0]);
6631 raw_printf(stderr
, "Should be one of: --init -v\n");
6633 goto meta_command_exit
;
6636 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
6638 bSelftestExists
= 0;
6640 bSelftestExists
= 1;
6643 createSelftestTable(p
);
6644 bSelftestExists
= 1;
6647 appendText(&str
, "x", 0);
6648 for(k
=bSelftestExists
; k
>=0; k
--){
6650 rc
= sqlite3_prepare_v2(p
->db
,
6651 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6654 rc
= sqlite3_prepare_v2(p
->db
,
6655 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6656 " (1,'run','PRAGMA integrity_check','ok')",
6660 raw_printf(stderr
, "Error querying the selftest table\n");
6662 sqlite3_finalize(pStmt
);
6663 goto meta_command_exit
;
6665 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
6666 int tno
= sqlite3_column_int(pStmt
, 0);
6667 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
6668 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
6669 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
6673 char *zQuote
= sqlite3_mprintf("%q", zSql
);
6674 printf("%d: %s %s\n", tno
, zOp
, zSql
);
6675 sqlite3_free(zQuote
);
6677 if( strcmp(zOp
,"memo")==0 ){
6678 utf8_printf(p
->out
, "%s\n", zSql
);
6680 if( strcmp(zOp
,"run")==0 ){
6684 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
6687 utf8_printf(p
->out
, "Result: %s\n", str
.z
);
6689 if( rc
|| zErrMsg
){
6692 utf8_printf(p
->out
, "%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
6693 sqlite3_free(zErrMsg
);
6694 }else if( strcmp(zAns
,str
.z
)!=0 ){
6697 utf8_printf(p
->out
, "%d: Expected: [%s]\n", tno
, zAns
);
6698 utf8_printf(p
->out
, "%d: Got: [%s]\n", tno
, str
.z
);
6703 "Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
6707 } /* End loop over rows of content from SELFTEST */
6708 sqlite3_finalize(pStmt
);
6709 } /* End loop over k */
6711 utf8_printf(p
->out
, "%d errors out of %d tests\n", nErr
, nTest
);
6714 if( c
=='s' && strncmp(azArg
[0], "separator", n
)==0 ){
6715 if( nArg
<2 || nArg
>3 ){
6716 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
6720 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
6721 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
6724 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
6725 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
6729 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"sha3sum",n
)==0 ){
6730 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
6731 int i
; /* Loop counter */
6732 int bSchema
= 0; /* Also hash the schema */
6733 int bSeparate
= 0; /* Hash each table separately */
6734 int iSize
= 224; /* Hash algorithm to use */
6735 int bDebug
= 0; /* Only show the query that would have run */
6736 sqlite3_stmt
*pStmt
; /* For querying tables names */
6737 char *zSql
; /* SQL to be run */
6738 char *zSep
; /* Separator */
6739 ShellText sSql
; /* Complete SQL for the query to run the hash */
6740 ShellText sQuery
; /* Set of queries used to read all content */
6742 for(i
=1; i
<nArg
; i
++){
6743 const char *z
= azArg
[i
];
6746 if( z
[0]=='-' ) z
++;
6747 if( strcmp(z
,"schema")==0 ){
6750 if( strcmp(z
,"sha3-224")==0 || strcmp(z
,"sha3-256")==0
6751 || strcmp(z
,"sha3-384")==0 || strcmp(z
,"sha3-512")==0
6753 iSize
= atoi(&z
[5]);
6755 if( strcmp(z
,"debug")==0 ){
6759 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
6760 azArg
[i
], azArg
[0]);
6761 raw_printf(stderr
, "Should be one of: --schema"
6762 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6764 goto meta_command_exit
;
6767 raw_printf(stderr
, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6769 goto meta_command_exit
;
6773 if( sqlite3_strlike("sqlite_%", zLike
, 0)==0 ) bSchema
= 1;
6777 zSql
= "SELECT lower(name) FROM sqlite_master"
6778 " WHERE type='table' AND coalesce(rootpage,0)>1"
6779 " UNION ALL SELECT 'sqlite_master'"
6780 " ORDER BY 1 collate nocase";
6782 zSql
= "SELECT lower(name) FROM sqlite_master"
6783 " WHERE type='table' AND coalesce(rootpage,0)>1"
6784 " AND name NOT LIKE 'sqlite_%'"
6785 " ORDER BY 1 collate nocase";
6787 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6790 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
6792 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
6793 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
6794 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
6795 if( strncmp(zTab
, "sqlite_",7)!=0 ){
6796 appendText(&sQuery
,"SELECT * FROM ", 0);
6797 appendText(&sQuery
,zTab
,'"');
6798 appendText(&sQuery
," NOT INDEXED;", 0);
6799 }else if( strcmp(zTab
, "sqlite_master")==0 ){
6800 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6801 " ORDER BY name;", 0);
6802 }else if( strcmp(zTab
, "sqlite_sequence")==0 ){
6803 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
6804 " ORDER BY name;", 0);
6805 }else if( strcmp(zTab
, "sqlite_stat1")==0 ){
6806 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
6807 " ORDER BY tbl,idx;", 0);
6808 }else if( strcmp(zTab
, "sqlite_stat3")==0
6809 || strcmp(zTab
, "sqlite_stat4")==0 ){
6810 appendText(&sQuery
, "SELECT * FROM ", 0);
6811 appendText(&sQuery
, zTab
, 0);
6812 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
6814 appendText(&sSql
, zSep
, 0);
6815 appendText(&sSql
, sQuery
.z
, '\'');
6817 appendText(&sSql
, ",", 0);
6818 appendText(&sSql
, zTab
, '\'');
6821 sqlite3_finalize(pStmt
);
6823 zSql
= sqlite3_mprintf(
6825 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6826 " FROM [sha3sum$query]",
6829 zSql
= sqlite3_mprintf(
6831 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6832 " FROM [sha3sum$query]",
6838 utf8_printf(p
->out
, "%s\n", zSql
);
6840 shell_exec(p
->db
, zSql
, shell_callback
, p
, 0);
6846 && (strncmp(azArg
[0], "shell", n
)==0 || strncmp(azArg
[0],"system",n
)==0)
6851 raw_printf(stderr
, "Usage: .system COMMAND\n");
6853 goto meta_command_exit
;
6855 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
6856 for(i
=2; i
<nArg
; i
++){
6857 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
6862 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
6865 if( c
=='s' && strncmp(azArg
[0], "show", n
)==0 ){
6866 static const char *azBool
[] = { "off", "on", "trigger", "full"};
6869 raw_printf(stderr
, "Usage: .show\n");
6871 goto meta_command_exit
;
6873 utf8_printf(p
->out
, "%12.12s: %s\n","echo",
6874 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
6875 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
6876 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
6877 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
6878 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
6879 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
6880 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
6881 output_c_string(p
->out
, p
->nullValue
);
6882 raw_printf(p
->out
, "\n");
6883 utf8_printf(p
->out
,"%12.12s: %s\n","output",
6884 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
6885 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
6886 output_c_string(p
->out
, p
->colSeparator
);
6887 raw_printf(p
->out
, "\n");
6888 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
6889 output_c_string(p
->out
, p
->rowSeparator
);
6890 raw_printf(p
->out
, "\n");
6891 utf8_printf(p
->out
, "%12.12s: %s\n","stats", azBool
[p
->statsOn
!=0]);
6892 utf8_printf(p
->out
, "%12.12s: ", "width");
6893 for (i
=0;i
<(int)ArraySize(p
->colWidth
) && p
->colWidth
[i
] != 0;i
++) {
6894 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
6896 raw_printf(p
->out
, "\n");
6897 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
6898 p
->zDbFilename
? p
->zDbFilename
: "");
6901 if( c
=='s' && strncmp(azArg
[0], "stats", n
)==0 ){
6903 p
->statsOn
= booleanValue(azArg
[1]);
6904 }else if( nArg
==1 ){
6905 display_stats(p
->db
, p
, 0);
6907 raw_printf(stderr
, "Usage: .stats ?on|off?\n");
6912 if( (c
=='t' && n
>1 && strncmp(azArg
[0], "tables", n
)==0)
6913 || (c
=='i' && (strncmp(azArg
[0], "indices", n
)==0
6914 || strncmp(azArg
[0], "indexes", n
)==0) )
6916 sqlite3_stmt
*pStmt
;
6923 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
6924 if( rc
) return shellDatabaseError(p
->db
);
6926 if( nArg
>2 && c
=='i' ){
6927 /* It is an historical accident that the .indexes command shows an error
6928 ** when called with the wrong number of arguments whereas the .tables
6929 ** command does not. */
6930 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
6932 goto meta_command_exit
;
6934 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
6935 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
6936 if( zDbName
==0 ) continue;
6937 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
6938 if( sqlite3_stricmp(zDbName
, "main")==0 ){
6939 appendText(&s
, "SELECT name FROM ", 0);
6941 appendText(&s
, "SELECT ", 0);
6942 appendText(&s
, zDbName
, '\'');
6943 appendText(&s
, "||'.'||name FROM ", 0);
6945 appendText(&s
, zDbName
, '"');
6946 appendText(&s
, ".sqlite_master ", 0);
6948 appendText(&s
," WHERE type IN ('table','view')"
6949 " AND name NOT LIKE 'sqlite_%'"
6950 " AND name LIKE ?1", 0);
6952 appendText(&s
," WHERE type='index'"
6953 " AND tbl_name LIKE ?1", 0);
6956 rc
= sqlite3_finalize(pStmt
);
6957 appendText(&s
, " ORDER BY 1", 0);
6958 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
6960 if( rc
) return shellDatabaseError(p
->db
);
6962 /* Run the SQL statement prepared by the above block. Store the results
6963 ** as an array of nul-terminated strings in azResult[]. */
6967 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
6969 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
6971 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6974 int n2
= nAlloc
*2 + 10;
6975 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
6977 rc
= shellNomemError();
6983 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
6984 if( 0==azResult
[nRow
] ){
6985 rc
= shellNomemError();
6990 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
6991 rc
= shellDatabaseError(p
->db
);
6994 /* Pretty-print the contents of array azResult[] to the output */
6995 if( rc
==0 && nRow
>0 ){
6996 int len
, maxlen
= 0;
6998 int nPrintCol
, nPrintRow
;
6999 for(i
=0; i
<nRow
; i
++){
7000 len
= strlen30(azResult
[i
]);
7001 if( len
>maxlen
) maxlen
= len
;
7003 nPrintCol
= 80/(maxlen
+2);
7004 if( nPrintCol
<1 ) nPrintCol
= 1;
7005 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
7006 for(i
=0; i
<nPrintRow
; i
++){
7007 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
7008 char *zSp
= j
<nPrintRow
? "" : " ";
7009 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
7010 azResult
[j
] ? azResult
[j
]:"");
7012 raw_printf(p
->out
, "\n");
7016 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
7017 sqlite3_free(azResult
);
7020 /* Begin redirecting output to the file "testcase-out.txt" */
7021 if( c
=='t' && strcmp(azArg
[0],"testcase")==0 ){
7023 p
->out
= output_file_open("testcase-out.txt");
7025 raw_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
7028 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
7030 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
7034 #ifndef SQLITE_UNTESTABLE
7035 if( c
=='t' && n
>=8 && strncmp(azArg
[0], "testctrl", n
)==0 ){
7036 static const struct {
7037 const char *zCtrlName
; /* Name of a test-control option */
7038 int ctrlCode
; /* Integer code for that option */
7039 const char *zUsage
; /* Usage notes */
7041 { "always", SQLITE_TESTCTRL_ALWAYS
, "BOOLEAN" },
7042 { "assert", SQLITE_TESTCTRL_ASSERT
, "BOOLEAN" },
7043 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7044 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7045 { "byteorder", SQLITE_TESTCTRL_BYTEORDER
, "" },
7046 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7047 { "imposter", SQLITE_TESTCTRL_IMPOSTER
, "SCHEMA ON/OFF ROOTPAGE"},
7048 #ifdef SQLITE_N_KEYWORD
7049 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD
, "IDENTIFIER" },
7051 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,"BOOLEAN" },
7052 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
, "BOOLEAN" },
7053 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
, "DISABLE-MASK" },
7055 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE
, "" },
7057 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
, "OFFSET " },
7058 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET
, "" },
7059 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
, "" },
7060 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, "" },
7061 { "reserve", SQLITE_TESTCTRL_RESERVE
, "BYTES-OF-RESERVE" },
7065 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7068 const char *zCmd
= 0;
7071 zCmd
= nArg
>=2 ? azArg
[1] : "help";
7073 /* The argument can optionally begin with "-" or "--" */
7074 if( zCmd
[0]=='-' && zCmd
[1] ){
7076 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
7079 /* --help lists all test-controls */
7080 if( strcmp(zCmd
,"help")==0 ){
7081 utf8_printf(p
->out
, "Available test-controls:\n");
7082 for(i
=0; i
<ArraySize(aCtrl
); i
++){
7083 utf8_printf(p
->out
, " .testctrl %s %s\n",
7084 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
7087 goto meta_command_exit
;
7090 /* convert testctrl text option to value. allow any unique prefix
7091 ** of the option name, or a numerical value. */
7092 n2
= strlen30(zCmd
);
7093 for(i
=0; i
<ArraySize(aCtrl
); i
++){
7094 if( strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
7096 testctrl
= aCtrl
[i
].ctrlCode
;
7099 utf8_printf(stderr
, "Error: ambiguous test-control: \"%s\"\n"
7100 "Use \".testctrl --help\" for help\n", zCmd
);
7102 goto meta_command_exit
;
7107 utf8_printf(stderr
,"Error: unknown test-control: %s\n"
7108 "Use \".testctrl --help\" for help\n", zCmd
);
7112 /* sqlite3_test_control(int, db, int) */
7113 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
7114 case SQLITE_TESTCTRL_RESERVE
:
7116 int opt
= (int)strtol(azArg
[2], 0, 0);
7117 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
7122 /* sqlite3_test_control(int) */
7123 case SQLITE_TESTCTRL_PRNG_SAVE
:
7124 case SQLITE_TESTCTRL_PRNG_RESTORE
:
7125 case SQLITE_TESTCTRL_PRNG_RESET
:
7126 case SQLITE_TESTCTRL_BYTEORDER
:
7128 rc2
= sqlite3_test_control(testctrl
);
7129 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
7133 /* sqlite3_test_control(int, uint) */
7134 case SQLITE_TESTCTRL_PENDING_BYTE
:
7136 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
7137 rc2
= sqlite3_test_control(testctrl
, opt
);
7142 /* sqlite3_test_control(int, int) */
7143 case SQLITE_TESTCTRL_ASSERT
:
7144 case SQLITE_TESTCTRL_ALWAYS
:
7146 int opt
= booleanValue(azArg
[2]);
7147 rc2
= sqlite3_test_control(testctrl
, opt
);
7152 /* sqlite3_test_control(int, int) */
7153 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
7154 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
7156 int opt
= booleanValue(azArg
[2]);
7157 rc2
= sqlite3_test_control(testctrl
, opt
);
7162 /* sqlite3_test_control(int, char *) */
7163 #ifdef SQLITE_N_KEYWORD
7164 case SQLITE_TESTCTRL_ISKEYWORD
:
7166 const char *opt
= azArg
[2];
7167 rc2
= sqlite3_test_control(testctrl
, opt
);
7173 case SQLITE_TESTCTRL_IMPOSTER
:
7175 rc2
= sqlite3_test_control(testctrl
, p
->db
,
7177 integerValue(azArg
[3]),
7178 integerValue(azArg
[4]));
7184 case SQLITE_TESTCTRL_PARSER_COVERAGE
:
7186 sqlite3_test_control(testctrl
, p
->out
);
7192 if( isOk
==0 && iCtrl
>=0 ){
7193 utf8_printf(p
->out
, "Usage: .testctrl %s %s\n", zCmd
, aCtrl
[iCtrl
].zUsage
);
7195 }else if( isOk
==1 ){
7196 raw_printf(p
->out
, "%d\n", rc2
);
7197 }else if( isOk
==2 ){
7198 raw_printf(p
->out
, "0x%08x\n", rc2
);
7201 #endif /* !defined(SQLITE_UNTESTABLE) */
7203 if( c
=='t' && n
>4 && strncmp(azArg
[0], "timeout", n
)==0 ){
7205 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
7208 if( c
=='t' && n
>=5 && strncmp(azArg
[0], "timer", n
)==0 ){
7210 enableTimer
= booleanValue(azArg
[1]);
7211 if( enableTimer
&& !HAS_TIMER
){
7212 raw_printf(stderr
, "Error: timer not available on this system.\n");
7216 raw_printf(stderr
, "Usage: .timer on|off\n");
7221 if( c
=='t' && strncmp(azArg
[0], "trace", n
)==0 ){
7224 raw_printf(stderr
, "Usage: .trace FILE|off\n");
7226 goto meta_command_exit
;
7228 output_file_close(p
->traceOut
);
7229 p
->traceOut
= output_file_open(azArg
[1]);
7230 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7231 if( p
->traceOut
==0 ){
7232 sqlite3_trace_v2(p
->db
, 0, 0, 0);
7234 sqlite3_trace_v2(p
->db
, SQLITE_TRACE_STMT
, sql_trace_callback
,p
->traceOut
);
7239 #if SQLITE_USER_AUTHENTICATION
7240 if( c
=='u' && strncmp(azArg
[0], "user", n
)==0 ){
7242 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
7244 goto meta_command_exit
;
7247 if( strcmp(azArg
[1],"login")==0 ){
7249 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
7251 goto meta_command_exit
;
7253 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]));
7255 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
7258 }else if( strcmp(azArg
[1],"add")==0 ){
7260 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
7262 goto meta_command_exit
;
7264 rc
= sqlite3_user_add(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
7265 booleanValue(azArg
[4]));
7267 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
7270 }else if( strcmp(azArg
[1],"edit")==0 ){
7272 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
7274 goto meta_command_exit
;
7276 rc
= sqlite3_user_change(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
7277 booleanValue(azArg
[4]));
7279 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
7282 }else if( strcmp(azArg
[1],"delete")==0 ){
7284 raw_printf(stderr
, "Usage: .user delete USER\n");
7286 goto meta_command_exit
;
7288 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
7290 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
7294 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
7296 goto meta_command_exit
;
7299 #endif /* SQLITE_USER_AUTHENTICATION */
7301 if( c
=='v' && strncmp(azArg
[0], "version", n
)==0 ){
7302 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
7303 sqlite3_libversion(), sqlite3_sourceid());
7306 if( c
=='v' && strncmp(azArg
[0], "vfsinfo", n
)==0 ){
7307 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
7308 sqlite3_vfs
*pVfs
= 0;
7310 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
7312 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
7313 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
7314 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
7315 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
7320 if( c
=='v' && strncmp(azArg
[0], "vfslist", n
)==0 ){
7322 sqlite3_vfs
*pCurrent
= 0;
7324 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
7326 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
7327 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
7328 pVfs
==pCurrent
? " <--- CURRENT" : "");
7329 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
7330 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
7331 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
7333 raw_printf(p
->out
, "-----------------------------------\n");
7338 if( c
=='v' && strncmp(azArg
[0], "vfsname", n
)==0 ){
7339 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
7342 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
7344 utf8_printf(p
->out
, "%s\n", zVfsName
);
7345 sqlite3_free(zVfsName
);
7350 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7351 if( c
=='w' && strncmp(azArg
[0], "wheretrace", n
)==0 ){
7352 sqlite3WhereTrace
= nArg
>=2 ? booleanValue(azArg
[1]) : 0xff;
7356 if( c
=='w' && strncmp(azArg
[0], "width", n
)==0 ){
7358 assert( nArg
<=ArraySize(azArg
) );
7359 for(j
=1; j
<nArg
&& j
<ArraySize(p
->colWidth
); j
++){
7360 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
7365 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
7366 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
7373 if( p
->outCount
==0 ) output_reset(p
);
7379 ** Return TRUE if a semicolon occurs anywhere in the first N characters
7382 static int line_contains_semicolon(const char *z
, int N
){
7384 for(i
=0; i
<N
; i
++){ if( z
[i
]==';' ) return 1; }
7389 ** Test to see if a line consists entirely of whitespace.
7391 static int _all_whitespace(const char *z
){
7393 if( IsSpace(z
[0]) ) continue;
7394 if( *z
=='/' && z
[1]=='*' ){
7396 while( *z
&& (*z
!='*' || z
[1]!='/') ){ z
++; }
7397 if( *z
==0 ) return 0;
7401 if( *z
=='-' && z
[1]=='-' ){
7403 while( *z
&& *z
!='\n' ){ z
++; }
7404 if( *z
==0 ) return 1;
7413 ** Return TRUE if the line typed in is an SQL command terminator other
7414 ** than a semi-colon. The SQL Server style "go" command is understood
7415 ** as is the Oracle "/".
7417 static int line_is_command_terminator(const char *zLine
){
7418 while( IsSpace(zLine
[0]) ){ zLine
++; };
7419 if( zLine
[0]=='/' && _all_whitespace(&zLine
[1]) ){
7420 return 1; /* Oracle */
7422 if( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o'
7423 && _all_whitespace(&zLine
[2]) ){
7424 return 1; /* SQL Server */
7430 ** Return true if zSql is a complete SQL statement. Return false if it
7431 ** ends in the middle of a string literal or C-style comment.
7433 static int line_is_complete(char *zSql
, int nSql
){
7435 if( zSql
==0 ) return 1;
7438 rc
= sqlite3_complete(zSql
);
7444 ** Run a single line of SQL
7446 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
7451 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
7453 rc
= shell_exec(p
->db
, zSql
, shell_callback
, p
, &zErrMsg
);
7455 if( rc
|| zErrMsg
){
7457 if( in
!=0 || !stdin_is_interactive
){
7458 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
7459 "Error: near line %d:", startline
);
7461 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "Error:");
7464 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrMsg
);
7465 sqlite3_free(zErrMsg
);
7468 utf8_printf(stderr
, "%s %s\n", zPrefix
, sqlite3_errmsg(p
->db
));
7471 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
7472 raw_printf(p
->out
, "changes: %3d total_changes: %d\n",
7473 sqlite3_changes(p
->db
), sqlite3_total_changes(p
->db
));
7480 ** Read input from *in and process it. If *in==0 then input
7481 ** is interactive - the user is typing it it. Otherwise, input
7482 ** is coming from a file or device. A prompt is issued and history
7483 ** is saved only if input is interactive. An interrupt signal will
7484 ** cause this routine to exit immediately, unless input is interactive.
7486 ** Return the number of errors.
7488 static int process_input(ShellState
*p
, FILE *in
){
7489 char *zLine
= 0; /* A single input line */
7490 char *zSql
= 0; /* Accumulated SQL text */
7491 int nLine
; /* Length of current line */
7492 int nSql
= 0; /* Bytes of zSql[] used */
7493 int nAlloc
= 0; /* Allocated zSql[] space */
7494 int nSqlPrior
= 0; /* Bytes of zSql[] used by prior line */
7495 int rc
; /* Error code */
7496 int errCnt
= 0; /* Number of errors seen */
7497 int lineno
= 0; /* Current line number */
7498 int startline
= 0; /* Line number for start of current input */
7500 while( errCnt
==0 || !bail_on_error
|| (in
==0 && stdin_is_interactive
) ){
7502 zLine
= one_input_line(in
, zLine
, nSql
>0);
7505 if( in
==0 && stdin_is_interactive
) printf("\n");
7508 if( seenInterrupt
){
7513 if( nSql
==0 && _all_whitespace(zLine
) ){
7514 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
7517 if( zLine
&& zLine
[0]=='.' && nSql
==0 ){
7518 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
7519 rc
= do_meta_command(zLine
, p
);
7520 if( rc
==2 ){ /* exit requested */
7527 if( line_is_command_terminator(zLine
) && line_is_complete(zSql
, nSql
) ){
7528 memcpy(zLine
,";",2);
7530 nLine
= strlen30(zLine
);
7531 if( nSql
+nLine
+2>=nAlloc
){
7532 nAlloc
= nSql
+nLine
+100;
7533 zSql
= realloc(zSql
, nAlloc
);
7535 raw_printf(stderr
, "Error: out of memory\n");
7542 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
7543 assert( nAlloc
>0 && zSql
!=0 );
7544 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
7548 zSql
[nSql
++] = '\n';
7549 memcpy(zSql
+nSql
, zLine
, nLine
+1);
7552 if( nSql
&& line_contains_semicolon(&zSql
[nSqlPrior
], nSql
-nSqlPrior
)
7553 && sqlite3_complete(zSql
) ){
7554 errCnt
+= runOneSqlLine(p
, zSql
, in
, startline
);
7560 }else if( nSql
&& _all_whitespace(zSql
) ){
7561 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zSql
);
7565 if( nSql
&& !_all_whitespace(zSql
) ){
7566 runOneSqlLine(p
, zSql
, in
, startline
);
7574 ** Return a pathname which is the user's home directory. A
7575 ** 0 return indicates an error of some kind.
7577 static char *find_home_dir(int clearFlag
){
7578 static char *home_dir
= NULL
;
7584 if( home_dir
) return home_dir
;
7586 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7587 && !defined(__RTP__) && !defined(_WRS_KERNEL)
7589 struct passwd
*pwent
;
7590 uid_t uid
= getuid();
7591 if( (pwent
=getpwuid(uid
)) != NULL
) {
7592 home_dir
= pwent
->pw_dir
;
7597 #if defined(_WIN32_WCE)
7598 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7603 #if defined(_WIN32) || defined(WIN32)
7605 home_dir
= getenv("USERPROFILE");
7610 home_dir
= getenv("HOME");
7613 #if defined(_WIN32) || defined(WIN32)
7615 char *zDrive
, *zPath
;
7617 zDrive
= getenv("HOMEDRIVE");
7618 zPath
= getenv("HOMEPATH");
7619 if( zDrive
&& zPath
){
7620 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
7621 home_dir
= malloc( n
);
7622 if( home_dir
==0 ) return 0;
7623 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
7630 #endif /* !_WIN32_WCE */
7633 int n
= strlen30(home_dir
) + 1;
7634 char *z
= malloc( n
);
7635 if( z
) memcpy(z
, home_dir
, n
);
7643 ** Read input from the file given by sqliterc_override. Or if that
7644 ** parameter is NULL, take input from ~/.sqliterc
7646 ** Returns the number of errors.
7648 static void process_sqliterc(
7649 ShellState
*p
, /* Configuration data */
7650 const char *sqliterc_override
/* Name of config file. NULL to use default */
7652 char *home_dir
= NULL
;
7653 const char *sqliterc
= sqliterc_override
;
7657 if (sqliterc
== NULL
) {
7658 home_dir
= find_home_dir(0);
7660 raw_printf(stderr
, "-- warning: cannot find home directory;"
7661 " cannot read ~/.sqliterc\n");
7664 sqlite3_initialize();
7665 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
7668 in
= fopen(sqliterc
,"rb");
7670 if( stdin_is_interactive
){
7671 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
7673 process_input(p
,in
);
7680 ** Show available command line options
7682 static const char zOptions
[] =
7683 " -ascii set output mode to 'ascii'\n"
7684 " -bail stop after hitting an error\n"
7685 " -batch force batch I/O\n"
7686 " -column set output mode to 'column'\n"
7687 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
7688 " -csv set output mode to 'csv'\n"
7689 " -echo print commands before execution\n"
7690 " -init FILENAME read/process named file\n"
7691 " -[no]header turn headers on or off\n"
7692 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7693 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7695 " -help show this message\n"
7696 " -html set output mode to HTML\n"
7697 " -interactive force interactive I/O\n"
7698 " -line set output mode to 'line'\n"
7699 " -list set output mode to 'list'\n"
7700 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
7701 " -mmap N default mmap size set to N\n"
7702 #ifdef SQLITE_ENABLE_MULTIPLEX
7703 " -multiplex enable the multiplexor VFS\n"
7705 " -newline SEP set output row separator. Default: '\\n'\n"
7706 " -nullvalue TEXT set text string for NULL values. Default ''\n"
7707 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7708 " -quote set output mode to 'quote'\n"
7709 " -separator SEP set output column separator. Default: '|'\n"
7710 " -stats print memory stats before each finalize\n"
7711 " -version show SQLite version\n"
7712 " -vfs NAME use NAME as the default VFS\n"
7713 #ifdef SQLITE_ENABLE_VFSTRACE
7714 " -vfstrace enable tracing of all VFS calls\n"
7717 static void usage(int showDetail
){
7719 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
7720 "FILENAME is the name of an SQLite database. A new database is created\n"
7721 "if the file does not previously exist.\n", Argv0
);
7723 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
7725 raw_printf(stderr
, "Use the -help option for additional information\n");
7731 ** Initialize the state information in data
7733 static void main_init(ShellState
*data
) {
7734 memset(data
, 0, sizeof(*data
));
7735 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
7736 data
->autoExplain
= 1;
7737 memcpy(data
->colSeparator
,SEP_Column
, 2);
7738 memcpy(data
->rowSeparator
,SEP_Row
, 2);
7739 data
->showHeader
= 0;
7740 data
->shellFlgs
= SHFLG_Lookaside
;
7741 sqlite3_config(SQLITE_CONFIG_URI
, 1);
7742 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
7743 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
7744 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
7745 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
7749 ** Output text to the console in a font that attracts extra attention.
7752 static void printBold(const char *zText
){
7753 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
7754 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
7755 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
7756 SetConsoleTextAttribute(out
,
7757 FOREGROUND_RED
|FOREGROUND_INTENSITY
7759 printf("%s", zText
);
7760 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
7763 static void printBold(const char *zText
){
7764 printf("\033[1m%s\033[0m", zText
);
7769 ** Get the argument to an --option. Throw an error and die if no argument
7772 static char *cmdline_option_value(int argc
, char **argv
, int i
){
7774 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
7775 argv
[0], argv
[argc
-1]);
7781 #ifndef SQLITE_SHELL_IS_UTF8
7782 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7783 # define SQLITE_SHELL_IS_UTF8 (0)
7785 # define SQLITE_SHELL_IS_UTF8 (1)
7789 #if SQLITE_SHELL_IS_UTF8
7790 int SQLITE_CDECL
main(int argc
, char **argv
){
7792 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
7797 const char *zInitFile
= 0;
7800 int warnInmemoryDb
= 0;
7805 setBinaryMode(stdin
, 0);
7806 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
7807 stdin_is_interactive
= isatty(0);
7808 stdout_is_console
= isatty(1);
7810 #if USE_SYSTEM_SQLITE+0!=1
7811 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
7812 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
7813 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
7818 #if !SQLITE_SHELL_IS_UTF8
7819 sqlite3_initialize();
7820 argv
= sqlite3_malloc64(sizeof(argv
[0])*argc
);
7822 raw_printf(stderr
, "out of memory\n");
7825 for(i
=0; i
<argc
; i
++){
7826 argv
[i
] = sqlite3_win32_unicode_to_utf8(wargv
[i
]);
7828 raw_printf(stderr
, "out of memory\n");
7833 assert( argc
>=1 && argv
&& argv
[0] );
7836 /* Make sure we have a valid signal handler early, before anything
7840 signal(SIGINT
, interrupt_handler
);
7841 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
7842 SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
);
7845 #ifdef SQLITE_SHELL_DBNAME_PROC
7847 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7848 ** of a C-function that will provide the name of the database file. Use
7849 ** this compile-time option to embed this shell program in larger
7851 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7852 SQLITE_SHELL_DBNAME_PROC(&data
.zDbFilename
);
7857 /* Do an initial pass through the command-line argument to locate
7858 ** the name of the database file, the name of the initialization file,
7859 ** the size of the alternative malloc heap,
7860 ** and the first command to execute.
7862 for(i
=1; i
<argc
; i
++){
7866 if( data
.zDbFilename
==0 ){
7867 data
.zDbFilename
= z
;
7869 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7870 ** mean that nothing is read from stdin */
7873 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
7875 raw_printf(stderr
, "out of memory\n");
7881 if( z
[1]=='-' ) z
++;
7882 if( strcmp(z
,"-separator")==0
7883 || strcmp(z
,"-nullvalue")==0
7884 || strcmp(z
,"-newline")==0
7885 || strcmp(z
,"-cmd")==0
7887 (void)cmdline_option_value(argc
, argv
, ++i
);
7888 }else if( strcmp(z
,"-init")==0 ){
7889 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
7890 }else if( strcmp(z
,"-batch")==0 ){
7891 /* Need to check for batch mode here to so we can avoid printing
7892 ** informational messages (like from process_sqliterc) before
7893 ** we do the actual processing of arguments later in a second pass.
7895 stdin_is_interactive
= 0;
7896 }else if( strcmp(z
,"-heap")==0 ){
7897 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7899 sqlite3_int64 szHeap
;
7901 zSize
= cmdline_option_value(argc
, argv
, ++i
);
7902 szHeap
= integerValue(zSize
);
7903 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
7904 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
7906 (void)cmdline_option_value(argc
, argv
, ++i
);
7908 }else if( strcmp(z
,"-pagecache")==0 ){
7910 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
7911 if( sz
>70000 ) sz
= 70000;
7913 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
7914 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
7915 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
7916 data
.shellFlgs
|= SHFLG_Pagecache
;
7917 }else if( strcmp(z
,"-lookaside")==0 ){
7919 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
7921 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
7923 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
7924 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
7925 #ifdef SQLITE_ENABLE_VFSTRACE
7926 }else if( strcmp(z
,"-vfstrace")==0 ){
7927 extern int vfstrace_register(
7928 const char *zTraceName
,
7929 const char *zOldVfsName
,
7930 int (*xOut
)(const char*,void*),
7934 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
7936 #ifdef SQLITE_ENABLE_MULTIPLEX
7937 }else if( strcmp(z
,"-multiplex")==0 ){
7938 extern int sqlite3_multiple_initialize(const char*,int);
7939 sqlite3_multiplex_initialize(0, 1);
7941 }else if( strcmp(z
,"-mmap")==0 ){
7942 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
7943 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
7944 }else if( strcmp(z
,"-vfs")==0 ){
7945 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(cmdline_option_value(argc
,argv
,++i
));
7947 sqlite3_vfs_register(pVfs
, 1);
7949 utf8_printf(stderr
, "no such VFS: \"%s\"\n", argv
[i
]);
7952 #ifdef SQLITE_HAVE_ZIP
7953 }else if( strcmp(z
,"-zip")==0 ){
7954 data
.openMode
= SHELL_OPEN_ZIPFILE
;
7956 }else if( strcmp(z
,"-append")==0 ){
7957 data
.openMode
= SHELL_OPEN_APPENDVFS
;
7960 if( data
.zDbFilename
==0 ){
7961 #ifndef SQLITE_OMIT_MEMORYDB
7962 data
.zDbFilename
= ":memory:";
7963 warnInmemoryDb
= argc
==1;
7965 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
7970 sqlite3_appendvfs_init(0,0,0);
7972 /* Go ahead and open the database file if it already exists. If the
7973 ** file does not exist, delay opening it. This prevents empty database
7974 ** files from being created if a user mistypes the database name argument
7975 ** to the sqlite command-line tool.
7977 if( access(data
.zDbFilename
, 0)==0 ){
7981 /* Process the initialization file if there is one. If no -init option
7982 ** is given on the command line, look for a file named ~/.sqliterc and
7983 ** try to process it.
7985 process_sqliterc(&data
,zInitFile
);
7987 /* Make a second pass through the command-line argument and set
7988 ** options. This second pass is delayed until after the initialization
7989 ** file is processed so that the command-line arguments will override
7990 ** settings in the initialization file.
7992 for(i
=1; i
<argc
; i
++){
7994 if( z
[0]!='-' ) continue;
7995 if( z
[1]=='-' ){ z
++; }
7996 if( strcmp(z
,"-init")==0 ){
7998 }else if( strcmp(z
,"-html")==0 ){
7999 data
.mode
= MODE_Html
;
8000 }else if( strcmp(z
,"-list")==0 ){
8001 data
.mode
= MODE_List
;
8002 }else if( strcmp(z
,"-quote")==0 ){
8003 data
.mode
= MODE_Quote
;
8004 }else if( strcmp(z
,"-line")==0 ){
8005 data
.mode
= MODE_Line
;
8006 }else if( strcmp(z
,"-column")==0 ){
8007 data
.mode
= MODE_Column
;
8008 }else if( strcmp(z
,"-csv")==0 ){
8009 data
.mode
= MODE_Csv
;
8010 memcpy(data
.colSeparator
,",",2);
8011 #ifdef SQLITE_HAVE_ZIP
8012 }else if( strcmp(z
,"-zip")==0 ){
8013 data
.openMode
= SHELL_OPEN_ZIPFILE
;
8015 }else if( strcmp(z
,"-append")==0 ){
8016 data
.openMode
= SHELL_OPEN_APPENDVFS
;
8017 }else if( strcmp(z
,"-ascii")==0 ){
8018 data
.mode
= MODE_Ascii
;
8019 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
8021 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
8023 }else if( strcmp(z
,"-separator")==0 ){
8024 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
8025 "%s",cmdline_option_value(argc
,argv
,++i
));
8026 }else if( strcmp(z
,"-newline")==0 ){
8027 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
8028 "%s",cmdline_option_value(argc
,argv
,++i
));
8029 }else if( strcmp(z
,"-nullvalue")==0 ){
8030 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
8031 "%s",cmdline_option_value(argc
,argv
,++i
));
8032 }else if( strcmp(z
,"-header")==0 ){
8033 data
.showHeader
= 1;
8034 }else if( strcmp(z
,"-noheader")==0 ){
8035 data
.showHeader
= 0;
8036 }else if( strcmp(z
,"-echo")==0 ){
8037 ShellSetFlag(&data
, SHFLG_Echo
);
8038 }else if( strcmp(z
,"-eqp")==0 ){
8039 data
.autoEQP
= AUTOEQP_on
;
8040 }else if( strcmp(z
,"-eqpfull")==0 ){
8041 data
.autoEQP
= AUTOEQP_full
;
8042 }else if( strcmp(z
,"-stats")==0 ){
8044 }else if( strcmp(z
,"-scanstats")==0 ){
8045 data
.scanstatsOn
= 1;
8046 }else if( strcmp(z
,"-backslash")==0 ){
8047 /* Undocumented command-line option: -backslash
8048 ** Causes C-style backslash escapes to be evaluated in SQL statements
8049 ** prior to sending the SQL into SQLite. Useful for injecting
8050 ** crazy bytes in the middle of SQL statements for testing and debugging.
8052 ShellSetFlag(&data
, SHFLG_Backslash
);
8053 }else if( strcmp(z
,"-bail")==0 ){
8055 }else if( strcmp(z
,"-version")==0 ){
8056 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8058 }else if( strcmp(z
,"-interactive")==0 ){
8059 stdin_is_interactive
= 1;
8060 }else if( strcmp(z
,"-batch")==0 ){
8061 stdin_is_interactive
= 0;
8062 }else if( strcmp(z
,"-heap")==0 ){
8064 }else if( strcmp(z
,"-pagecache")==0 ){
8066 }else if( strcmp(z
,"-lookaside")==0 ){
8068 }else if( strcmp(z
,"-mmap")==0 ){
8070 }else if( strcmp(z
,"-vfs")==0 ){
8072 #ifdef SQLITE_ENABLE_VFSTRACE
8073 }else if( strcmp(z
,"-vfstrace")==0 ){
8076 #ifdef SQLITE_ENABLE_MULTIPLEX
8077 }else if( strcmp(z
,"-multiplex")==0 ){
8080 }else if( strcmp(z
,"-help")==0 ){
8082 }else if( strcmp(z
,"-cmd")==0 ){
8083 /* Run commands that follow -cmd first and separately from commands
8084 ** that simply appear on the command-line. This seems goofy. It would
8085 ** be better if all commands ran in the order that they appear. But
8086 ** we retain the goofy behavior for historical compatibility. */
8087 if( i
==argc
-1 ) break;
8088 z
= cmdline_option_value(argc
,argv
,++i
);
8090 rc
= do_meta_command(z
, &data
);
8091 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
8094 rc
= shell_exec(data
.db
, z
, shell_callback
, &data
, &zErrMsg
);
8096 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
8097 if( bail_on_error
) return rc
!=0 ? rc
: 1;
8099 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
8100 if( bail_on_error
) return rc
;
8104 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
8105 raw_printf(stderr
,"Use -help for a list of options.\n");
8108 data
.cMode
= data
.mode
;
8112 /* Run all arguments that do not begin with '-' as if they were separate
8113 ** command-line inputs, except for the argToSkip argument which contains
8114 ** the database filename.
8116 for(i
=0; i
<nCmd
; i
++){
8117 if( azCmd
[i
][0]=='.' ){
8118 rc
= do_meta_command(azCmd
[i
], &data
);
8119 if( rc
) return rc
==2 ? 0 : rc
;
8122 rc
= shell_exec(data
.db
, azCmd
[i
], shell_callback
, &data
, &zErrMsg
);
8124 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
8125 return rc
!=0 ? rc
: 1;
8127 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
8134 /* Run commands received from standard input
8136 if( stdin_is_interactive
){
8141 "SQLite version %s %.19s\n" /*extra-version-info*/
8142 "Enter \".help\" for usage hints.\n",
8143 sqlite3_libversion(), sqlite3_sourceid()
8145 if( warnInmemoryDb
){
8146 printf("Connected to a ");
8147 printBold("transient in-memory database");
8148 printf(".\nUse \".open FILENAME\" to reopen on a "
8149 "persistent database.\n");
8151 zHome
= find_home_dir(0);
8153 nHistory
= strlen30(zHome
) + 20;
8154 if( (zHistory
= malloc(nHistory
))!=0 ){
8155 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
8158 if( zHistory
){ shell_read_history(zHistory
); }
8159 #if HAVE_READLINE || HAVE_EDITLINE
8160 rl_attempted_completion_function
= readline_completion
;
8161 #elif HAVE_LINENOISE
8162 linenoiseSetCompletionCallback(linenoise_completion
);
8164 rc
= process_input(&data
, 0);
8166 shell_stifle_history(2000);
8167 shell_write_history(zHistory
);
8171 rc
= process_input(&data
, stdin
);
8174 set_table_name(&data
, 0);
8176 session_close_all(&data
);
8177 sqlite3_close(data
.db
);
8179 sqlite3_free(data
.zFreeOnClose
);
8181 #if !SQLITE_SHELL_IS_UTF8
8182 for(i
=0; i
<argc
; i
++) sqlite3_free(argv
[i
]);