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 #if SQLITE_USER_AUTHENTICATION
65 # include "sqlite3userauth.h"
70 #if !defined(_WIN32) && !defined(WIN32)
72 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
76 # include <sys/types.h>
80 # include <readline/readline.h>
81 # include <readline/history.h>
85 # include <editline/readline.h>
88 #if HAVE_EDITLINE || HAVE_READLINE
90 # define shell_add_history(X) add_history(X)
91 # define shell_read_history(X) read_history(X)
92 # define shell_write_history(X) write_history(X)
93 # define shell_stifle_history(X) stifle_history(X)
94 # define shell_readline(X) readline(X)
98 # include "linenoise.h"
99 # define shell_add_history(X) linenoiseHistoryAdd(X)
100 # define shell_read_history(X) linenoiseHistoryLoad(X)
101 # define shell_write_history(X) linenoiseHistorySave(X)
102 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
103 # define shell_readline(X) linenoise(X)
107 # define shell_read_history(X)
108 # define shell_write_history(X)
109 # define shell_stifle_history(X)
111 # define SHELL_USE_LOCAL_GETLINE 1
115 #if defined(_WIN32) || defined(WIN32)
118 # define isatty(h) _isatty(h)
120 # define access(f,m) _access((f),(m))
123 # define popen _popen
125 # define pclose _pclose
127 /* Make sure isatty() has a prototype. */
128 extern int isatty(int);
130 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
131 /* popen and pclose are not C89 functions and so are
132 ** sometimes omitted from the <stdio.h> header */
133 extern FILE *popen(const char*,const char*);
134 extern int pclose(FILE*);
136 # define SQLITE_OMIT_POPEN 1
140 #if defined(_WIN32_WCE)
141 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
142 * thus we always assume that we have a console. That can be
143 * overridden with the -batch command line option.
148 /* ctype macros that work with signed characters */
149 #define IsSpace(X) isspace((unsigned char)X)
150 #define IsDigit(X) isdigit((unsigned char)X)
151 #define ToLower(X) (char)tolower((unsigned char)X)
153 #if defined(_WIN32) || defined(WIN32)
156 /* string conversion routines only needed on Win32 */
157 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
158 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
159 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
160 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
163 /* On Windows, we normally run with output mode of TEXT so that \n characters
164 ** are automatically translated into \r\n. However, this behavior needs
165 ** to be disabled in some cases (ex: when generating CSV output and when
166 ** rendering quoted strings that contain \n characters). The following
167 ** routines take care of that.
169 #if defined(_WIN32) || defined(WIN32)
170 static void setBinaryMode(FILE *file
, int isOutput
){
171 if( isOutput
) fflush(file
);
172 _setmode(_fileno(file
), _O_BINARY
);
174 static void setTextMode(FILE *file
, int isOutput
){
175 if( isOutput
) fflush(file
);
176 _setmode(_fileno(file
), _O_TEXT
);
179 # define setBinaryMode(X,Y)
180 # define setTextMode(X,Y)
184 /* True if the timer is enabled */
185 static int enableTimer
= 0;
187 /* Return the current wall-clock time */
188 static sqlite3_int64
timeOfDay(void){
189 static sqlite3_vfs
*clockVfs
= 0;
191 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
192 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
193 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
196 clockVfs
->xCurrentTime(clockVfs
, &r
);
197 t
= (sqlite3_int64
)(r
*86400000.0);
202 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
203 #include <sys/time.h>
204 #include <sys/resource.h>
206 /* VxWorks does not support getrusage() as far as we can determine */
207 #if defined(_WRS_KERNEL) || defined(__RTP__)
209 struct timeval ru_utime
; /* user CPU time used */
210 struct timeval ru_stime
; /* system CPU time used */
212 #define getrusage(A,B) memset(B,0,sizeof(*B))
215 /* Saved resource information for the beginning of an operation */
216 static struct rusage sBegin
; /* CPU time at start */
217 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
220 ** Begin timing an operation
222 static void beginTimer(void){
224 getrusage(RUSAGE_SELF
, &sBegin
);
225 iBegin
= timeOfDay();
229 /* Return the difference of two time_structs in seconds */
230 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
231 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
232 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
236 ** Print the timing results.
238 static void endTimer(void){
240 sqlite3_int64 iEnd
= timeOfDay();
242 getrusage(RUSAGE_SELF
, &sEnd
);
243 printf("Run Time: real %.3f user %f sys %f\n",
244 (iEnd
- iBegin
)*0.001,
245 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
246 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
250 #define BEGIN_TIMER beginTimer()
251 #define END_TIMER endTimer()
254 #elif (defined(_WIN32) || defined(WIN32))
256 /* Saved resource information for the beginning of an operation */
257 static HANDLE hProcess
;
258 static FILETIME ftKernelBegin
;
259 static FILETIME ftUserBegin
;
260 static sqlite3_int64 ftWallBegin
;
261 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
262 LPFILETIME
, LPFILETIME
);
263 static GETPROCTIMES getProcessTimesAddr
= NULL
;
266 ** Check to see if we have timer support. Return 1 if necessary
267 ** support found (or found previously).
269 static int hasTimer(void){
270 if( getProcessTimesAddr
){
273 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
274 ** versions. See if the version we are running on has it, and if it
275 ** does, save off a pointer to it and the current process handle.
277 hProcess
= GetCurrentProcess();
279 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
280 if( NULL
!= hinstLib
){
281 getProcessTimesAddr
=
282 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
283 if( NULL
!= getProcessTimesAddr
){
286 FreeLibrary(hinstLib
);
294 ** Begin timing an operation
296 static void beginTimer(void){
297 if( enableTimer
&& getProcessTimesAddr
){
298 FILETIME ftCreation
, ftExit
;
299 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
300 &ftKernelBegin
,&ftUserBegin
);
301 ftWallBegin
= timeOfDay();
305 /* Return the difference of two FILETIME structs in seconds */
306 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
307 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
308 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
309 return (double) ((i64End
- i64Start
) / 10000000.0);
313 ** Print the timing results.
315 static void endTimer(void){
316 if( enableTimer
&& getProcessTimesAddr
){
317 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
318 sqlite3_int64 ftWallEnd
= timeOfDay();
319 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
320 printf("Run Time: real %.3f user %f sys %f\n",
321 (ftWallEnd
- ftWallBegin
)*0.001,
322 timeDiff(&ftUserBegin
, &ftUserEnd
),
323 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
327 #define BEGIN_TIMER beginTimer()
328 #define END_TIMER endTimer()
329 #define HAS_TIMER hasTimer()
338 ** Used to prevent warnings about unused parameters
340 #define UNUSED_PARAMETER(x) (void)(x)
343 ** If the following flag is set, then command execution stops
344 ** at an error if we are not interactive.
346 static int bail_on_error
= 0;
349 ** Threat stdin as an interactive input if the following variable
350 ** is true. Otherwise, assume stdin is connected to a file or pipe.
352 static int stdin_is_interactive
= 1;
355 ** On Windows systems we have to know if standard output is a console
356 ** in order to translate UTF-8 into MBCS. The following variable is
357 ** true if translation is required.
359 static int stdout_is_console
= 1;
362 ** The following is the open SQLite database. We make a pointer
363 ** to this database a static variable so that it can be accessed
364 ** by the SIGINT handler to interrupt database processing.
366 static sqlite3
*globalDb
= 0;
369 ** True if an interrupt (Control-C) has been received.
371 static volatile int seenInterrupt
= 0;
374 ** This is the name of our program. It is set in main(), used
375 ** in a number of other places, mostly for error messages.
380 ** Prompt strings. Initialized in main. Settable with
381 ** .prompt main continue
383 static char mainPrompt
[20]; /* First line prompt. default: "sqlite> "*/
384 static char continuePrompt
[20]; /* Continuation prompt. default: " ...> " */
387 ** Render output like fprintf(). Except, if the output is going to the
388 ** console and if this is running on a Windows machine, translate the
389 ** output from UTF-8 into MBCS.
391 #if defined(_WIN32) || defined(WIN32)
392 void utf8_printf(FILE *out
, const char *zFormat
, ...){
394 va_start(ap
, zFormat
);
395 if( stdout_is_console
&& (out
==stdout
|| out
==stderr
) ){
396 char *z1
= sqlite3_vmprintf(zFormat
, ap
);
397 char *z2
= sqlite3_win32_utf8_to_mbcs_v2(z1
, 0);
402 vfprintf(out
, zFormat
, ap
);
406 #elif !defined(utf8_printf)
407 # define utf8_printf fprintf
411 ** Render output like fprintf(). This should not be used on anything that
412 ** includes string formatting (e.g. "%s").
414 #if !defined(raw_printf)
415 # define raw_printf fprintf
419 ** Write I/O traces to the following stream.
421 #ifdef SQLITE_ENABLE_IOTRACE
422 static FILE *iotrace
= 0;
426 ** This routine works like printf in that its first argument is a
427 ** format string and subsequent arguments are values to be substituted
428 ** in place of % fields. The result of formatting this string
429 ** is written to iotrace.
431 #ifdef SQLITE_ENABLE_IOTRACE
432 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
435 if( iotrace
==0 ) return;
436 va_start(ap
, zFormat
);
437 z
= sqlite3_vmprintf(zFormat
, ap
);
439 utf8_printf(iotrace
, "%s", z
);
445 ** Output string zUtf to stream pOut as w characters. If w is negative,
446 ** then right-justify the text. W is the width in UTF-8 characters, not
447 ** in bytes. This is different from the %*.*s specification in printf
448 ** since with %*.*s the width is measured in bytes, not characters.
450 static void utf8_width_print(FILE *pOut
, int w
, const char *zUtf
){
453 int aw
= w
<0 ? -w
: w
;
455 if( aw
>(int)sizeof(zBuf
)/3 ) aw
= (int)sizeof(zBuf
)/3;
456 for(i
=n
=0; zUtf
[i
]; i
++){
457 if( (zUtf
[i
]&0xc0)!=0x80 ){
460 do{ i
++; }while( (zUtf
[i
]&0xc0)==0x80 );
466 utf8_printf(pOut
, "%.*s", i
, zUtf
);
468 utf8_printf(pOut
, "%*s%s", aw
-n
, "", zUtf
);
470 utf8_printf(pOut
, "%s%*s", zUtf
, aw
-n
, "");
476 ** Determines if a string is a number of not.
478 static int isNumber(const char *z
, int *realnum
){
479 if( *z
=='-' || *z
=='+' ) z
++;
484 if( realnum
) *realnum
= 0;
485 while( IsDigit(*z
) ){ z
++; }
488 if( !IsDigit(*z
) ) return 0;
489 while( IsDigit(*z
) ){ z
++; }
490 if( realnum
) *realnum
= 1;
492 if( *z
=='e' || *z
=='E' ){
494 if( *z
=='+' || *z
=='-' ) z
++;
495 if( !IsDigit(*z
) ) return 0;
496 while( IsDigit(*z
) ){ z
++; }
497 if( realnum
) *realnum
= 1;
503 ** Compute a string length that is limited to what can be stored in
504 ** lower 30 bits of a 32-bit signed integer.
506 static int strlen30(const char *z
){
508 while( *z2
){ z2
++; }
509 return 0x3fffffff & (int)(z2
- z
);
513 ** Return the length of a string in characters. Multibyte UTF8 characters
514 ** count as a single character.
516 static int strlenChar(const char *z
){
519 if( (0xc0&*(z
++))!=0x80 ) n
++;
525 ** This routine reads a line of text from FILE in, stores
526 ** the text in memory obtained from malloc() and returns a pointer
527 ** to the text. NULL is returned at end of file, or if malloc()
530 ** If zLine is not NULL then it is a malloced buffer returned from
531 ** a previous call to this routine that may be reused.
533 static char *local_getline(char *zLine
, FILE *in
){
534 int nLine
= zLine
==0 ? 0 : 100;
539 nLine
= nLine
*2 + 100;
540 zLine
= realloc(zLine
, nLine
);
541 if( zLine
==0 ) return 0;
543 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
551 while( zLine
[n
] ) n
++;
552 if( n
>0 && zLine
[n
-1]=='\n' ){
554 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
559 #if defined(_WIN32) || defined(WIN32)
560 /* For interactive input on Windows systems, translate the
561 ** multi-byte characterset characters into UTF-8. */
562 if( stdin_is_interactive
&& in
==stdin
){
563 char *zTrans
= sqlite3_win32_mbcs_to_utf8_v2(zLine
, 0);
565 int nTrans
= strlen30(zTrans
)+1;
567 zLine
= realloc(zLine
, nTrans
);
569 sqlite3_free(zTrans
);
573 memcpy(zLine
, zTrans
, nTrans
);
574 sqlite3_free(zTrans
);
577 #endif /* defined(_WIN32) || defined(WIN32) */
582 ** Retrieve a single line of input text.
584 ** If in==0 then read from standard input and prompt before each line.
585 ** If isContinuation is true, then a continuation prompt is appropriate.
586 ** If isContinuation is zero, then the main prompt should be used.
588 ** If zPrior is not NULL then it is a buffer from a prior call to this
589 ** routine that can be reused.
591 ** The result is stored in space obtained from malloc() and must either
592 ** be freed by the caller or else passed back into this routine via the
593 ** zPrior argument for reuse.
595 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
599 zResult
= local_getline(zPrior
, in
);
601 zPrompt
= isContinuation
? continuePrompt
: mainPrompt
;
602 #if SHELL_USE_LOCAL_GETLINE
603 printf("%s", zPrompt
);
605 zResult
= local_getline(zPrior
, stdin
);
608 zResult
= shell_readline(zPrompt
);
609 if( zResult
&& *zResult
) shell_add_history(zResult
);
615 ** A variable length string to which one can append text.
617 typedef struct ShellText ShellText
;
625 ** Initialize and destroy a ShellText object
627 static void initText(ShellText
*p
){
628 memset(p
, 0, sizeof(*p
));
630 static void freeText(ShellText
*p
){
635 /* zIn is either a pointer to a NULL-terminated string in memory obtained
636 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
637 ** added to zIn, and the result returned in memory obtained from malloc().
638 ** zIn, if it was not NULL, is freed.
640 ** If the third argument, quote, is not '\0', then it is used as a
641 ** quote character for zAppend.
643 static void appendText(ShellText
*p
, char const *zAppend
, char quote
){
646 int nAppend
= strlen30(zAppend
);
648 len
= nAppend
+p
->n
+1;
651 for(i
=0; i
<nAppend
; i
++){
652 if( zAppend
[i
]==quote
) len
++;
656 if( p
->n
+len
>=p
->nAlloc
){
657 p
->nAlloc
= p
->nAlloc
*2 + len
+ 20;
658 p
->z
= realloc(p
->z
, p
->nAlloc
);
660 memset(p
, 0, sizeof(*p
));
666 char *zCsr
= p
->z
+p
->n
;
668 for(i
=0; i
<nAppend
; i
++){
669 *zCsr
++ = zAppend
[i
];
670 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
673 p
->n
= (int)(zCsr
- p
->z
);
676 memcpy(p
->z
+p
->n
, zAppend
, nAppend
);
683 ** Attempt to determine if identifier zName needs to be quoted, either
684 ** because it contains non-alphanumeric characters, or because it is an
685 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
686 ** that quoting is required.
688 ** Return '"' if quoting is required. Return 0 if no quoting is required.
690 static char quoteChar(const char *zName
){
691 /* All SQLite keywords, in alphabetical order */
692 static const char *azKeywords
[] = {
693 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
694 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
695 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
696 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
697 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
698 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
699 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
700 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
701 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
702 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
703 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
704 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
705 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
706 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
707 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
708 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
709 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
712 int i
, lwr
, upr
, mid
, c
;
713 if( !isalpha((unsigned char)zName
[0]) && zName
[0]!='_' ) return '"';
714 for(i
=0; zName
[i
]; i
++){
715 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ) return '"';
718 upr
= sizeof(azKeywords
)/sizeof(azKeywords
[0]) - 1;
721 c
= sqlite3_stricmp(azKeywords
[mid
], zName
);
722 if( c
==0 ) return '"';
733 ** Construct a fake object name and column list to describe the structure
734 ** of the view, virtual table, or table valued function zSchema.zName.
736 static char *shellFakeSchema(
737 sqlite3
*db
, /* The database connection containing the vtab */
738 const char *zSchema
, /* Schema of the database holding the vtab */
739 const char *zName
/* The name of the virtual table */
741 sqlite3_stmt
*pStmt
= 0;
748 zSql
= sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
749 zSchema
? zSchema
: "main", zName
);
750 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
754 cQuote
= quoteChar(zSchema
);
755 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")==0 ) cQuote
= 0;
756 appendText(&s
, zSchema
, cQuote
);
757 appendText(&s
, ".", 0);
759 cQuote
= quoteChar(zName
);
760 appendText(&s
, zName
, cQuote
);
761 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
762 const char *zCol
= (const char*)sqlite3_column_text(pStmt
, 1);
764 appendText(&s
, zDiv
, 0);
766 cQuote
= quoteChar(zCol
);
767 appendText(&s
, zCol
, cQuote
);
769 appendText(&s
, ")", 0);
770 sqlite3_finalize(pStmt
);
779 ** SQL function: shell_module_schema(X)
781 ** Return a fake schema for the table-valued function or eponymous virtual
784 static void shellModuleSchema(
785 sqlite3_context
*pCtx
,
787 sqlite3_value
**apVal
789 const char *zName
= (const char*)sqlite3_value_text(apVal
[0]);
790 char *zFake
= shellFakeSchema(sqlite3_context_db_handle(pCtx
), 0, zName
);
792 sqlite3_result_text(pCtx
, sqlite3_mprintf("/* %z */", zFake
),
798 ** SQL function: shell_add_schema(S,X)
800 ** Add the schema name X to the CREATE statement in S and return the result.
803 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
808 ** CREATE UNIQUE INDEX
811 ** CREATE VIRTUAL TABLE
813 ** This UDF is used by the .schema command to insert the schema name of
814 ** attached databases into the middle of the sqlite_master.sql field.
816 static void shellAddSchemaName(
817 sqlite3_context
*pCtx
,
819 sqlite3_value
**apVal
821 static const char *aPrefix
[] = {
830 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
831 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
832 const char *zName
= (const char*)sqlite3_value_text(apVal
[2]);
833 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
834 if( zIn
!=0 && strncmp(zIn
, "CREATE ", 7)==0 ){
835 for(i
=0; i
<(int)(sizeof(aPrefix
)/sizeof(aPrefix
[0])); i
++){
836 int n
= strlen30(aPrefix
[i
]);
837 if( strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
841 char cQuote
= quoteChar(zSchema
);
842 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")!=0 ){
843 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
845 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
849 && aPrefix
[i
][0]=='V'
850 && (zFake
= shellFakeSchema(db
, zSchema
, zName
))!=0
853 z
= sqlite3_mprintf("%s\n/* %z */", zIn
, zFake
);
855 z
= sqlite3_mprintf("%z\n/* %z */", z
, zFake
);
859 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
865 sqlite3_result_value(pCtx
, apVal
[0]);
869 ** The source code for several run-time loadable extensions is inserted
870 ** below by the ../tool/mkshellc.tcl script. Before processing that included
871 ** code, we need to override some macros to make the included program code
872 ** work here in the middle of this regular program.
874 #define SQLITE_EXTENSION_INIT1
875 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
877 INCLUDE
../ext
/misc
/shathree
.c
878 INCLUDE
../ext
/misc
/fileio
.c
879 INCLUDE
../ext
/misc
/completion
.c
880 INCLUDE
../ext
/expert
/sqlite3expert
.h
881 INCLUDE
../ext
/expert
/sqlite3expert
.c
883 #if defined(SQLITE_ENABLE_SESSION)
885 ** State information for a single open session
887 typedef struct OpenSession OpenSession
;
889 char *zName
; /* Symbolic name for this session */
890 int nFilter
; /* Number of xFilter rejection GLOB patterns */
891 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
892 sqlite3_session
*p
; /* The open session */
897 ** Shell output mode information from before ".explain on",
898 ** saved so that it can be restored by ".explain off"
900 typedef struct SavedModeInfo SavedModeInfo
;
901 struct SavedModeInfo
{
902 int valid
; /* Is there legit data in here? */
903 int mode
; /* Mode prior to ".explain on" */
904 int showHeader
; /* The ".header" setting prior to ".explain on" */
905 int colWidth
[100]; /* Column widths prior to ".explain on" */
908 typedef struct ExpertInfo ExpertInfo
;
910 sqlite3expert
*pExpert
;
915 ** State information about the database connection is contained in an
916 ** instance of the following structure.
918 typedef struct ShellState ShellState
;
920 sqlite3
*db
; /* The database */
921 int autoExplain
; /* Automatically turn on .explain mode */
922 int autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
923 int statsOn
; /* True to display memory stats before each finalize */
924 int scanstatsOn
; /* True to display scan stats before each finalize */
925 int outCount
; /* Revert to stdout when reaching zero */
926 int cnt
; /* Number of records displayed so far */
927 FILE *out
; /* Write results here */
928 FILE *traceOut
; /* Output for sqlite3_trace() */
929 int nErr
; /* Number of errors seen */
930 int mode
; /* An output mode setting */
931 int cMode
; /* temporary output mode for the current query */
932 int normalMode
; /* Output mode before ".explain on" */
933 int writableSchema
; /* True if PRAGMA writable_schema=ON */
934 int showHeader
; /* True to show column names in List or Column mode */
935 int nCheck
; /* Number of ".check" commands run */
936 unsigned shellFlgs
; /* Various flags */
937 char *zDestTable
; /* Name of destination table when MODE_Insert */
938 char zTestcase
[30]; /* Name of current test case */
939 char colSeparator
[20]; /* Column separator character for several modes */
940 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
941 int colWidth
[100]; /* Requested width of each column when in column mode*/
942 int actualWidth
[100]; /* Actual width of each column */
943 char nullValue
[20]; /* The text to print when a NULL comes back from
945 char outfile
[FILENAME_MAX
]; /* Filename for *out */
946 const char *zDbFilename
; /* name of the database file */
947 char *zFreeOnClose
; /* Filename to free when closing */
948 const char *zVfs
; /* Name of VFS to use */
949 sqlite3_stmt
*pStmt
; /* Current statement if any. */
950 FILE *pLog
; /* Write log output here */
951 int *aiIndent
; /* Array of indents used in MODE_Explain */
952 int nIndent
; /* Size of array aiIndent[] */
953 int iIndent
; /* Index of current op in aiIndent[] */
954 #if defined(SQLITE_ENABLE_SESSION)
955 int nSession
; /* Number of active sessions */
956 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
958 ExpertInfo expert
; /* Valid if previous command was ".expert OPT..." */
961 /* Allowed values for ShellState.autoEQP
963 #define AUTOEQP_off 0
965 #define AUTOEQP_trigger 2
966 #define AUTOEQP_full 3
969 ** These are the allowed shellFlgs values
971 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
972 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
973 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
974 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
975 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
976 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
977 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
980 ** Macros for testing and setting shellFlgs
982 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
983 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
984 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
987 ** These are the allowed modes.
989 #define MODE_Line 0 /* One column per line. Blank line between records */
990 #define MODE_Column 1 /* One record per line in neat columns */
991 #define MODE_List 2 /* One record per line with a separator */
992 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
993 #define MODE_Html 4 /* Generate an XHTML table */
994 #define MODE_Insert 5 /* Generate SQL "insert" statements */
995 #define MODE_Quote 6 /* Quote values as for SQL */
996 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
997 #define MODE_Csv 8 /* Quote strings, numbers are plain */
998 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
999 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1000 #define MODE_Pretty 11 /* Pretty-print schemas */
1002 static const char *modeDescr
[] = {
1018 ** These are the column/row/line separators used by the various
1019 ** import/export modes.
1021 #define SEP_Column "|"
1022 #define SEP_Row "\n"
1023 #define SEP_Tab "\t"
1024 #define SEP_Space " "
1025 #define SEP_Comma ","
1026 #define SEP_CrLf "\r\n"
1027 #define SEP_Unit "\x1F"
1028 #define SEP_Record "\x1E"
1031 ** Number of elements in an array
1033 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
1036 ** A callback for the sqlite3_log() interface.
1038 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
1039 ShellState
*p
= (ShellState
*)pArg
;
1040 if( p
->pLog
==0 ) return;
1041 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
1046 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1048 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
1050 char *zBlob
= (char *)pBlob
;
1051 raw_printf(out
,"X'");
1052 for(i
=0; i
<nBlob
; i
++){ raw_printf(out
,"%02x",zBlob
[i
]&0xff); }
1053 raw_printf(out
,"'");
1057 ** Find a string that is not found anywhere in z[]. Return a pointer
1060 ** Try to use zA and zB first. If both of those are already found in z[]
1061 ** then make up some string and store it in the buffer zBuf.
1063 static const char *unused_string(
1064 const char *z
, /* Result must not appear anywhere in z */
1065 const char *zA
, const char *zB
, /* Try these first */
1066 char *zBuf
/* Space to store a generated string */
1069 if( strstr(z
, zA
)==0 ) return zA
;
1070 if( strstr(z
, zB
)==0 ) return zB
;
1072 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
1073 }while( strstr(z
,zBuf
)!=0 );
1078 ** Output the given string as a quoted string using SQL quoting conventions.
1080 ** See also: output_quoted_escaped_string()
1082 static void output_quoted_string(FILE *out
, const char *z
){
1085 setBinaryMode(out
, 1);
1086 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1088 utf8_printf(out
,"'%s'",z
);
1090 raw_printf(out
, "'");
1092 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1095 utf8_printf(out
, "%.*s", i
, z
);
1099 raw_printf(out
, "'");
1107 raw_printf(out
, "'");
1109 setTextMode(out
, 1);
1113 ** Output the given string as a quoted string using SQL quoting conventions.
1114 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1115 ** get corrupted by end-of-line translation facilities in some operating
1118 ** This is like output_quoted_string() but with the addition of the \r\n
1119 ** escape mechanism.
1121 static void output_quoted_escaped_string(FILE *out
, const char *z
){
1124 setBinaryMode(out
, 1);
1125 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1127 utf8_printf(out
,"'%s'",z
);
1129 const char *zNL
= 0;
1130 const char *zCR
= 0;
1133 char zBuf1
[20], zBuf2
[20];
1134 for(i
=0; z
[i
]; i
++){
1135 if( z
[i
]=='\n' ) nNL
++;
1136 if( z
[i
]=='\r' ) nCR
++;
1139 raw_printf(out
, "replace(");
1140 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1143 raw_printf(out
, "replace(");
1144 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1146 raw_printf(out
, "'");
1148 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1151 utf8_printf(out
, "%.*s", i
, z
);
1155 raw_printf(out
, "'");
1163 raw_printf(out
, "%s", zNL
);
1166 raw_printf(out
, "%s", zCR
);
1168 raw_printf(out
, "'");
1170 raw_printf(out
, ",'%s',char(13))", zCR
);
1173 raw_printf(out
, ",'%s',char(10))", zNL
);
1176 setTextMode(out
, 1);
1180 ** Output the given string as a quoted according to C or TCL quoting rules.
1182 static void output_c_string(FILE *out
, const char *z
){
1185 while( (c
= *(z
++))!=0 ){
1192 }else if( c
=='\t' ){
1195 }else if( c
=='\n' ){
1198 }else if( c
=='\r' ){
1201 }else if( !isprint(c
&0xff) ){
1202 raw_printf(out
, "\\%03o", c
&0xff);
1211 ** Output the given string with characters that are special to
1214 static void output_html_string(FILE *out
, const char *z
){
1226 utf8_printf(out
,"%.*s",i
,z
);
1229 raw_printf(out
,"<");
1230 }else if( z
[i
]=='&' ){
1231 raw_printf(out
,"&");
1232 }else if( z
[i
]=='>' ){
1233 raw_printf(out
,">");
1234 }else if( z
[i
]=='\"' ){
1235 raw_printf(out
,""");
1236 }else if( z
[i
]=='\'' ){
1237 raw_printf(out
,"'");
1246 ** If a field contains any character identified by a 1 in the following
1247 ** array, then the string must be quoted for CSV.
1249 static const char needCsvQuote
[] = {
1250 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1251 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1252 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1253 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1254 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1255 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1256 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1257 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1258 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1259 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1260 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1261 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1262 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1263 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1264 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1265 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1269 ** Output a single term of CSV. Actually, p->colSeparator is used for
1270 ** the separator, which may or may not be a comma. p->nullValue is
1271 ** the null value. Strings are quoted if necessary. The separator
1272 ** is only issued if bSep is true.
1274 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
1277 utf8_printf(out
,"%s",p
->nullValue
);
1280 int nSep
= strlen30(p
->colSeparator
);
1281 for(i
=0; z
[i
]; i
++){
1282 if( needCsvQuote
[((unsigned char*)z
)[i
]]
1283 || (z
[i
]==p
->colSeparator
[0] &&
1284 (nSep
==1 || memcmp(z
, p
->colSeparator
, nSep
)==0)) ){
1290 char *zQuoted
= sqlite3_mprintf("\"%w\"", z
);
1291 utf8_printf(out
, "%s", zQuoted
);
1292 sqlite3_free(zQuoted
);
1294 utf8_printf(out
, "%s", z
);
1298 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1303 ** This routine runs when the user presses Ctrl-C
1305 static void interrupt_handler(int NotUsed
){
1306 UNUSED_PARAMETER(NotUsed
);
1308 if( seenInterrupt
>2 ) exit(1);
1309 if( globalDb
) sqlite3_interrupt(globalDb
);
1312 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1314 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1316 static BOOL WINAPI
ConsoleCtrlHandler(
1317 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
1319 if( dwCtrlType
==CTRL_C_EVENT
){
1320 interrupt_handler(0);
1327 #ifndef SQLITE_OMIT_AUTHORIZATION
1329 ** When the ".auth ON" is set, the following authorizer callback is
1330 ** invoked. It always returns SQLITE_OK.
1332 static int shellAuth(
1340 ShellState
*p
= (ShellState
*)pClientData
;
1341 static const char *azAction
[] = { 0,
1342 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1343 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1344 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1345 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1346 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1347 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1348 "PRAGMA", "READ", "SELECT",
1349 "TRANSACTION", "UPDATE", "ATTACH",
1350 "DETACH", "ALTER_TABLE", "REINDEX",
1351 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1352 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1360 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
1362 raw_printf(p
->out
, " ");
1364 output_c_string(p
->out
, az
[i
]);
1366 raw_printf(p
->out
, "NULL");
1369 raw_printf(p
->out
, "\n");
1375 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1377 ** This routine converts some CREATE TABLE statements for shadow tables
1378 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1380 static void printSchemaLine(FILE *out
, const char *z
, const char *zTail
){
1381 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
1382 utf8_printf(out
, "CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
1384 utf8_printf(out
, "%s%s", z
, zTail
);
1387 static void printSchemaLineN(FILE *out
, char *z
, int n
, const char *zTail
){
1390 printSchemaLine(out
, z
, zTail
);
1395 ** This is the callback routine that the shell
1396 ** invokes for each row of a query result.
1398 static int shell_callback(
1400 int nArg
, /* Number of result columns */
1401 char **azArg
, /* Text of each result column */
1402 char **azCol
, /* Column names */
1403 int *aiType
/* Column types */
1406 ShellState
*p
= (ShellState
*)pArg
;
1408 if( azArg
==0 ) return 0;
1412 if( azArg
==0 ) break;
1413 for(i
=0; i
<nArg
; i
++){
1414 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
1415 if( len
>w
) w
= len
;
1417 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1418 for(i
=0; i
<nArg
; i
++){
1419 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
1420 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
1426 static const int aExplainWidths
[] = {4, 13, 4, 4, 4, 13, 2, 13};
1427 const int *colWidth
;
1430 if( p
->cMode
==MODE_Column
){
1431 colWidth
= p
->colWidth
;
1432 showHdr
= p
->showHeader
;
1433 rowSep
= p
->rowSeparator
;
1435 colWidth
= aExplainWidths
;
1440 for(i
=0; i
<nArg
; i
++){
1442 if( i
<ArraySize(p
->colWidth
) ){
1448 w
= strlenChar(azCol
[i
] ? azCol
[i
] : "");
1450 n
= strlenChar(azArg
&& azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1453 if( i
<ArraySize(p
->actualWidth
) ){
1454 p
->actualWidth
[i
] = w
;
1457 utf8_width_print(p
->out
, w
, azCol
[i
]);
1458 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1462 for(i
=0; i
<nArg
; i
++){
1464 if( i
<ArraySize(p
->actualWidth
) ){
1465 w
= p
->actualWidth
[i
];
1470 utf8_printf(p
->out
,"%-*.*s%s",w
,w
,
1471 "----------------------------------------------------------"
1472 "----------------------------------------------------------",
1473 i
==nArg
-1 ? rowSep
: " ");
1477 if( azArg
==0 ) break;
1478 for(i
=0; i
<nArg
; i
++){
1480 if( i
<ArraySize(p
->actualWidth
) ){
1481 w
= p
->actualWidth
[i
];
1485 if( p
->cMode
==MODE_Explain
&& azArg
[i
] && strlenChar(azArg
[i
])>w
){
1486 w
= strlenChar(azArg
[i
]);
1488 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
1489 if( p
->iIndent
<p
->nIndent
){
1490 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
1494 utf8_width_print(p
->out
, w
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1495 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1499 case MODE_Semi
: { /* .schema and .fullschema output */
1500 printSchemaLine(p
->out
, azArg
[0], ";\n");
1503 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
1511 if( azArg
[0]==0 ) break;
1512 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
1513 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
1515 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
1518 z
= sqlite3_mprintf("%s", azArg
[0]);
1520 for(i
=0; IsSpace(z
[i
]); i
++){}
1521 for(; (c
= z
[i
])!=0; i
++){
1523 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
1524 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
1525 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
1530 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
1532 if( strlen30(z
)>=79 ){
1533 for(i
=j
=0; (c
= z
[i
])!=0; i
++){
1536 }else if( c
=='"' || c
=='\'' || c
=='`' ){
1544 if( nLine
>0 && nParen
==0 && j
>0 ){
1545 printSchemaLineN(p
->out
, z
, j
, "\n");
1550 if( nParen
==1 && (c
=='(' || c
==',' || c
=='\n') ){
1552 printSchemaLineN(p
->out
, z
, j
, "\n ");
1555 while( IsSpace(z
[i
+1]) ){ i
++; }
1560 printSchemaLine(p
->out
, z
, ";\n");
1565 if( p
->cnt
++==0 && p
->showHeader
){
1566 for(i
=0; i
<nArg
; i
++){
1567 utf8_printf(p
->out
,"%s%s",azCol
[i
],
1568 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
1571 if( azArg
==0 ) break;
1572 for(i
=0; i
<nArg
; i
++){
1574 if( z
==0 ) z
= p
->nullValue
;
1575 utf8_printf(p
->out
, "%s", z
);
1577 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1579 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1585 if( p
->cnt
++==0 && p
->showHeader
){
1586 raw_printf(p
->out
,"<TR>");
1587 for(i
=0; i
<nArg
; i
++){
1588 raw_printf(p
->out
,"<TH>");
1589 output_html_string(p
->out
, azCol
[i
]);
1590 raw_printf(p
->out
,"</TH>\n");
1592 raw_printf(p
->out
,"</TR>\n");
1594 if( azArg
==0 ) break;
1595 raw_printf(p
->out
,"<TR>");
1596 for(i
=0; i
<nArg
; i
++){
1597 raw_printf(p
->out
,"<TD>");
1598 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1599 raw_printf(p
->out
,"</TD>\n");
1601 raw_printf(p
->out
,"</TR>\n");
1605 if( p
->cnt
++==0 && p
->showHeader
){
1606 for(i
=0; i
<nArg
; i
++){
1607 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
1608 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1610 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1612 if( azArg
==0 ) break;
1613 for(i
=0; i
<nArg
; i
++){
1614 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1615 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1617 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1621 setBinaryMode(p
->out
, 1);
1622 if( p
->cnt
++==0 && p
->showHeader
){
1623 for(i
=0; i
<nArg
; i
++){
1624 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
1626 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1629 for(i
=0; i
<nArg
; i
++){
1630 output_csv(p
, azArg
[i
], i
<nArg
-1);
1632 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1634 setTextMode(p
->out
, 1);
1638 if( azArg
==0 ) break;
1639 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
1640 if( p
->showHeader
){
1641 raw_printf(p
->out
,"(");
1642 for(i
=0; i
<nArg
; i
++){
1643 if( i
>0 ) raw_printf(p
->out
, ",");
1644 if( quoteChar(azCol
[i
]) ){
1645 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
1646 utf8_printf(p
->out
, "%s", z
);
1649 raw_printf(p
->out
, "%s", azCol
[i
]);
1652 raw_printf(p
->out
,")");
1655 for(i
=0; i
<nArg
; i
++){
1656 raw_printf(p
->out
, i
>0 ? "," : " VALUES(");
1657 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
1658 utf8_printf(p
->out
,"NULL");
1659 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
1660 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
1661 output_quoted_string(p
->out
, azArg
[i
]);
1663 output_quoted_escaped_string(p
->out
, azArg
[i
]);
1665 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
1666 utf8_printf(p
->out
,"%s", azArg
[i
]);
1667 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
1669 double r
= sqlite3_column_double(p
->pStmt
, i
);
1670 sqlite3_snprintf(50,z
,"%!.20g", r
);
1671 raw_printf(p
->out
, "%s", z
);
1672 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
1673 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
1674 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
1675 output_hex_blob(p
->out
, pBlob
, nBlob
);
1676 }else if( isNumber(azArg
[i
], 0) ){
1677 utf8_printf(p
->out
,"%s", azArg
[i
]);
1678 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
1679 output_quoted_string(p
->out
, azArg
[i
]);
1681 output_quoted_escaped_string(p
->out
, azArg
[i
]);
1684 raw_printf(p
->out
,");\n");
1688 if( azArg
==0 ) break;
1689 if( p
->cnt
==0 && p
->showHeader
){
1690 for(i
=0; i
<nArg
; i
++){
1691 if( i
>0 ) raw_printf(p
->out
, ",");
1692 output_quoted_string(p
->out
, azCol
[i
]);
1694 raw_printf(p
->out
,"\n");
1697 for(i
=0; i
<nArg
; i
++){
1698 if( i
>0 ) raw_printf(p
->out
, ",");
1699 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
1700 utf8_printf(p
->out
,"NULL");
1701 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
1702 output_quoted_string(p
->out
, azArg
[i
]);
1703 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
1704 utf8_printf(p
->out
,"%s", azArg
[i
]);
1705 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
1707 double r
= sqlite3_column_double(p
->pStmt
, i
);
1708 sqlite3_snprintf(50,z
,"%!.20g", r
);
1709 raw_printf(p
->out
, "%s", z
);
1710 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
1711 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
1712 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
1713 output_hex_blob(p
->out
, pBlob
, nBlob
);
1714 }else if( isNumber(azArg
[i
], 0) ){
1715 utf8_printf(p
->out
,"%s", azArg
[i
]);
1717 output_quoted_string(p
->out
, azArg
[i
]);
1720 raw_printf(p
->out
,"\n");
1724 if( p
->cnt
++==0 && p
->showHeader
){
1725 for(i
=0; i
<nArg
; i
++){
1726 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1727 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
1729 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1731 if( azArg
==0 ) break;
1732 for(i
=0; i
<nArg
; i
++){
1733 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1734 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1736 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1744 ** This is the callback routine that the SQLite library
1745 ** invokes for each row of a query result.
1747 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
1748 /* since we don't have type info, call the shell_callback with a NULL value */
1749 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
1753 ** This is the callback routine from sqlite3_exec() that appends all
1754 ** output onto the end of a ShellText object.
1756 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
1757 ShellText
*p
= (ShellText
*)pArg
;
1759 UNUSED_PARAMETER(az
);
1760 if( azArg
==0 ) return 0;
1761 if( p
->n
) appendText(p
, "|", 0);
1762 for(i
=0; i
<nArg
; i
++){
1763 if( i
) appendText(p
, ",", 0);
1764 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
1770 ** Generate an appropriate SELFTEST table in the main database.
1772 static void createSelftestTable(ShellState
*p
){
1775 "SAVEPOINT selftest_init;\n"
1776 "CREATE TABLE IF NOT EXISTS selftest(\n"
1777 " tno INTEGER PRIMARY KEY,\n" /* Test number */
1778 " op TEXT,\n" /* Operator: memo run */
1779 " cmd TEXT,\n" /* Command text */
1780 " ans TEXT\n" /* Desired answer */
1782 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
1783 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
1784 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
1785 " 'memo','Tests generated by --init');\n"
1786 "INSERT INTO [_shell$self]\n"
1788 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
1789 "FROM sqlite_master ORDER BY 2'',224))',\n"
1790 " hex(sha3_query('SELECT type,name,tbl_name,sql "
1791 "FROM sqlite_master ORDER BY 2',224));\n"
1792 "INSERT INTO [_shell$self]\n"
1794 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
1795 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
1796 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
1798 " SELECT name FROM sqlite_master\n"
1799 " WHERE type='table'\n"
1800 " AND name<>'selftest'\n"
1801 " AND coalesce(rootpage,0)>0\n"
1804 "INSERT INTO [_shell$self]\n"
1805 " VALUES('run','PRAGMA integrity_check','ok');\n"
1806 "INSERT INTO selftest(tno,op,cmd,ans)"
1807 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
1808 "DROP TABLE [_shell$self];"
1811 utf8_printf(stderr
, "SELFTEST initialization failure: %s\n", zErrMsg
);
1812 sqlite3_free(zErrMsg
);
1814 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
1819 ** Set the destination table field of the ShellState structure to
1820 ** the name of the table given. Escape any quote characters in the
1823 static void set_table_name(ShellState
*p
, const char *zName
){
1828 if( p
->zDestTable
){
1829 free(p
->zDestTable
);
1832 if( zName
==0 ) return;
1833 cQuote
= quoteChar(zName
);
1834 n
= strlen30(zName
);
1835 if( cQuote
) n
+= n
+2;
1836 z
= p
->zDestTable
= malloc( n
+1 );
1838 raw_printf(stderr
,"Error: out of memory\n");
1842 if( cQuote
) z
[n
++] = cQuote
;
1843 for(i
=0; zName
[i
]; i
++){
1845 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
1847 if( cQuote
) z
[n
++] = cQuote
;
1853 ** Execute a query statement that will generate SQL output. Print
1854 ** the result columns, comma-separated, on a line and then add a
1855 ** semicolon terminator to the end of that line.
1857 ** If the number of columns is 1 and that column contains text "--"
1858 ** then write the semicolon on a separate line. That way, if a
1859 ** "--" comment occurs at the end of the statement, the comment
1860 ** won't consume the semicolon terminator.
1862 static int run_table_dump_query(
1863 ShellState
*p
, /* Query context */
1864 const char *zSelect
, /* SELECT statement to extract content */
1865 const char *zFirstRow
/* Print before first row, if not NULL */
1867 sqlite3_stmt
*pSelect
;
1872 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
1873 if( rc
!=SQLITE_OK
|| !pSelect
){
1874 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
1875 sqlite3_errmsg(p
->db
));
1876 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
1879 rc
= sqlite3_step(pSelect
);
1880 nResult
= sqlite3_column_count(pSelect
);
1881 while( rc
==SQLITE_ROW
){
1883 utf8_printf(p
->out
, "%s", zFirstRow
);
1886 z
= (const char*)sqlite3_column_text(pSelect
, 0);
1887 utf8_printf(p
->out
, "%s", z
);
1888 for(i
=1; i
<nResult
; i
++){
1889 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
1892 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
1894 raw_printf(p
->out
, "\n;\n");
1896 raw_printf(p
->out
, ";\n");
1898 rc
= sqlite3_step(pSelect
);
1900 rc
= sqlite3_finalize(pSelect
);
1901 if( rc
!=SQLITE_OK
){
1902 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
1903 sqlite3_errmsg(p
->db
));
1904 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
1910 ** Allocate space and save off current error string.
1912 static char *save_err_msg(
1913 sqlite3
*db
/* Database to query */
1915 int nErrMsg
= 1+strlen30(sqlite3_errmsg(db
));
1916 char *zErrMsg
= sqlite3_malloc64(nErrMsg
);
1918 memcpy(zErrMsg
, sqlite3_errmsg(db
), nErrMsg
);
1925 ** Attempt to display I/O stats on Linux using /proc/PID/io
1927 static void displayLinuxIoStats(FILE *out
){
1930 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
1931 in
= fopen(z
, "rb");
1933 while( fgets(z
, sizeof(z
), in
)!=0 ){
1934 static const struct {
1935 const char *zPattern
;
1938 { "rchar: ", "Bytes received by read():" },
1939 { "wchar: ", "Bytes sent to write():" },
1940 { "syscr: ", "Read() system calls:" },
1941 { "syscw: ", "Write() system calls:" },
1942 { "read_bytes: ", "Bytes read from storage:" },
1943 { "write_bytes: ", "Bytes written to storage:" },
1944 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
1947 for(i
=0; i
<ArraySize(aTrans
); i
++){
1948 int n
= (int)strlen(aTrans
[i
].zPattern
);
1949 if( strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
1950 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
1960 ** Display a single line of status using 64-bit values.
1962 static void displayStatLine(
1963 ShellState
*p
, /* The shell context */
1964 char *zLabel
, /* Label for this one line */
1965 char *zFormat
, /* Format for the result */
1966 int iStatusCtrl
, /* Which status to display */
1967 int bReset
/* True to reset the stats */
1969 sqlite3_int64 iCur
= -1;
1970 sqlite3_int64 iHiwtr
= -1;
1973 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
1974 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
1975 if( zFormat
[i
]=='%' ) nPercent
++;
1978 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
1980 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
1982 raw_printf(p
->out
, "%-36s %s\n", zLabel
, zLine
);
1986 ** Display memory stats.
1988 static int display_stats(
1989 sqlite3
*db
, /* Database to query */
1990 ShellState
*pArg
, /* Pointer to ShellState */
1991 int bReset
/* True to reset the stats */
1996 if( pArg
&& pArg
->out
){
1997 displayStatLine(pArg
, "Memory Used:",
1998 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
1999 displayStatLine(pArg
, "Number of Outstanding Allocations:",
2000 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
2001 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
2002 displayStatLine(pArg
, "Number of Pcache Pages Used:",
2003 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
2005 displayStatLine(pArg
, "Number of Pcache Overflow Bytes:",
2006 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
2007 displayStatLine(pArg
, "Largest Allocation:",
2008 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
2009 displayStatLine(pArg
, "Largest Pcache Allocation:",
2010 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
2011 #ifdef YYTRACKMAXSTACKDEPTH
2012 displayStatLine(pArg
, "Deepest Parser Stack:",
2013 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
2017 if( pArg
&& pArg
->out
&& db
){
2018 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
2020 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
2021 &iCur
, &iHiwtr
, bReset
);
2022 raw_printf(pArg
->out
,
2023 "Lookaside Slots Used: %d (max %d)\n",
2025 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
2026 &iCur
, &iHiwtr
, bReset
);
2027 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
2029 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
2030 &iCur
, &iHiwtr
, bReset
);
2031 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
2033 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
2034 &iCur
, &iHiwtr
, bReset
);
2035 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
2039 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
2040 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
2043 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
2044 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
2046 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
2047 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
2049 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
2050 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
2052 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
2053 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
2056 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
2057 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
2061 if( pArg
&& pArg
->out
&& db
&& pArg
->pStmt
){
2062 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
2064 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
2065 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
2066 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
2067 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
2068 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
2069 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
2070 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
2074 displayLinuxIoStats(pArg
->out
);
2077 /* Do not remove this machine readable comment: extra-stats-output-here */
2083 ** Display scan stats.
2085 static void display_scanstats(
2086 sqlite3
*db
, /* Database to query */
2087 ShellState
*pArg
/* Pointer to ShellState */
2089 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2090 UNUSED_PARAMETER(db
);
2091 UNUSED_PARAMETER(pArg
);
2094 raw_printf(pArg
->out
, "-------- scanstats --------\n");
2096 for(k
=0; k
<=mx
; k
++){
2097 double rEstLoop
= 1.0;
2099 sqlite3_stmt
*p
= pArg
->pStmt
;
2100 sqlite3_int64 nLoop
, nVisit
;
2103 const char *zExplain
;
2104 if( sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NLOOP
, (void*)&nLoop
) ){
2107 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_SELECTID
, (void*)&iSid
);
2108 if( iSid
>mx
) mx
= iSid
;
2109 if( iSid
!=k
) continue;
2111 rEstLoop
= (double)nLoop
;
2112 if( k
>0 ) raw_printf(pArg
->out
, "-------- subquery %d -------\n", k
);
2115 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NVISIT
, (void*)&nVisit
);
2116 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EST
, (void*)&rEst
);
2117 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EXPLAIN
, (void*)&zExplain
);
2118 utf8_printf(pArg
->out
, "Loop %2d: %s\n", n
, zExplain
);
2120 raw_printf(pArg
->out
,
2121 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2122 nLoop
, nVisit
, (sqlite3_int64
)(rEstLoop
+0.5), rEst
2126 raw_printf(pArg
->out
, "---------------------------\n");
2131 ** Parameter azArray points to a zero-terminated array of strings. zStr
2132 ** points to a single nul-terminated string. Return non-zero if zStr
2133 ** is equal, according to strcmp(), to any of the strings in the array.
2134 ** Otherwise, return zero.
2136 static int str_in_array(const char *zStr
, const char **azArray
){
2138 for(i
=0; azArray
[i
]; i
++){
2139 if( 0==strcmp(zStr
, azArray
[i
]) ) return 1;
2145 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2146 ** and populate the ShellState.aiIndent[] array with the number of
2147 ** spaces each opcode should be indented before it is output.
2149 ** The indenting rules are:
2151 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2152 ** all opcodes that occur between the p2 jump destination and the opcode
2153 ** itself by 2 spaces.
2155 ** * For each "Goto", if the jump destination is earlier in the program
2156 ** and ends on one of:
2157 ** Yield SeekGt SeekLt RowSetRead Rewind
2158 ** or if the P1 parameter is one instead of zero,
2159 ** then indent all opcodes between the earlier instruction
2160 ** and "Goto" by 2 spaces.
2162 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
2163 const char *zSql
; /* The text of the SQL statement */
2164 const char *z
; /* Used to check if this is an EXPLAIN */
2165 int *abYield
= 0; /* True if op is an OP_Yield */
2166 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
2167 int iOp
; /* Index of operation in p->aiIndent[] */
2169 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2170 "NextIfOpen", "PrevIfOpen", 0 };
2171 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2173 const char *azGoto
[] = { "Goto", 0 };
2175 /* Try to figure out if this is really an EXPLAIN statement. If this
2176 ** cannot be verified, return early. */
2177 if( sqlite3_column_count(pSql
)!=8 ){
2181 zSql
= sqlite3_sql(pSql
);
2182 if( zSql
==0 ) return;
2183 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
2184 if( sqlite3_strnicmp(z
, "explain", 7) ){
2189 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
2191 int iAddr
= sqlite3_column_int(pSql
, 0);
2192 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
2194 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2195 ** p2 is an instruction address, set variable p2op to the index of that
2196 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2197 ** the current instruction is part of a sub-program generated by an
2198 ** SQL trigger or foreign key. */
2199 int p2
= sqlite3_column_int(pSql
, 3);
2200 int p2op
= (p2
+ (iOp
-iAddr
));
2202 /* Grow the p->aiIndent array as required */
2205 /* Do further verfication that this is explain output. Abort if
2207 static const char *explainCols
[] = {
2208 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2210 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
2211 if( strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
2213 sqlite3_reset(pSql
);
2219 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
2220 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
2222 abYield
[iOp
] = str_in_array(zOp
, azYield
);
2223 p
->aiIndent
[iOp
] = 0;
2226 if( str_in_array(zOp
, azNext
) ){
2227 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2229 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
2230 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
2232 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2237 sqlite3_free(abYield
);
2238 sqlite3_reset(pSql
);
2242 ** Free the array allocated by explain_data_prepare().
2244 static void explain_data_delete(ShellState
*p
){
2245 sqlite3_free(p
->aiIndent
);
2252 ** Disable and restore .wheretrace and .selecttrace settings.
2254 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2255 extern int sqlite3SelectTrace
;
2256 static int savedSelectTrace
;
2258 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2259 extern int sqlite3WhereTrace
;
2260 static int savedWhereTrace
;
2262 static void disable_debug_trace_modes(void){
2263 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2264 savedSelectTrace
= sqlite3SelectTrace
;
2265 sqlite3SelectTrace
= 0;
2267 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2268 savedWhereTrace
= sqlite3WhereTrace
;
2269 sqlite3WhereTrace
= 0;
2272 static void restore_debug_trace_modes(void){
2273 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2274 sqlite3SelectTrace
= savedSelectTrace
;
2276 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2277 sqlite3WhereTrace
= savedWhereTrace
;
2282 ** Run a prepared statement
2284 static void exec_prepared_stmt(
2285 ShellState
*pArg
, /* Pointer to ShellState */
2286 sqlite3_stmt
*pStmt
, /* Statment to run */
2287 int (*xCallback
)(void*,int,char**,char**,int*) /* Callback function */
2291 /* perform the first step. this will tell us if we
2292 ** have a result set or not and how wide it is.
2294 rc
= sqlite3_step(pStmt
);
2295 /* if we have a result set... */
2296 if( SQLITE_ROW
== rc
){
2297 /* if we have a callback... */
2299 /* allocate space for col name ptr, value ptr, and type */
2300 int nCol
= sqlite3_column_count(pStmt
);
2301 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
2305 char **azCols
= (char **)pData
; /* Names of result columns */
2306 char **azVals
= &azCols
[nCol
]; /* Results */
2307 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
2309 assert(sizeof(int) <= sizeof(char *));
2310 /* save off ptrs to column names */
2311 for(i
=0; i
<nCol
; i
++){
2312 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
2315 /* extract the data and data types */
2316 for(i
=0; i
<nCol
; i
++){
2317 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
2318 if( x
==SQLITE_BLOB
&& pArg
&& pArg
->cMode
==MODE_Insert
){
2321 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
2323 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
2325 break; /* from for */
2329 /* if data and types extracted successfully... */
2330 if( SQLITE_ROW
== rc
){
2331 /* call the supplied callback with the result row data */
2332 if( xCallback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
2335 rc
= sqlite3_step(pStmt
);
2338 } while( SQLITE_ROW
== rc
);
2339 sqlite3_free(pData
);
2343 rc
= sqlite3_step(pStmt
);
2344 } while( rc
== SQLITE_ROW
);
2350 ** This function is called to process SQL if the previous shell command
2351 ** was ".expert". It passes the SQL in the second argument directly to
2352 ** the sqlite3expert object.
2354 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2355 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2356 ** an English language error message. It is the responsibility of the
2357 ** caller to eventually free this buffer using sqlite3_free().
2359 static int expertHandleSQL(
2364 assert( pState
->expert
.pExpert
);
2365 assert( pzErr
==0 || *pzErr
==0 );
2366 return sqlite3_expert_sql(pState
->expert
.pExpert
, zSql
, pzErr
);
2370 ** This function is called either to silently clean up the object
2371 ** created by the ".expert" command (if bCancel==1), or to generate a
2372 ** report from it and then clean it up (if bCancel==0).
2374 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2375 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2376 ** an English language error message. It is the responsibility of the
2377 ** caller to eventually free this buffer using sqlite3_free().
2379 static int expertFinish(
2385 sqlite3expert
*p
= pState
->expert
.pExpert
;
2387 assert( bCancel
|| pzErr
==0 || *pzErr
==0 );
2389 FILE *out
= pState
->out
;
2390 int bVerbose
= pState
->expert
.bVerbose
;
2392 rc
= sqlite3_expert_analyze(p
, pzErr
);
2393 if( rc
==SQLITE_OK
){
2394 int nQuery
= sqlite3_expert_count(p
);
2398 const char *zCand
= sqlite3_expert_report(p
,0,EXPERT_REPORT_CANDIDATES
);
2399 raw_printf(out
, "-- Candidates -----------------------------\n");
2400 raw_printf(out
, "%s\n", zCand
);
2402 for(i
=0; i
<nQuery
; i
++){
2403 const char *zSql
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_SQL
);
2404 const char *zIdx
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_INDEXES
);
2405 const char *zEQP
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_PLAN
);
2406 if( zIdx
==0 ) zIdx
= "(no new indexes)\n";
2408 raw_printf(out
, "-- Query %d --------------------------------\n",i
+1);
2409 raw_printf(out
, "%s\n\n", zSql
);
2411 raw_printf(out
, "%s\n", zIdx
);
2412 raw_printf(out
, "%s\n", zEQP
);
2416 sqlite3_expert_destroy(p
);
2417 pState
->expert
.pExpert
= 0;
2423 ** Execute a statement or set of statements. Print
2424 ** any result rows/columns depending on the current mode
2425 ** set via the supplied callback.
2427 ** This is very similar to SQLite's built-in sqlite3_exec()
2428 ** function except it takes a slightly different callback
2429 ** and callback data argument.
2431 static int shell_exec(
2432 sqlite3
*db
, /* An open database */
2433 const char *zSql
, /* SQL to be evaluated */
2434 int (*xCallback
)(void*,int,char**,char**,int*), /* Callback function */
2435 /* (not the same as sqlite3_exec) */
2436 ShellState
*pArg
, /* Pointer to ShellState */
2437 char **pzErrMsg
/* Error msg written here */
2439 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
2440 int rc
= SQLITE_OK
; /* Return Code */
2442 const char *zLeftover
; /* Tail of unprocessed SQL */
2448 if( pArg
->expert
.pExpert
){
2449 rc
= expertHandleSQL(pArg
, zSql
, pzErrMsg
);
2450 return expertFinish(pArg
, (rc
!=SQLITE_OK
), pzErrMsg
);
2453 while( zSql
[0] && (SQLITE_OK
== rc
) ){
2454 static const char *zStmtSql
;
2455 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
2456 if( SQLITE_OK
!= rc
){
2458 *pzErrMsg
= save_err_msg(db
);
2462 /* this happens for a comment or white-space */
2464 while( IsSpace(zSql
[0]) ) zSql
++;
2467 zStmtSql
= sqlite3_sql(pStmt
);
2468 if( zStmtSql
==0 ) zStmtSql
= "";
2469 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
2471 /* save off the prepared statment handle and reset row count */
2473 pArg
->pStmt
= pStmt
;
2477 /* echo the sql statement if echo on */
2478 if( pArg
&& ShellHasFlag(pArg
, SHFLG_Echo
) ){
2479 utf8_printf(pArg
->out
, "%s\n", zStmtSql
? zStmtSql
: zSql
);
2482 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2483 if( pArg
&& pArg
->autoEQP
&& sqlite3_strlike("EXPLAIN%",zStmtSql
,0)!=0 ){
2484 sqlite3_stmt
*pExplain
;
2487 disable_debug_trace_modes();
2488 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, -1, &triggerEQP
);
2489 if( pArg
->autoEQP
>=AUTOEQP_trigger
){
2490 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 1, 0);
2492 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
2493 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2494 if( rc
==SQLITE_OK
){
2495 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
2496 raw_printf(pArg
->out
,"--EQP-- %d,",sqlite3_column_int(pExplain
, 0));
2497 raw_printf(pArg
->out
,"%d,", sqlite3_column_int(pExplain
, 1));
2498 raw_printf(pArg
->out
,"%d,", sqlite3_column_int(pExplain
, 2));
2499 utf8_printf(pArg
->out
,"%s\n", sqlite3_column_text(pExplain
, 3));
2502 sqlite3_finalize(pExplain
);
2504 if( pArg
->autoEQP
>=AUTOEQP_full
){
2505 /* Also do an EXPLAIN for ".eqp full" mode */
2506 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
2507 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2508 if( rc
==SQLITE_OK
){
2509 pArg
->cMode
= MODE_Explain
;
2510 explain_data_prepare(pArg
, pExplain
);
2511 exec_prepared_stmt(pArg
, pExplain
, xCallback
);
2512 explain_data_delete(pArg
);
2514 sqlite3_finalize(pExplain
);
2517 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, triggerEQP
, 0);
2518 restore_debug_trace_modes();
2522 pArg
->cMode
= pArg
->mode
;
2523 if( pArg
->autoExplain
2524 && sqlite3_column_count(pStmt
)==8
2525 && sqlite3_strlike("EXPLAIN%", zStmtSql
,0)==0
2527 pArg
->cMode
= MODE_Explain
;
2530 /* If the shell is currently in ".explain" mode, gather the extra
2531 ** data required to add indents to the output.*/
2532 if( pArg
->cMode
==MODE_Explain
){
2533 explain_data_prepare(pArg
, pStmt
);
2537 exec_prepared_stmt(pArg
, pStmt
, xCallback
);
2538 explain_data_delete(pArg
);
2540 /* print usage stats if stats on */
2541 if( pArg
&& pArg
->statsOn
){
2542 display_stats(db
, pArg
, 0);
2545 /* print loop-counters if required */
2546 if( pArg
&& pArg
->scanstatsOn
){
2547 display_scanstats(db
, pArg
);
2550 /* Finalize the statement just executed. If this fails, save a
2551 ** copy of the error message. Otherwise, set zSql to point to the
2552 ** next statement to execute. */
2553 rc2
= sqlite3_finalize(pStmt
);
2554 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
2555 if( rc
==SQLITE_OK
){
2557 while( IsSpace(zSql
[0]) ) zSql
++;
2558 }else if( pzErrMsg
){
2559 *pzErrMsg
= save_err_msg(db
);
2562 /* clear saved stmt handle */
2573 ** Release memory previously allocated by tableColumnList().
2575 static void freeColumnList(char **azCol
){
2577 for(i
=1; azCol
[i
]; i
++){
2578 sqlite3_free(azCol
[i
]);
2580 /* azCol[0] is a static string */
2581 sqlite3_free(azCol
);
2585 ** Return a list of pointers to strings which are the names of all
2586 ** columns in table zTab. The memory to hold the names is dynamically
2587 ** allocated and must be released by the caller using a subsequent call
2588 ** to freeColumnList().
2590 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2591 ** value that needs to be preserved, then azCol[0] is filled in with the
2592 ** name of the rowid column.
2594 ** The first regular column in the table is azCol[1]. The list is terminated
2595 ** by an entry with azCol[i]==0.
2597 static char **tableColumnList(ShellState
*p
, const char *zTab
){
2599 sqlite3_stmt
*pStmt
;
2603 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
2604 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
2605 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
2608 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
2609 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
2612 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
2613 if( nCol
>=nAlloc
-2 ){
2614 nAlloc
= nAlloc
*2 + nCol
+ 10;
2615 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
2617 raw_printf(stderr
, "Error: out of memory\n");
2621 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
2622 if( sqlite3_column_int(pStmt
, 5) ){
2625 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
2634 sqlite3_finalize(pStmt
);
2635 if( azCol
==0 ) return 0;
2639 /* The decision of whether or not a rowid really needs to be preserved
2640 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2641 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2642 ** rowids on tables where the rowid is inaccessible because there are other
2643 ** columns in the table named "rowid", "_rowid_", and "oid".
2645 if( preserveRowid
&& isIPK
){
2646 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2647 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2648 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2649 ** ROWID aliases. To distinguish these cases, check to see if
2650 ** there is a "pk" entry in "PRAGMA index_list". There will be
2651 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2653 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2654 " WHERE origin='pk'", zTab
);
2655 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
2658 freeColumnList(azCol
);
2661 rc
= sqlite3_step(pStmt
);
2662 sqlite3_finalize(pStmt
);
2663 preserveRowid
= rc
==SQLITE_ROW
;
2665 if( preserveRowid
){
2666 /* Only preserve the rowid if we can find a name to use for the
2668 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
2671 for(i
=1; i
<=nCol
; i
++){
2672 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
2675 /* At this point, we know that azRowid[j] is not the name of any
2676 ** ordinary column in the table. Verify that azRowid[j] is a valid
2677 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2678 ** tables will fail this last check */
2679 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
2680 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
2689 ** Toggle the reverse_unordered_selects setting.
2691 static void toggleSelectOrder(sqlite3
*db
){
2692 sqlite3_stmt
*pStmt
= 0;
2695 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
2696 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
2697 iSetting
= sqlite3_column_int(pStmt
, 0);
2699 sqlite3_finalize(pStmt
);
2700 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
2701 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
2702 sqlite3_exec(db
, zStmt
, 0, 0, 0);
2706 ** This is a different callback routine used for dumping the database.
2707 ** Each row received by this callback consists of a table name,
2708 ** the table type ("index" or "table") and SQL to create the table.
2709 ** This routine should print text sufficient to recreate the table.
2711 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
2716 ShellState
*p
= (ShellState
*)pArg
;
2718 UNUSED_PARAMETER(azNotUsed
);
2719 if( nArg
!=3 || azArg
==0 ) return 0;
2724 if( strcmp(zTable
, "sqlite_sequence")==0 ){
2725 raw_printf(p
->out
, "DELETE FROM sqlite_sequence;\n");
2726 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 ){
2727 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
2728 }else if( strncmp(zTable
, "sqlite_", 7)==0 ){
2730 }else if( strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
2732 if( !p
->writableSchema
){
2733 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
2734 p
->writableSchema
= 1;
2736 zIns
= sqlite3_mprintf(
2737 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2738 "VALUES('table','%q','%q',0,'%q');",
2739 zTable
, zTable
, zSql
);
2740 utf8_printf(p
->out
, "%s\n", zIns
);
2744 printSchemaLine(p
->out
, zSql
, ";\n");
2747 if( strcmp(zType
, "table")==0 ){
2752 char *savedDestTable
;
2755 azCol
= tableColumnList(p
, zTable
);
2761 /* Always quote the table name, even if it appears to be pure ascii,
2762 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2764 appendText(&sTable
, zTable
, quoteChar(zTable
));
2765 /* If preserving the rowid, add a column list after the table name.
2766 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2767 ** instead of the usual "INSERT INTO tab VALUES(...)".
2770 appendText(&sTable
, "(", 0);
2771 appendText(&sTable
, azCol
[0], 0);
2772 for(i
=1; azCol
[i
]; i
++){
2773 appendText(&sTable
, ",", 0);
2774 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
2776 appendText(&sTable
, ")", 0);
2779 /* Build an appropriate SELECT statement */
2781 appendText(&sSelect
, "SELECT ", 0);
2783 appendText(&sSelect
, azCol
[0], 0);
2784 appendText(&sSelect
, ",", 0);
2786 for(i
=1; azCol
[i
]; i
++){
2787 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
2789 appendText(&sSelect
, ",", 0);
2792 freeColumnList(azCol
);
2793 appendText(&sSelect
, " FROM ", 0);
2794 appendText(&sSelect
, zTable
, quoteChar(zTable
));
2796 savedDestTable
= p
->zDestTable
;
2797 savedMode
= p
->mode
;
2798 p
->zDestTable
= sTable
.z
;
2799 p
->mode
= p
->cMode
= MODE_Insert
;
2800 rc
= shell_exec(p
->db
, sSelect
.z
, shell_callback
, p
, 0);
2801 if( (rc
&0xff)==SQLITE_CORRUPT
){
2802 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
2803 toggleSelectOrder(p
->db
);
2804 shell_exec(p
->db
, sSelect
.z
, shell_callback
, p
, 0);
2805 toggleSelectOrder(p
->db
);
2807 p
->zDestTable
= savedDestTable
;
2808 p
->mode
= savedMode
;
2817 ** Run zQuery. Use dump_callback() as the callback routine so that
2818 ** the contents of the query are output as SQL statements.
2820 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
2821 ** "ORDER BY rowid DESC" to the end.
2823 static int run_schema_dump_query(
2829 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
2830 if( rc
==SQLITE_CORRUPT
){
2832 int len
= strlen30(zQuery
);
2833 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
2835 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
2839 zQ2
= malloc( len
+100 );
2840 if( zQ2
==0 ) return rc
;
2841 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
2842 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
2844 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
2846 rc
= SQLITE_CORRUPT
;
2855 ** Text of a help message
2857 static char zHelp
[] =
2858 #ifndef SQLITE_OMIT_AUTHORIZATION
2859 ".auth ON|OFF Show authorizer callbacks\n"
2861 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
2862 ".bail on|off Stop after hitting an error. Default OFF\n"
2863 ".binary on|off Turn binary output on or off. Default OFF\n"
2864 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
2865 ".changes on|off Show number of rows changed by SQL\n"
2866 ".check GLOB Fail if output since .testcase does not match\n"
2867 ".clone NEWDB Clone data into NEWDB from the existing database\n"
2868 ".databases List names and files of attached databases\n"
2869 ".dbinfo ?DB? Show status information about the database\n"
2870 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
2871 " If TABLE specified, only dump tables matching\n"
2872 " LIKE pattern TABLE.\n"
2873 ".echo on|off Turn command echo on or off\n"
2874 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
2875 ".exit Exit this program\n"
2876 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
2877 /* Because explain mode comes on automatically now, the ".explain" mode
2878 ** is removed from the help screen. It is still supported for legacy, however */
2879 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
2880 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
2881 ".headers on|off Turn display of headers on or off\n"
2882 ".help Show this message\n"
2883 ".import FILE TABLE Import data from FILE into TABLE\n"
2884 #ifndef SQLITE_OMIT_TEST_CONTROL
2885 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
2887 ".indexes ?TABLE? Show names of all indexes\n"
2888 " If TABLE specified, only show indexes for tables\n"
2889 " matching LIKE pattern TABLE.\n"
2890 #ifdef SQLITE_ENABLE_IOTRACE
2891 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
2893 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
2894 ".lint OPTIONS Report potential schema issues. Options:\n"
2895 " fkey-indexes Find missing foreign key indexes\n"
2896 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2897 ".load FILE ?ENTRY? Load an extension library\n"
2899 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
2900 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
2901 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
2902 " csv Comma-separated values\n"
2903 " column Left-aligned columns. (See .width)\n"
2904 " html HTML <table> code\n"
2905 " insert SQL insert statements for TABLE\n"
2906 " line One value per line\n"
2907 " list Values delimited by \"|\"\n"
2908 " quote Escape answers as for SQL\n"
2909 " tabs Tab-separated values\n"
2910 " tcl TCL list elements\n"
2911 ".nullvalue STRING Use STRING in place of NULL values\n"
2912 ".once FILENAME Output for the next SQL command only to FILENAME\n"
2913 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
2914 " The --new option starts with an empty file\n"
2915 ".output ?FILENAME? Send output to FILENAME or stdout\n"
2916 ".print STRING... Print literal STRING\n"
2917 ".prompt MAIN CONTINUE Replace the standard prompts\n"
2918 ".quit Exit this program\n"
2919 ".read FILENAME Execute SQL in FILENAME\n"
2920 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
2921 ".save FILE Write in-memory database into FILE\n"
2922 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
2923 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
2924 " Add --indent for pretty-printing\n"
2925 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
2926 ".separator COL ?ROW? Change the column separator and optionally the row\n"
2927 " separator for both the output mode and .import\n"
2928 #if defined(SQLITE_ENABLE_SESSION)
2929 ".session CMD ... Create or control sessions\n"
2931 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
2932 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
2933 ".show Show the current values for various settings\n"
2934 ".stats ?on|off? Show stats or turn stats on or off\n"
2935 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
2936 ".tables ?TABLE? List names of tables\n"
2937 " If TABLE specified, only list tables matching\n"
2938 " LIKE pattern TABLE.\n"
2939 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
2940 ".timeout MS Try opening locked tables for MS milliseconds\n"
2941 ".timer on|off Turn SQL timer on or off\n"
2942 ".trace FILE|off Output each SQL statement as it is run\n"
2943 ".vfsinfo ?AUX? Information about the top-level VFS\n"
2944 ".vfslist List all available VFSes\n"
2945 ".vfsname ?AUX? Print the name of the VFS stack\n"
2946 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
2947 " Negative values right-justify\n"
2950 #if defined(SQLITE_ENABLE_SESSION)
2952 ** Print help information for the ".sessions" command
2954 void session_help(ShellState
*p
){
2956 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
2957 "If ?NAME? is omitted, the first defined session is used.\n"
2959 " attach TABLE Attach TABLE\n"
2960 " changeset FILE Write a changeset into FILE\n"
2961 " close Close one session\n"
2962 " enable ?BOOLEAN? Set or query the enable bit\n"
2963 " filter GLOB... Reject tables matching GLOBs\n"
2964 " indirect ?BOOLEAN? Mark or query the indirect status\n"
2965 " isempty Query whether the session is empty\n"
2966 " list List currently open session names\n"
2967 " open DB NAME Open a new session on DB\n"
2968 " patchset FILE Write a patchset into FILE\n"
2974 /* Forward reference */
2975 static int process_input(ShellState
*p
, FILE *in
);
2978 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
2979 ** and return a pointer to the buffer. The caller is responsible for freeing
2982 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
2985 ** For convenience, a nul-terminator byte is always appended to the data read
2986 ** from the file before the buffer is returned. This byte is not included in
2987 ** the final value of (*pnByte), if applicable.
2989 ** NULL is returned if any error is encountered. The final value of *pnByte
2990 ** is undefined in this case.
2992 static char *readFile(const char *zName
, int *pnByte
){
2993 FILE *in
= fopen(zName
, "rb");
2997 if( in
==0 ) return 0;
2998 fseek(in
, 0, SEEK_END
);
3001 pBuf
= sqlite3_malloc64( nIn
+1 );
3002 if( pBuf
==0 ) return 0;
3003 nRead
= fread(pBuf
, nIn
, 1, in
);
3010 if( pnByte
) *pnByte
= nIn
;
3014 #if defined(SQLITE_ENABLE_SESSION)
3016 ** Close a single OpenSession object and release all of its associated
3019 static void session_close(OpenSession
*pSession
){
3021 sqlite3session_delete(pSession
->p
);
3022 sqlite3_free(pSession
->zName
);
3023 for(i
=0; i
<pSession
->nFilter
; i
++){
3024 sqlite3_free(pSession
->azFilter
[i
]);
3026 sqlite3_free(pSession
->azFilter
);
3027 memset(pSession
, 0, sizeof(OpenSession
));
3032 ** Close all OpenSession objects and release all associated resources.
3034 #if defined(SQLITE_ENABLE_SESSION)
3035 static void session_close_all(ShellState
*p
){
3037 for(i
=0; i
<p
->nSession
; i
++){
3038 session_close(&p
->aSession
[i
]);
3043 # define session_close_all(X)
3047 ** Implementation of the xFilter function for an open session. Omit
3048 ** any tables named by ".session filter" but let all other table through.
3050 #if defined(SQLITE_ENABLE_SESSION)
3051 static int session_filter(void *pCtx
, const char *zTab
){
3052 OpenSession
*pSession
= (OpenSession
*)pCtx
;
3054 for(i
=0; i
<pSession
->nFilter
; i
++){
3055 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
3062 ** Make sure the database is open. If it is not, then open it. If
3063 ** the database fails to open, print an error message and exit.
3065 static void open_db(ShellState
*p
, int keepAlive
){
3067 sqlite3_initialize();
3068 sqlite3_open(p
->zDbFilename
, &p
->db
);
3070 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3071 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
3072 p
->zDbFilename
, sqlite3_errmsg(p
->db
));
3073 if( keepAlive
) return;
3076 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3077 sqlite3_enable_load_extension(p
->db
, 1);
3079 sqlite3_fileio_init(p
->db
, 0, 0);
3080 sqlite3_shathree_init(p
->db
, 0, 0);
3081 sqlite3_completion_init(p
->db
, 0, 0);
3082 sqlite3_create_function(p
->db
, "shell_add_schema", 3, SQLITE_UTF8
, 0,
3083 shellAddSchemaName
, 0, 0);
3084 sqlite3_create_function(p
->db
, "shell_module_schema", 1, SQLITE_UTF8
, 0,
3085 shellModuleSchema
, 0, 0);
3089 #if HAVE_READLINE || HAVE_EDITLINE
3091 ** Readline completion callbacks
3093 static char *readline_completion_generator(const char *text
, int state
){
3094 static sqlite3_stmt
*pStmt
= 0;
3098 sqlite3_finalize(pStmt
);
3099 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3100 " FROM completion(%Q) ORDER BY 1", text
);
3101 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3104 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
3105 zRet
= strdup((const char*)sqlite3_column_text(pStmt
, 0));
3107 sqlite3_finalize(pStmt
);
3113 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
3114 rl_attempted_completion_over
= 1;
3115 return rl_completion_matches(zText
, readline_completion_generator
);
3118 #elif HAVE_LINENOISE
3120 ** Linenoise completion callback
3122 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
3123 int nLine
= (int)strlen(zLine
);
3125 sqlite3_stmt
*pStmt
= 0;
3129 if( nLine
>sizeof(zBuf
)-30 ) return;
3130 if( zLine
[0]=='.' ) return;
3131 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
3132 if( i
==nLine
-1 ) return;
3134 memcpy(zBuf
, zLine
, iStart
);
3135 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3136 " FROM completion(%Q,%Q) ORDER BY 1",
3137 &zLine
[iStart
], zLine
);
3138 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3140 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3141 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
3142 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
3143 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
3144 if( iStart
+nCompletion
< sizeof(zBuf
)-1 ){
3145 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
3146 linenoiseAddCompletion(lc
, zBuf
);
3149 sqlite3_finalize(pStmt
);
3154 ** Do C-language style dequoting.
3160 ** \v -> vertical tab
3162 ** \r -> carriage return
3167 ** \NNN -> ascii character NNN in octal
3169 static void resolve_backslashes(char *z
){
3172 while( *z
&& *z
!='\\' ) z
++;
3173 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
3174 if( c
=='\\' && z
[i
+1]!=0 ){
3192 }else if( c
=='\'' ){
3194 }else if( c
=='\\' ){
3196 }else if( c
>='0' && c
<='7' ){
3198 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3200 c
= (c
<<3) + z
[i
] - '0';
3201 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3203 c
= (c
<<3) + z
[i
] - '0';
3214 ** Return the value of a hexadecimal digit. Return -1 if the input
3215 ** is not a hex digit.
3217 static int hexDigitValue(char c
){
3218 if( c
>='0' && c
<='9' ) return c
- '0';
3219 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
3220 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
3225 ** Interpret zArg as an integer value, possibly with suffixes.
3227 static sqlite3_int64
integerValue(const char *zArg
){
3228 sqlite3_int64 v
= 0;
3229 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
3231 { "MiB", 1024*1024 },
3232 { "GiB", 1024*1024*1024 },
3235 { "GB", 1000000000 },
3238 { "G", 1000000000 },
3245 }else if( zArg
[0]=='+' ){
3248 if( zArg
[0]=='0' && zArg
[1]=='x' ){
3251 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
3256 while( IsDigit(zArg
[0]) ){
3257 v
= v
*10 + zArg
[0] - '0';
3261 for(i
=0; i
<ArraySize(aMult
); i
++){
3262 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
3263 v
*= aMult
[i
].iMult
;
3267 return isNeg
? -v
: v
;
3271 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3272 ** for TRUE and FALSE. Return the integer value if appropriate.
3274 static int booleanValue(const char *zArg
){
3276 if( zArg
[0]=='0' && zArg
[1]=='x' ){
3277 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
3279 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
3281 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
3282 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
3285 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
3288 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3294 ** Set or clear a shell flag according to a boolean value.
3296 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
3297 if( booleanValue(zArg
) ){
3298 ShellSetFlag(p
, mFlag
);
3300 ShellClearFlag(p
, mFlag
);
3305 ** Close an output file, assuming it is not stderr or stdout
3307 static void output_file_close(FILE *f
){
3308 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
3312 ** Try to open an output file. The names "stdout" and "stderr" are
3313 ** recognized and do the right thing. NULL is returned if the output
3314 ** filename is "off".
3316 static FILE *output_file_open(const char *zFile
){
3318 if( strcmp(zFile
,"stdout")==0 ){
3320 }else if( strcmp(zFile
, "stderr")==0 ){
3322 }else if( strcmp(zFile
, "off")==0 ){
3325 f
= fopen(zFile
, "wb");
3327 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
3333 #if !defined(SQLITE_UNTESTABLE)
3334 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3336 ** A routine for handling output from sqlite3_trace().
3338 static int sql_trace_callback(
3344 FILE *f
= (FILE*)pArg
;
3345 UNUSED_PARAMETER(mType
);
3346 UNUSED_PARAMETER(pP
);
3348 const char *z
= (const char*)pX
;
3349 int i
= (int)strlen(z
);
3350 while( i
>0 && z
[i
-1]==';' ){ i
--; }
3351 utf8_printf(f
, "%.*s;\n", i
, z
);
3359 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
3360 ** a useful spot to set a debugger breakpoint.
3362 static void test_breakpoint(void){
3363 static int nCall
= 0;
3368 ** An object used to read a CSV and other files for import.
3370 typedef struct ImportCtx ImportCtx
;
3372 const char *zFile
; /* Name of the input file */
3373 FILE *in
; /* Read the CSV text from this input stream */
3374 char *z
; /* Accumulated text for a field */
3375 int n
; /* Number of bytes in z */
3376 int nAlloc
; /* Space allocated for z[] */
3377 int nLine
; /* Current line number */
3378 int bNotFirst
; /* True if one or more bytes already read */
3379 int cTerm
; /* Character that terminated the most recent field */
3380 int cColSep
; /* The column separator character. (Usually ",") */
3381 int cRowSep
; /* The row separator character. (Usually "\n") */
3384 /* Append a single byte to z[] */
3385 static void import_append_char(ImportCtx
*p
, int c
){
3386 if( p
->n
+1>=p
->nAlloc
){
3387 p
->nAlloc
+= p
->nAlloc
+ 100;
3388 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
3390 raw_printf(stderr
, "out of memory\n");
3394 p
->z
[p
->n
++] = (char)c
;
3397 /* Read a single field of CSV text. Compatible with rfc4180 and extended
3398 ** with the option of having a separator other than ",".
3400 ** + Input comes from p->in.
3401 ** + Store results in p->z of length p->n. Space to hold p->z comes
3402 ** from sqlite3_malloc64().
3403 ** + Use p->cSep as the column separator. The default is ",".
3404 ** + Use p->rSep as the row separator. The default is "\n".
3405 ** + Keep track of the line number in p->nLine.
3406 ** + Store the character that terminates the field in p->cTerm. Store
3407 ** EOF on end-of-file.
3408 ** + Report syntax errors on stderr
3410 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
3412 int cSep
= p
->cColSep
;
3413 int rSep
= p
->cRowSep
;
3416 if( c
==EOF
|| seenInterrupt
){
3422 int startLine
= p
->nLine
;
3427 if( c
==rSep
) p
->nLine
++;
3434 if( (c
==cSep
&& pc
==cQuote
)
3435 || (c
==rSep
&& pc
==cQuote
)
3436 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
3437 || (c
==EOF
&& pc
==cQuote
)
3439 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
3443 if( pc
==cQuote
&& c
!='\r' ){
3444 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
3445 p
->zFile
, p
->nLine
, cQuote
);
3448 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
3449 p
->zFile
, startLine
, cQuote
);
3453 import_append_char(p
, c
);
3458 /* If this is the first field being parsed and it begins with the
3459 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3460 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
3461 import_append_char(p
, c
);
3463 if( (c
&0xff)==0xbb ){
3464 import_append_char(p
, c
);
3466 if( (c
&0xff)==0xbf ){
3469 return csv_read_one_field(p
);
3473 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
3474 import_append_char(p
, c
);
3479 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
3483 if( p
->z
) p
->z
[p
->n
] = 0;
3488 /* Read a single field of ASCII delimited text.
3490 ** + Input comes from p->in.
3491 ** + Store results in p->z of length p->n. Space to hold p->z comes
3492 ** from sqlite3_malloc64().
3493 ** + Use p->cSep as the column separator. The default is "\x1F".
3494 ** + Use p->rSep as the row separator. The default is "\x1E".
3495 ** + Keep track of the row number in p->nLine.
3496 ** + Store the character that terminates the field in p->cTerm. Store
3497 ** EOF on end-of-file.
3498 ** + Report syntax errors on stderr
3500 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
3502 int cSep
= p
->cColSep
;
3503 int rSep
= p
->cRowSep
;
3506 if( c
==EOF
|| seenInterrupt
){
3510 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
3511 import_append_char(p
, c
);
3518 if( p
->z
) p
->z
[p
->n
] = 0;
3523 ** Try to transfer data for table zTable. If an error is seen while
3524 ** moving forward, try to go backwards. The backwards movement won't
3525 ** work for WITHOUT ROWID tables.
3527 static void tryToCloneData(
3532 sqlite3_stmt
*pQuery
= 0;
3533 sqlite3_stmt
*pInsert
= 0;
3538 int nTable
= (int)strlen(zTable
);
3541 const int spinRate
= 10000;
3543 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
3544 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3546 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
3547 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
3551 n
= sqlite3_column_count(pQuery
);
3552 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
3554 raw_printf(stderr
, "out of memory\n");
3557 sqlite3_snprintf(200+nTable
,zInsert
,
3558 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
3559 i
= (int)strlen(zInsert
);
3561 memcpy(zInsert
+i
, ",?", 2);
3564 memcpy(zInsert
+i
, ");", 3);
3565 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
3567 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
3568 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
3573 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
3575 switch( sqlite3_column_type(pQuery
, i
) ){
3577 sqlite3_bind_null(pInsert
, i
+1);
3580 case SQLITE_INTEGER
: {
3581 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
3584 case SQLITE_FLOAT
: {
3585 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
3589 sqlite3_bind_text(pInsert
, i
+1,
3590 (const char*)sqlite3_column_text(pQuery
,i
),
3595 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
3596 sqlite3_column_bytes(pQuery
,i
),
3602 rc
= sqlite3_step(pInsert
);
3603 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
3604 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
3605 sqlite3_errmsg(newDb
));
3607 sqlite3_reset(pInsert
);
3609 if( (cnt
%spinRate
)==0 ){
3610 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
3614 if( rc
==SQLITE_DONE
) break;
3615 sqlite3_finalize(pQuery
);
3616 sqlite3_free(zQuery
);
3617 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3619 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3621 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
3624 } /* End for(k=0...) */
3627 sqlite3_finalize(pQuery
);
3628 sqlite3_finalize(pInsert
);
3629 sqlite3_free(zQuery
);
3630 sqlite3_free(zInsert
);
3635 ** Try to transfer all rows of the schema that match zWhere. For
3636 ** each row, invoke xForEach() on the object defined by that row.
3637 ** If an error is encountered while moving forward through the
3638 ** sqlite_master table, try again moving backwards.
3640 static void tryToCloneSchema(
3644 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
3646 sqlite3_stmt
*pQuery
= 0;
3649 const unsigned char *zName
;
3650 const unsigned char *zSql
;
3653 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3654 " WHERE %s", zWhere
);
3655 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3657 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
3658 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
3660 goto end_schema_xfer
;
3662 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
3663 zName
= sqlite3_column_text(pQuery
, 0);
3664 zSql
= sqlite3_column_text(pQuery
, 1);
3665 printf("%s... ", zName
); fflush(stdout
);
3666 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
3668 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
3669 sqlite3_free(zErrMsg
);
3673 xForEach(p
, newDb
, (const char*)zName
);
3677 if( rc
!=SQLITE_DONE
){
3678 sqlite3_finalize(pQuery
);
3679 sqlite3_free(zQuery
);
3680 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3681 " WHERE %s ORDER BY rowid DESC", zWhere
);
3682 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
3684 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
3685 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
3687 goto end_schema_xfer
;
3689 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
3690 zName
= sqlite3_column_text(pQuery
, 0);
3691 zSql
= sqlite3_column_text(pQuery
, 1);
3692 printf("%s... ", zName
); fflush(stdout
);
3693 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
3695 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
3696 sqlite3_free(zErrMsg
);
3700 xForEach(p
, newDb
, (const char*)zName
);
3706 sqlite3_finalize(pQuery
);
3707 sqlite3_free(zQuery
);
3711 ** Open a new database file named "zNewDb". Try to recover as much information
3712 ** as possible out of the main database (which might be corrupt) and write it
3715 static void tryToClone(ShellState
*p
, const char *zNewDb
){
3718 if( access(zNewDb
,0)==0 ){
3719 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
3722 rc
= sqlite3_open(zNewDb
, &newDb
);
3724 utf8_printf(stderr
, "Cannot create output database: %s\n",
3725 sqlite3_errmsg(newDb
));
3727 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
3728 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
3729 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
3730 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
3731 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
3732 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3734 sqlite3_close(newDb
);
3738 ** Change the output file back to stdout
3740 static void output_reset(ShellState
*p
){
3741 if( p
->outfile
[0]=='|' ){
3742 #ifndef SQLITE_OMIT_POPEN
3746 output_file_close(p
->out
);
3753 ** Run an SQL command and return the single integer result.
3755 static int db_int(ShellState
*p
, const char *zSql
){
3756 sqlite3_stmt
*pStmt
;
3758 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3759 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
3760 res
= sqlite3_column_int(pStmt
,0);
3762 sqlite3_finalize(pStmt
);
3767 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
3769 static unsigned int get2byteInt(unsigned char *a
){
3770 return (a
[0]<<8) + a
[1];
3772 static unsigned int get4byteInt(unsigned char *a
){
3773 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
3777 ** Implementation of the ".info" command.
3779 ** Return 1 on error, 2 to exit, and 0 otherwise.
3781 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
3782 static const struct { const char *zName
; int ofst
; } aField
[] = {
3783 { "file change counter:", 24 },
3784 { "database page count:", 28 },
3785 { "freelist page count:", 36 },
3786 { "schema cookie:", 40 },
3787 { "schema format:", 44 },
3788 { "default cache size:", 48 },
3789 { "autovacuum top root:", 52 },
3790 { "incremental vacuum:", 64 },
3791 { "text encoding:", 56 },
3792 { "user version:", 60 },
3793 { "application id:", 68 },
3794 { "software version:", 96 },
3796 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
3797 { "number of tables:",
3798 "SELECT count(*) FROM %s WHERE type='table'" },
3799 { "number of indexes:",
3800 "SELECT count(*) FROM %s WHERE type='index'" },
3801 { "number of triggers:",
3802 "SELECT count(*) FROM %s WHERE type='trigger'" },
3803 { "number of views:",
3804 "SELECT count(*) FROM %s WHERE type='view'" },
3806 "SELECT total(length(sql)) FROM %s" },
3810 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
3811 sqlite3_stmt
*pStmt
= 0;
3812 unsigned char aHdr
[100];
3814 if( p
->db
==0 ) return 1;
3815 sqlite3_prepare_v2(p
->db
,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
3817 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
3818 if( sqlite3_step(pStmt
)==SQLITE_ROW
3819 && sqlite3_column_bytes(pStmt
,0)>100
3821 memcpy(aHdr
, sqlite3_column_blob(pStmt
,0), 100);
3822 sqlite3_finalize(pStmt
);
3824 raw_printf(stderr
, "unable to read database header\n");
3825 sqlite3_finalize(pStmt
);
3828 i
= get2byteInt(aHdr
+16);
3829 if( i
==1 ) i
= 65536;
3830 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
3831 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
3832 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
3833 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
3834 for(i
=0; i
<ArraySize(aField
); i
++){
3835 int ofst
= aField
[i
].ofst
;
3836 unsigned int val
= get4byteInt(aHdr
+ ofst
);
3837 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
3840 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
3841 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
3842 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
3845 raw_printf(p
->out
, "\n");
3848 zSchemaTab
= sqlite3_mprintf("main.sqlite_master");
3849 }else if( strcmp(zDb
,"temp")==0 ){
3850 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_master");
3852 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_master", zDb
);
3854 for(i
=0; i
<ArraySize(aQuery
); i
++){
3855 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
3856 int val
= db_int(p
, zSql
);
3858 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
3860 sqlite3_free(zSchemaTab
);
3865 ** Print the current sqlite3_errmsg() value to stderr and return 1.
3867 static int shellDatabaseError(sqlite3
*db
){
3868 const char *zErr
= sqlite3_errmsg(db
);
3869 utf8_printf(stderr
, "Error: %s\n", zErr
);
3874 ** Print an out-of-memory message to stderr and return 1.
3876 static int shellNomemError(void){
3877 raw_printf(stderr
, "Error: out of memory\n");
3882 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
3883 ** if they match and FALSE (0) if they do not match.
3887 ** '*' Matches any sequence of zero or more characters.
3889 ** '?' Matches exactly one character.
3891 ** [...] Matches one character from the enclosed list of
3894 ** [^...] Matches one character not in the enclosed list.
3896 ** '#' Matches any sequence of one or more digits with an
3897 ** optional + or - sign in front
3899 ** ' ' Any span of whitespace matches any other span of
3902 ** Extra whitespace at the end of z[] is ignored.
3904 static int testcase_glob(const char *zGlob
, const char *z
){
3909 while( (c
= (*(zGlob
++)))!=0 ){
3911 if( !IsSpace(*z
) ) return 0;
3912 while( IsSpace(*zGlob
) ) zGlob
++;
3913 while( IsSpace(*z
) ) z
++;
3915 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
3916 if( c
=='?' && (*(z
++))==0 ) return 0;
3921 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
3926 while( (c2
= (*(z
++)))!=0 ){
3929 if( c2
==0 ) return 0;
3931 if( testcase_glob(zGlob
,z
) ) return 1;
3935 if( (*(z
++))==0 ) return 0;
3941 if( c
==0 ) return 0;
3948 if( c
==']' ) seen
= 1;
3951 while( c2
&& c2
!=']' ){
3952 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
3954 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
3964 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
3966 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
3967 if( !IsDigit(z
[0]) ) return 0;
3969 while( IsDigit(z
[0]) ){ z
++; }
3971 if( c
!=(*(z
++)) ) return 0;
3974 while( IsSpace(*z
) ){ z
++; }
3980 ** Compare the string as a command-line option with either one or two
3981 ** initial "-" characters.
3983 static int optionMatch(const char *zStr
, const char *zOpt
){
3984 if( zStr
[0]!='-' ) return 0;
3986 if( zStr
[0]=='-' ) zStr
++;
3987 return strcmp(zStr
, zOpt
)==0;
3993 int shellDeleteFile(const char *zFilename
){
3996 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
4000 rc
= unlink(zFilename
);
4007 ** The implementation of SQL scalar function fkey_collate_clause(), used
4008 ** by the ".lint fkey-indexes" command. This scalar function is always
4009 ** called with four arguments - the parent table name, the parent column name,
4010 ** the child table name and the child column name.
4012 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4014 ** If either of the named tables or columns do not exist, this function
4015 ** returns an empty string. An empty string is also returned if both tables
4016 ** and columns exist but have the same default collation sequence. Or,
4017 ** if both exist but the default collation sequences are different, this
4018 ** function returns the string " COLLATE <parent-collation>", where
4019 ** <parent-collation> is the default collation sequence of the parent column.
4021 static void shellFkeyCollateClause(
4022 sqlite3_context
*pCtx
,
4024 sqlite3_value
**apVal
4026 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
4027 const char *zParent
;
4028 const char *zParentCol
;
4029 const char *zParentSeq
;
4031 const char *zChildCol
;
4032 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
4036 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
4037 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
4038 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
4039 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
4041 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
4042 rc
= sqlite3_table_column_metadata(
4043 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
4045 if( rc
==SQLITE_OK
){
4046 rc
= sqlite3_table_column_metadata(
4047 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
4051 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
4052 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
4053 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
4060 ** The implementation of dot-command ".lint fkey-indexes".
4062 static int lintFkeyIndexes(
4063 ShellState
*pState
, /* Current shell tool state */
4064 char **azArg
, /* Array of arguments passed to dot command */
4065 int nArg
/* Number of entries in azArg[] */
4067 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
4068 FILE *out
= pState
->out
; /* Stream to write non-error output to */
4069 int bVerbose
= 0; /* If -verbose is present */
4070 int bGroupByParent
= 0; /* If -groupbyparent is present */
4071 int i
; /* To iterate through azArg[] */
4072 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
4073 int rc
; /* Return code */
4074 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
4077 ** This SELECT statement returns one row for each foreign key constraint
4078 ** in the schema of the main database. The column values are:
4080 ** 0. The text of an SQL statement similar to:
4082 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
4084 ** This SELECT is similar to the one that the foreign keys implementation
4085 ** needs to run internally on child tables. If there is an index that can
4086 ** be used to optimize this query, then it can also be used by the FK
4087 ** implementation to optimize DELETE or UPDATE statements on the parent
4090 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4091 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4092 ** contains an index that can be used to optimize the query.
4094 ** 2. Human readable text that describes the child table and columns. e.g.
4096 ** "child_table(child_key1, child_key2)"
4098 ** 3. Human readable text that describes the parent table and columns. e.g.
4100 ** "parent_table(parent_key1, parent_key2)"
4102 ** 4. A full CREATE INDEX statement for an index that could be used to
4103 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4105 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4107 ** 5. The name of the parent table.
4109 ** These six values are used by the C logic below to generate the report.
4113 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
4114 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4115 " || fkey_collate_clause("
4116 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4118 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4119 " || group_concat('*=?', ' AND ') || ')'"
4121 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4123 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4125 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4126 " || ' ON ' || quote(s.name) || '('"
4127 " || group_concat(quote(f.[from]) ||"
4128 " fkey_collate_clause("
4129 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4133 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4134 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4135 "GROUP BY s.name, f.id "
4136 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4138 const char *zGlobIPK
= "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4140 for(i
=2; i
<nArg
; i
++){
4141 int n
= (int)strlen(azArg
[i
]);
4142 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
4145 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
4150 raw_printf(stderr
, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4153 return SQLITE_ERROR
;
4157 /* Register the fkey_collate_clause() SQL function */
4158 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
4159 0, shellFkeyCollateClause
, 0, 0
4163 if( rc
==SQLITE_OK
){
4164 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
4166 if( rc
==SQLITE_OK
){
4167 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
4170 if( rc
==SQLITE_OK
){
4173 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
4175 sqlite3_stmt
*pExplain
= 0;
4176 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
4177 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
4178 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
4179 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
4180 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
4181 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
4183 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4184 if( rc
!=SQLITE_OK
) break;
4185 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
4186 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
4188 0==sqlite3_strglob(zGlob
, zPlan
)
4189 || 0==sqlite3_strglob(zGlobIPK
, zPlan
)
4192 rc
= sqlite3_finalize(pExplain
);
4193 if( rc
!=SQLITE_OK
) break;
4196 raw_printf(stderr
, "Error: internal error");
4200 && (bVerbose
|| res
==0)
4201 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
4203 raw_printf(out
, "-- Parent table %s\n", zParent
);
4204 sqlite3_free(zPrev
);
4205 zPrev
= sqlite3_mprintf("%s", zParent
);
4209 raw_printf(out
, "%s%s --> %s\n", zIndent
, zCI
, zTarget
);
4210 }else if( bVerbose
){
4211 raw_printf(out
, "%s/* no extra indexes required for %s -> %s */\n",
4212 zIndent
, zFrom
, zTarget
4217 sqlite3_free(zPrev
);
4219 if( rc
!=SQLITE_OK
){
4220 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4223 rc2
= sqlite3_finalize(pSql
);
4224 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
4226 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4229 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4236 ** Implementation of ".lint" dot command.
4238 static int lintDotCommand(
4239 ShellState
*pState
, /* Current shell tool state */
4240 char **azArg
, /* Array of arguments passed to dot command */
4241 int nArg
/* Number of entries in azArg[] */
4244 n
= (nArg
>=2 ? (int)strlen(azArg
[1]) : 0);
4245 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
4246 return lintFkeyIndexes(pState
, azArg
, nArg
);
4249 raw_printf(stderr
, "Usage %s sub-command ?switches...?\n", azArg
[0]);
4250 raw_printf(stderr
, "Where sub-commands are:\n");
4251 raw_printf(stderr
, " fkey-indexes\n");
4252 return SQLITE_ERROR
;
4256 ** Implementation of ".expert" dot command.
4258 static int expertDotCommand(
4259 ShellState
*pState
, /* Current shell tool state */
4260 char **azArg
, /* Array of arguments passed to dot command */
4261 int nArg
/* Number of entries in azArg[] */
4268 assert( pState
->expert
.pExpert
==0 );
4269 memset(&pState
->expert
, 0, sizeof(ExpertInfo
));
4271 for(i
=1; rc
==SQLITE_OK
&& i
<nArg
; i
++){
4274 if( z
[0]=='-' && z
[1]=='-' ) z
++;
4276 if( n
>=2 && 0==strncmp(z
, "-verbose", n
) ){
4277 pState
->expert
.bVerbose
= 1;
4279 else if( n
>=2 && 0==strncmp(z
, "-sample", n
) ){
4281 raw_printf(stderr
, "option requires an argument: %s\n", z
);
4284 iSample
= (int)integerValue(azArg
[++i
]);
4285 if( iSample
<0 || iSample
>100 ){
4286 raw_printf(stderr
, "value out of range: %s\n", azArg
[i
]);
4292 raw_printf(stderr
, "unknown option: %s\n", z
);
4297 if( rc
==SQLITE_OK
){
4298 pState
->expert
.pExpert
= sqlite3_expert_new(pState
->db
, &zErr
);
4299 if( pState
->expert
.pExpert
==0 ){
4300 raw_printf(stderr
, "sqlite3_expert_new: %s\n", zErr
);
4303 sqlite3_expert_config(
4304 pState
->expert
.pExpert
, EXPERT_CONFIG_SAMPLE
, iSample
4315 ** If an input line begins with "." then invoke this routine to
4316 ** process that line.
4318 ** Return 1 on error, 2 to exit, and 0 otherwise.
4320 static int do_meta_command(char *zLine
, ShellState
*p
){
4327 if( p
->expert
.pExpert
){
4328 expertFinish(p
, 1, 0);
4331 /* Parse the input line into tokens.
4333 while( zLine
[h
] && nArg
<ArraySize(azArg
) ){
4334 while( IsSpace(zLine
[h
]) ){ h
++; }
4335 if( zLine
[h
]==0 ) break;
4336 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
4337 int delim
= zLine
[h
++];
4338 azArg
[nArg
++] = &zLine
[h
];
4339 while( zLine
[h
] && zLine
[h
]!=delim
){
4340 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
4343 if( zLine
[h
]==delim
){
4346 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
4348 azArg
[nArg
++] = &zLine
[h
];
4349 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
4350 if( zLine
[h
] ) zLine
[h
++] = 0;
4351 resolve_backslashes(azArg
[nArg
-1]);
4355 /* Process the input line.
4357 if( nArg
==0 ) return 0; /* no tokens, no error */
4358 n
= strlen30(azArg
[0]);
4361 #ifndef SQLITE_OMIT_AUTHORIZATION
4362 if( c
=='a' && strncmp(azArg
[0], "auth", n
)==0 ){
4364 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
4366 goto meta_command_exit
;
4369 if( booleanValue(azArg
[1]) ){
4370 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
4372 sqlite3_set_authorizer(p
->db
, 0, 0);
4377 if( (c
=='b' && n
>=3 && strncmp(azArg
[0], "backup", n
)==0)
4378 || (c
=='s' && n
>=3 && strncmp(azArg
[0], "save", n
)==0)
4380 const char *zDestFile
= 0;
4381 const char *zDb
= 0;
4383 sqlite3_backup
*pBackup
;
4385 for(j
=1; j
<nArg
; j
++){
4386 const char *z
= azArg
[j
];
4388 while( z
[0]=='-' ) z
++;
4389 /* No options to process at this time */
4391 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
4394 }else if( zDestFile
==0 ){
4395 zDestFile
= azArg
[j
];
4398 zDestFile
= azArg
[j
];
4400 raw_printf(stderr
, "too many arguments to .backup\n");
4405 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
4408 if( zDb
==0 ) zDb
= "main";
4409 rc
= sqlite3_open(zDestFile
, &pDest
);
4410 if( rc
!=SQLITE_OK
){
4411 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
4412 sqlite3_close(pDest
);
4416 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
4418 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
4419 sqlite3_close(pDest
);
4422 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
4423 sqlite3_backup_finish(pBackup
);
4424 if( rc
==SQLITE_DONE
){
4427 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
4430 sqlite3_close(pDest
);
4433 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "bail", n
)==0 ){
4435 bail_on_error
= booleanValue(azArg
[1]);
4437 raw_printf(stderr
, "Usage: .bail on|off\n");
4442 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "binary", n
)==0 ){
4444 if( booleanValue(azArg
[1]) ){
4445 setBinaryMode(p
->out
, 1);
4447 setTextMode(p
->out
, 1);
4450 raw_printf(stderr
, "Usage: .binary on|off\n");
4455 if( c
=='c' && strcmp(azArg
[0],"cd")==0 ){
4457 #if defined(_WIN32) || defined(WIN32)
4458 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
4459 rc
= !SetCurrentDirectoryW(z
);
4462 rc
= chdir(azArg
[1]);
4465 utf8_printf(stderr
, "Cannot change to directory \"%s\"\n", azArg
[1]);
4469 raw_printf(stderr
, "Usage: .cd DIRECTORY\n");
4474 /* The undocumented ".breakpoint" command causes a call to the no-op
4475 ** routine named test_breakpoint().
4477 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "breakpoint", n
)==0 ){
4481 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "changes", n
)==0 ){
4483 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
4485 raw_printf(stderr
, "Usage: .changes on|off\n");
4490 /* Cancel output redirection, if it is currently set (by .testcase)
4491 ** Then read the content of the testcase-out.txt file and compare against
4492 ** azArg[1]. If there are differences, report an error and exit.
4494 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "check", n
)==0 ){
4498 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
4500 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
4501 raw_printf(stderr
, "Error: cannot read 'testcase-out.txt'\n");
4503 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
4505 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4506 p
->zTestcase
, azArg
[1], zRes
);
4509 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
4515 if( c
=='c' && strncmp(azArg
[0], "clone", n
)==0 ){
4517 tryToClone(p
, azArg
[1]);
4519 raw_printf(stderr
, "Usage: .clone FILENAME\n");
4524 if( c
=='d' && n
>1 && strncmp(azArg
[0], "databases", n
)==0 ){
4528 memcpy(&data
, p
, sizeof(data
));
4529 data
.showHeader
= 0;
4530 data
.cMode
= data
.mode
= MODE_List
;
4531 sqlite3_snprintf(sizeof(data
.colSeparator
),data
.colSeparator
,": ");
4533 sqlite3_exec(p
->db
, "SELECT name, file FROM pragma_database_list",
4534 callback
, &data
, &zErrMsg
);
4536 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
4537 sqlite3_free(zErrMsg
);
4542 if( c
=='d' && strncmp(azArg
[0], "dbinfo", n
)==0 ){
4543 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
4546 if( c
=='d' && strncmp(azArg
[0], "dump", n
)==0 ){
4547 const char *zLike
= 0;
4549 int savedShowHeader
= p
->showHeader
;
4550 ShellClearFlag(p
, SHFLG_PreserveRowid
|SHFLG_Newlines
);
4551 for(i
=1; i
<nArg
; i
++){
4552 if( azArg
[i
][0]=='-' ){
4553 const char *z
= azArg
[i
]+1;
4554 if( z
[0]=='-' ) z
++;
4555 if( strcmp(z
,"preserve-rowids")==0 ){
4556 #ifdef SQLITE_OMIT_VIRTUALTABLE
4557 raw_printf(stderr
, "The --preserve-rowids option is not compatible"
4558 " with SQLITE_OMIT_VIRTUALTABLE\n");
4560 goto meta_command_exit
;
4562 ShellSetFlag(p
, SHFLG_PreserveRowid
);
4565 if( strcmp(z
,"newlines")==0 ){
4566 ShellSetFlag(p
, SHFLG_Newlines
);
4569 raw_printf(stderr
, "Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
4571 goto meta_command_exit
;
4574 raw_printf(stderr
, "Usage: .dump ?--preserve-rowids? "
4575 "?--newlines? ?LIKE-PATTERN?\n");
4577 goto meta_command_exit
;
4583 /* When playing back a "dump", the content might appear in an order
4584 ** which causes immediate foreign key constraints to be violated.
4585 ** So disable foreign-key constraint enforcement to prevent problems. */
4586 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
4587 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
4588 p
->writableSchema
= 0;
4590 /* Set writable_schema=ON since doing so forces SQLite to initialize
4591 ** as much of the schema as it can even if the sqlite_master table is
4593 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
4596 run_schema_dump_query(p
,
4597 "SELECT name, type, sql FROM sqlite_master "
4598 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
4600 run_schema_dump_query(p
,
4601 "SELECT name, type, sql FROM sqlite_master "
4602 "WHERE name=='sqlite_sequence'"
4604 run_table_dump_query(p
,
4605 "SELECT sql FROM sqlite_master "
4606 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
4610 zSql
= sqlite3_mprintf(
4611 "SELECT name, type, sql FROM sqlite_master "
4612 "WHERE tbl_name LIKE %Q AND type=='table'"
4613 " AND sql NOT NULL", zLike
);
4614 run_schema_dump_query(p
,zSql
);
4616 zSql
= sqlite3_mprintf(
4617 "SELECT sql FROM sqlite_master "
4618 "WHERE sql NOT NULL"
4619 " AND type IN ('index','trigger','view')"
4620 " AND tbl_name LIKE %Q", zLike
);
4621 run_table_dump_query(p
, zSql
, 0);
4624 if( p
->writableSchema
){
4625 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
4626 p
->writableSchema
= 0;
4628 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4629 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
4630 raw_printf(p
->out
, p
->nErr
? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
4631 p
->showHeader
= savedShowHeader
;
4634 if( c
=='e' && strncmp(azArg
[0], "echo", n
)==0 ){
4636 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
4638 raw_printf(stderr
, "Usage: .echo on|off\n");
4643 if( c
=='e' && strncmp(azArg
[0], "eqp", n
)==0 ){
4645 if( strcmp(azArg
[1],"full")==0 ){
4646 p
->autoEQP
= AUTOEQP_full
;
4647 }else if( strcmp(azArg
[1],"trigger")==0 ){
4648 p
->autoEQP
= AUTOEQP_trigger
;
4650 p
->autoEQP
= booleanValue(azArg
[1]);
4653 raw_printf(stderr
, "Usage: .eqp off|on|trigger|full\n");
4658 if( c
=='e' && strncmp(azArg
[0], "exit", n
)==0 ){
4659 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
4663 /* The ".explain" command is automatic now. It is largely pointless. It
4664 ** retained purely for backwards compatibility */
4665 if( c
=='e' && strncmp(azArg
[0], "explain", n
)==0 ){
4668 if( strcmp(azArg
[1],"auto")==0 ){
4671 val
= booleanValue(azArg
[1]);
4674 if( val
==1 && p
->mode
!=MODE_Explain
){
4675 p
->normalMode
= p
->mode
;
4676 p
->mode
= MODE_Explain
;
4679 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
4681 }else if( val
==99 ){
4682 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
4687 if( c
=='e' && strncmp(azArg
[0], "expert", n
)==0 ){
4689 expertDotCommand(p
, azArg
, nArg
);
4692 if( c
=='f' && strncmp(azArg
[0], "fullschema", n
)==0 ){
4696 memcpy(&data
, p
, sizeof(data
));
4697 data
.showHeader
= 0;
4698 data
.cMode
= data
.mode
= MODE_Semi
;
4699 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
4700 data
.cMode
= data
.mode
= MODE_Pretty
;
4704 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
4706 goto meta_command_exit
;
4709 rc
= sqlite3_exec(p
->db
,
4711 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4712 " FROM sqlite_master UNION ALL"
4713 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4714 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
4716 callback
, &data
, &zErrMsg
4718 if( rc
==SQLITE_OK
){
4719 sqlite3_stmt
*pStmt
;
4720 rc
= sqlite3_prepare_v2(p
->db
,
4721 "SELECT rowid FROM sqlite_master"
4722 " WHERE name GLOB 'sqlite_stat[134]'",
4724 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
4725 sqlite3_finalize(pStmt
);
4728 raw_printf(p
->out
, "/* No STAT tables available */\n");
4730 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
4731 sqlite3_exec(p
->db
, "SELECT 'ANALYZE sqlite_master'",
4732 callback
, &data
, &zErrMsg
);
4733 data
.cMode
= data
.mode
= MODE_Insert
;
4734 data
.zDestTable
= "sqlite_stat1";
4735 shell_exec(p
->db
, "SELECT * FROM sqlite_stat1",
4736 shell_callback
, &data
,&zErrMsg
);
4737 data
.zDestTable
= "sqlite_stat3";
4738 shell_exec(p
->db
, "SELECT * FROM sqlite_stat3",
4739 shell_callback
, &data
,&zErrMsg
);
4740 data
.zDestTable
= "sqlite_stat4";
4741 shell_exec(p
->db
, "SELECT * FROM sqlite_stat4",
4742 shell_callback
, &data
, &zErrMsg
);
4743 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
4747 if( c
=='h' && strncmp(azArg
[0], "headers", n
)==0 ){
4749 p
->showHeader
= booleanValue(azArg
[1]);
4751 raw_printf(stderr
, "Usage: .headers on|off\n");
4756 if( c
=='h' && strncmp(azArg
[0], "help", n
)==0 ){
4757 utf8_printf(p
->out
, "%s", zHelp
);
4760 if( c
=='i' && strncmp(azArg
[0], "import", n
)==0 ){
4761 char *zTable
; /* Insert data into this table */
4762 char *zFile
; /* Name of file to extra content from */
4763 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
4764 int nCol
; /* Number of columns in the table */
4765 int nByte
; /* Number of bytes in an SQL string */
4766 int i
, j
; /* Loop counters */
4767 int needCommit
; /* True to COMMIT or ROLLBACK at end */
4768 int nSep
; /* Number of bytes in p->colSeparator[] */
4769 char *zSql
; /* An SQL statement */
4770 ImportCtx sCtx
; /* Reader context */
4771 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
4772 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close file */
4775 raw_printf(stderr
, "Usage: .import FILE TABLE\n");
4776 goto meta_command_exit
;
4781 memset(&sCtx
, 0, sizeof(sCtx
));
4783 nSep
= strlen30(p
->colSeparator
);
4786 "Error: non-null column separator required for import\n");
4790 raw_printf(stderr
, "Error: multi-character column separators not allowed"
4794 nSep
= strlen30(p
->rowSeparator
);
4796 raw_printf(stderr
, "Error: non-null row separator required for import\n");
4799 if( nSep
==2 && p
->mode
==MODE_Csv
&& strcmp(p
->rowSeparator
, SEP_CrLf
)==0 ){
4800 /* When importing CSV (only), if the row separator is set to the
4801 ** default output row separator, change it to the default input
4802 ** row separator. This avoids having to maintain different input
4803 ** and output row separators. */
4804 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
4805 nSep
= strlen30(p
->rowSeparator
);
4808 raw_printf(stderr
, "Error: multi-character row separators not allowed"
4814 if( sCtx
.zFile
[0]=='|' ){
4815 #ifdef SQLITE_OMIT_POPEN
4816 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
4819 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
4820 sCtx
.zFile
= "<pipe>";
4824 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
4827 if( p
->mode
==MODE_Ascii
){
4828 xRead
= ascii_read_one_field
;
4830 xRead
= csv_read_one_field
;
4833 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
4836 sCtx
.cColSep
= p
->colSeparator
[0];
4837 sCtx
.cRowSep
= p
->rowSeparator
[0];
4838 zSql
= sqlite3_mprintf("SELECT * FROM %s", zTable
);
4840 raw_printf(stderr
, "Error: out of memory\n");
4844 nByte
= strlen30(zSql
);
4845 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4846 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
4847 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
4848 char *zCreate
= sqlite3_mprintf("CREATE TABLE %s", zTable
);
4850 while( xRead(&sCtx
) ){
4851 zCreate
= sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate
, cSep
, sCtx
.z
);
4853 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
4856 sqlite3_free(zCreate
);
4857 sqlite3_free(sCtx
.z
);
4859 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
4862 zCreate
= sqlite3_mprintf("%z\n)", zCreate
);
4863 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
4864 sqlite3_free(zCreate
);
4866 utf8_printf(stderr
, "CREATE TABLE %s(...) failed: %s\n", zTable
,
4867 sqlite3_errmsg(p
->db
));
4868 sqlite3_free(sCtx
.z
);
4872 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4876 if (pStmt
) sqlite3_finalize(pStmt
);
4877 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
4881 nCol
= sqlite3_column_count(pStmt
);
4882 sqlite3_finalize(pStmt
);
4884 if( nCol
==0 ) return 0; /* no columns, no error */
4885 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
4887 raw_printf(stderr
, "Error: out of memory\n");
4891 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO \"%w\" VALUES(?", zTable
);
4893 for(i
=1; i
<nCol
; i
++){
4899 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4902 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
4903 if (pStmt
) sqlite3_finalize(pStmt
);
4907 needCommit
= sqlite3_get_autocommit(p
->db
);
4908 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
4910 int startLine
= sCtx
.nLine
;
4911 for(i
=0; i
<nCol
; i
++){
4912 char *z
= xRead(&sCtx
);
4914 ** Did we reach end-of-file before finding any columns?
4915 ** If so, stop instead of NULL filling the remaining columns.
4917 if( z
==0 && i
==0 ) break;
4919 ** Did we reach end-of-file OR end-of-line before finding any
4920 ** columns in ASCII mode? If so, stop instead of NULL filling
4921 ** the remaining columns.
4923 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
4924 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
4925 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
4926 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
4927 "filling the rest with NULL\n",
4928 sCtx
.zFile
, startLine
, nCol
, i
+1);
4930 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
4933 if( sCtx
.cTerm
==sCtx
.cColSep
){
4937 }while( sCtx
.cTerm
==sCtx
.cColSep
);
4938 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
4940 sCtx
.zFile
, startLine
, nCol
, i
);
4943 sqlite3_step(pStmt
);
4944 rc
= sqlite3_reset(pStmt
);
4945 if( rc
!=SQLITE_OK
){
4946 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
4947 startLine
, sqlite3_errmsg(p
->db
));
4950 }while( sCtx
.cTerm
!=EOF
);
4953 sqlite3_free(sCtx
.z
);
4954 sqlite3_finalize(pStmt
);
4955 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
4958 #ifndef SQLITE_UNTESTABLE
4959 if( c
=='i' && strncmp(azArg
[0], "imposter", n
)==0 ){
4962 sqlite3_stmt
*pStmt
;
4966 utf8_printf(stderr
, "Usage: .imposter INDEX IMPOSTER\n");
4968 goto meta_command_exit
;
4971 zSql
= sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
4972 " WHERE name='%q' AND type='index'", azArg
[1]);
4973 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4975 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
4976 tnum
= sqlite3_column_int(pStmt
, 0);
4978 sqlite3_finalize(pStmt
);
4980 utf8_printf(stderr
, "no such index: \"%s\"\n", azArg
[1]);
4982 goto meta_command_exit
;
4984 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
4985 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4988 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
4990 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
4993 if( sqlite3_column_int(pStmt
,1)==-1 ){
4996 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
5001 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
5003 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
5006 sqlite3_finalize(pStmt
);
5007 zSql
= sqlite3_mprintf(
5008 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5009 azArg
[2], zCollist
, zCollist
);
5010 sqlite3_free(zCollist
);
5011 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
5012 if( rc
==SQLITE_OK
){
5013 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
5014 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
5016 utf8_printf(stderr
, "Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
5018 utf8_printf(stdout
, "%s;\n", zSql
);
5020 "WARNING: writing to an imposter table will corrupt the index!\n"
5024 raw_printf(stderr
, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
5029 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5031 #ifdef SQLITE_ENABLE_IOTRACE
5032 if( c
=='i' && strncmp(azArg
[0], "iotrace", n
)==0 ){
5033 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
5034 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
5038 }else if( strcmp(azArg
[1], "-")==0 ){
5039 sqlite3IoTrace
= iotracePrintf
;
5042 iotrace
= fopen(azArg
[1], "w");
5044 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
5048 sqlite3IoTrace
= iotracePrintf
;
5054 if( c
=='l' && n
>=5 && strncmp(azArg
[0], "limits", n
)==0 ){
5055 static const struct {
5056 const char *zLimitName
; /* Name of a limit */
5057 int limitCode
; /* Integer code for that limit */
5059 { "length", SQLITE_LIMIT_LENGTH
},
5060 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
5061 { "column", SQLITE_LIMIT_COLUMN
},
5062 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
5063 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
5064 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
5065 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
5066 { "attached", SQLITE_LIMIT_ATTACHED
},
5067 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
5068 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
5069 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
5070 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
5075 for(i
=0; i
<ArraySize(aLimit
); i
++){
5076 printf("%20s %d\n", aLimit
[i
].zLimitName
,
5077 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
5080 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
5082 goto meta_command_exit
;
5085 n2
= strlen30(azArg
[1]);
5086 for(i
=0; i
<ArraySize(aLimit
); i
++){
5087 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
5091 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
5093 goto meta_command_exit
;
5098 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
5099 "enter \".limits\" with no arguments for a list.\n",
5102 goto meta_command_exit
;
5105 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
5106 (int)integerValue(azArg
[2]));
5108 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
5109 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
5113 if( c
=='l' && n
>2 && strncmp(azArg
[0], "lint", n
)==0 ){
5115 lintDotCommand(p
, azArg
, nArg
);
5118 #ifndef SQLITE_OMIT_LOAD_EXTENSION
5119 if( c
=='l' && strncmp(azArg
[0], "load", n
)==0 ){
5120 const char *zFile
, *zProc
;
5123 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
5125 goto meta_command_exit
;
5128 zProc
= nArg
>=3 ? azArg
[2] : 0;
5130 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
5131 if( rc
!=SQLITE_OK
){
5132 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
5133 sqlite3_free(zErrMsg
);
5139 if( c
=='l' && strncmp(azArg
[0], "log", n
)==0 ){
5141 raw_printf(stderr
, "Usage: .log FILENAME\n");
5144 const char *zFile
= azArg
[1];
5145 output_file_close(p
->pLog
);
5146 p
->pLog
= output_file_open(zFile
);
5150 if( c
=='m' && strncmp(azArg
[0], "mode", n
)==0 ){
5151 const char *zMode
= nArg
>=2 ? azArg
[1] : "";
5152 int n2
= (int)strlen(zMode
);
5154 if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"lines",n2
)==0 ){
5155 p
->mode
= MODE_Line
;
5156 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
5157 }else if( c2
=='c' && strncmp(azArg
[1],"columns",n2
)==0 ){
5158 p
->mode
= MODE_Column
;
5159 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
5160 }else if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"list",n2
)==0 ){
5161 p
->mode
= MODE_List
;
5162 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
5163 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
5164 }else if( c2
=='h' && strncmp(azArg
[1],"html",n2
)==0 ){
5165 p
->mode
= MODE_Html
;
5166 }else if( c2
=='t' && strncmp(azArg
[1],"tcl",n2
)==0 ){
5168 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
5169 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
5170 }else if( c2
=='c' && strncmp(azArg
[1],"csv",n2
)==0 ){
5172 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
5173 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
5174 }else if( c2
=='t' && strncmp(azArg
[1],"tabs",n2
)==0 ){
5175 p
->mode
= MODE_List
;
5176 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
5177 }else if( c2
=='i' && strncmp(azArg
[1],"insert",n2
)==0 ){
5178 p
->mode
= MODE_Insert
;
5179 set_table_name(p
, nArg
>=3 ? azArg
[2] : "table");
5180 }else if( c2
=='q' && strncmp(azArg
[1],"quote",n2
)==0 ){
5181 p
->mode
= MODE_Quote
;
5182 }else if( c2
=='a' && strncmp(azArg
[1],"ascii",n2
)==0 ){
5183 p
->mode
= MODE_Ascii
;
5184 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
5185 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
5186 }else if( nArg
==1 ){
5187 raw_printf(p
->out
, "current output mode: %s\n", modeDescr
[p
->mode
]);
5189 raw_printf(stderr
, "Error: mode should be one of: "
5190 "ascii column csv html insert line list quote tabs tcl\n");
5196 if( c
=='n' && strncmp(azArg
[0], "nullvalue", n
)==0 ){
5198 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
5199 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
5201 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
5206 if( c
=='o' && strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
5207 char *zNewFilename
; /* Name of the database file to open */
5208 int iName
= 1; /* Index in azArg[] of the filename */
5209 int newFlag
= 0; /* True to delete file before opening */
5210 /* Close the existing database */
5211 session_close_all(p
);
5212 sqlite3_close(p
->db
);
5215 sqlite3_free(p
->zFreeOnClose
);
5216 p
->zFreeOnClose
= 0;
5217 /* Check for command-line arguments */
5218 for(iName
=1; iName
<nArg
&& azArg
[iName
][0]=='-'; iName
++){
5219 const char *z
= azArg
[iName
];
5220 if( optionMatch(z
,"new") ){
5222 }else if( z
[0]=='-' ){
5223 utf8_printf(stderr
, "unknown option: %s\n", z
);
5225 goto meta_command_exit
;
5228 /* If a filename is specified, try to open it first */
5229 zNewFilename
= nArg
>iName
? sqlite3_mprintf("%s", azArg
[iName
]) : 0;
5231 if( newFlag
) shellDeleteFile(zNewFilename
);
5232 p
->zDbFilename
= zNewFilename
;
5235 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
5236 sqlite3_free(zNewFilename
);
5238 p
->zFreeOnClose
= zNewFilename
;
5242 /* As a fall-back open a TEMP database */
5249 && (strncmp(azArg
[0], "output", n
)==0 || strncmp(azArg
[0], "once", n
)==0)
5251 const char *zFile
= nArg
>=2 ? azArg
[1] : "stdout";
5253 utf8_printf(stderr
, "Usage: .%s FILE\n", azArg
[0]);
5255 goto meta_command_exit
;
5257 if( n
>1 && strncmp(azArg
[0], "once", n
)==0 ){
5259 raw_printf(stderr
, "Usage: .once FILE\n");
5261 goto meta_command_exit
;
5268 if( zFile
[0]=='|' ){
5269 #ifdef SQLITE_OMIT_POPEN
5270 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
5274 p
->out
= popen(zFile
+ 1, "w");
5276 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
5280 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
5284 p
->out
= output_file_open(zFile
);
5286 if( strcmp(zFile
,"off")!=0 ){
5287 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
5292 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
5297 if( c
=='p' && n
>=3 && strncmp(azArg
[0], "print", n
)==0 ){
5299 for(i
=1; i
<nArg
; i
++){
5300 if( i
>1 ) raw_printf(p
->out
, " ");
5301 utf8_printf(p
->out
, "%s", azArg
[i
]);
5303 raw_printf(p
->out
, "\n");
5306 if( c
=='p' && strncmp(azArg
[0], "prompt", n
)==0 ){
5308 strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
5311 strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
5315 if( c
=='q' && strncmp(azArg
[0], "quit", n
)==0 ){
5319 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "read", n
)==0 ){
5322 raw_printf(stderr
, "Usage: .read FILE\n");
5324 goto meta_command_exit
;
5326 alt
= fopen(azArg
[1], "rb");
5328 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
5331 rc
= process_input(p
, alt
);
5336 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "restore", n
)==0 ){
5337 const char *zSrcFile
;
5340 sqlite3_backup
*pBackup
;
5344 zSrcFile
= azArg
[1];
5346 }else if( nArg
==3 ){
5347 zSrcFile
= azArg
[2];
5350 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
5352 goto meta_command_exit
;
5354 rc
= sqlite3_open(zSrcFile
, &pSrc
);
5355 if( rc
!=SQLITE_OK
){
5356 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
5357 sqlite3_close(pSrc
);
5361 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
5363 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
5364 sqlite3_close(pSrc
);
5367 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
5368 || rc
==SQLITE_BUSY
){
5369 if( rc
==SQLITE_BUSY
){
5370 if( nTimeout
++ >= 3 ) break;
5374 sqlite3_backup_finish(pBackup
);
5375 if( rc
==SQLITE_DONE
){
5377 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
5378 raw_printf(stderr
, "Error: source database is busy\n");
5381 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
5384 sqlite3_close(pSrc
);
5388 if( c
=='s' && strncmp(azArg
[0], "scanstats", n
)==0 ){
5390 p
->scanstatsOn
= booleanValue(azArg
[1]);
5391 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
5392 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
5395 raw_printf(stderr
, "Usage: .scanstats on|off\n");
5400 if( c
=='s' && strncmp(azArg
[0], "schema", n
)==0 ){
5404 const char *zDiv
= "(";
5405 const char *zName
= 0;
5411 memcpy(&data
, p
, sizeof(data
));
5412 data
.showHeader
= 0;
5413 data
.cMode
= data
.mode
= MODE_Semi
;
5415 for(ii
=1; ii
<nArg
; ii
++){
5416 if( optionMatch(azArg
[ii
],"indent") ){
5417 data
.cMode
= data
.mode
= MODE_Pretty
;
5418 }else if( optionMatch(azArg
[ii
],"debug") ){
5420 }else if( zName
==0 ){
5423 raw_printf(stderr
, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
5425 goto meta_command_exit
;
5429 int isMaster
= sqlite3_strlike(zName
, "sqlite_master", 0)==0;
5430 if( isMaster
|| sqlite3_strlike(zName
,"sqlite_temp_master",0)==0 ){
5431 char *new_argv
[2], *new_colv
[2];
5432 new_argv
[0] = sqlite3_mprintf(
5433 "CREATE TABLE %s (\n"
5437 " rootpage integer,\n"
5439 ")", isMaster
? "sqlite_master" : "sqlite_temp_master");
5441 new_colv
[0] = "sql";
5443 callback(&data
, 1, new_argv
, new_colv
);
5444 sqlite3_free(new_argv
[0]);
5448 sqlite3_stmt
*pStmt
= 0;
5449 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
5452 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
5453 sqlite3_finalize(pStmt
);
5455 goto meta_command_exit
;
5457 appendText(&sSelect
, "SELECT sql FROM", 0);
5459 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
5460 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
5462 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
5463 appendText(&sSelect
, zDiv
, 0);
5464 zDiv
= " UNION ALL ";
5465 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
5466 if( sqlite3_stricmp(zDb
, "main")!=0 ){
5467 appendText(&sSelect
, zDb
, '"');
5469 appendText(&sSelect
, "NULL", 0);
5471 appendText(&sSelect
, ",name) AS sql, type, tbl_name, name, rowid,", 0);
5472 appendText(&sSelect
, zScNum
, 0);
5473 appendText(&sSelect
, " AS snum, ", 0);
5474 appendText(&sSelect
, zDb
, '\'');
5475 appendText(&sSelect
, " AS sname FROM ", 0);
5476 appendText(&sSelect
, zDb
, '"');
5477 appendText(&sSelect
, ".sqlite_master", 0);
5479 sqlite3_finalize(pStmt
);
5480 #ifdef SQLITE_INTROSPECTION_PRAGMAS
5482 appendText(&sSelect
,
5483 " UNION ALL SELECT shell_module_schema(name),"
5484 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
5487 appendText(&sSelect
, ") WHERE ", 0);
5489 char *zQarg
= sqlite3_mprintf("%Q", zName
);
5490 if( strchr(zName
, '.') ){
5491 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
5493 appendText(&sSelect
, "lower(tbl_name)", 0);
5495 appendText(&sSelect
, strchr(zName
, '*') ? " GLOB " : " LIKE ", 0);
5496 appendText(&sSelect
, zQarg
, 0);
5497 appendText(&sSelect
, " AND ", 0);
5498 sqlite3_free(zQarg
);
5500 appendText(&sSelect
, "type!='meta' AND sql IS NOT NULL"
5501 " ORDER BY snum, rowid", 0);
5503 utf8_printf(p
->out
, "SQL: %s;\n", sSelect
.z
);
5505 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
5510 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
5511 sqlite3_free(zErrMsg
);
5513 }else if( rc
!= SQLITE_OK
){
5514 raw_printf(stderr
,"Error: querying schema information\n");
5521 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5522 if( c
=='s' && n
==11 && strncmp(azArg
[0], "selecttrace", n
)==0 ){
5523 sqlite3SelectTrace
= (int)integerValue(azArg
[1]);
5527 #if defined(SQLITE_ENABLE_SESSION)
5528 if( c
=='s' && strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
5529 OpenSession
*pSession
= &p
->aSession
[0];
5530 char **azCmd
= &azArg
[1];
5532 int nCmd
= nArg
- 1;
5534 if( nArg
<=1 ) goto session_syntax_error
;
5537 for(iSes
=0; iSes
<p
->nSession
; iSes
++){
5538 if( strcmp(p
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
5540 if( iSes
<p
->nSession
){
5541 pSession
= &p
->aSession
[iSes
];
5545 pSession
= &p
->aSession
[0];
5550 /* .session attach TABLE
5551 ** Invoke the sqlite3session_attach() interface to attach a particular
5552 ** table so that it is never filtered.
5554 if( strcmp(azCmd
[0],"attach")==0 ){
5555 if( nCmd
!=2 ) goto session_syntax_error
;
5556 if( pSession
->p
==0 ){
5558 raw_printf(stderr
, "ERROR: No sessions are open\n");
5560 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
5562 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
5568 /* .session changeset FILE
5569 ** .session patchset FILE
5570 ** Write a changeset or patchset into a file. The file is overwritten.
5572 if( strcmp(azCmd
[0],"changeset")==0 || strcmp(azCmd
[0],"patchset")==0 ){
5574 if( nCmd
!=2 ) goto session_syntax_error
;
5575 if( pSession
->p
==0 ) goto session_not_open
;
5576 out
= fopen(azCmd
[1], "wb");
5578 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n", azCmd
[1]);
5582 if( azCmd
[0][0]=='c' ){
5583 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
5585 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
5588 printf("Error: error code %d\n", rc
);
5592 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
5593 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
5596 sqlite3_free(pChng
);
5602 ** Close the identified session
5604 if( strcmp(azCmd
[0], "close")==0 ){
5605 if( nCmd
!=1 ) goto session_syntax_error
;
5607 session_close(pSession
);
5608 p
->aSession
[iSes
] = p
->aSession
[--p
->nSession
];
5612 /* .session enable ?BOOLEAN?
5613 ** Query or set the enable flag
5615 if( strcmp(azCmd
[0], "enable")==0 ){
5617 if( nCmd
>2 ) goto session_syntax_error
;
5618 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
5620 ii
= sqlite3session_enable(pSession
->p
, ii
);
5621 utf8_printf(p
->out
, "session %s enable flag = %d\n",
5622 pSession
->zName
, ii
);
5626 /* .session filter GLOB ....
5627 ** Set a list of GLOB patterns of table names to be excluded.
5629 if( strcmp(azCmd
[0], "filter")==0 ){
5631 if( nCmd
<2 ) goto session_syntax_error
;
5633 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
5634 sqlite3_free(pSession
->azFilter
[ii
]);
5636 sqlite3_free(pSession
->azFilter
);
5637 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
5638 pSession
->azFilter
= sqlite3_malloc( nByte
);
5639 if( pSession
->azFilter
==0 ){
5640 raw_printf(stderr
, "Error: out or memory\n");
5643 for(ii
=1; ii
<nCmd
; ii
++){
5644 pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
5646 pSession
->nFilter
= ii
-1;
5650 /* .session indirect ?BOOLEAN?
5651 ** Query or set the indirect flag
5653 if( strcmp(azCmd
[0], "indirect")==0 ){
5655 if( nCmd
>2 ) goto session_syntax_error
;
5656 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
5658 ii
= sqlite3session_indirect(pSession
->p
, ii
);
5659 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
5660 pSession
->zName
, ii
);
5665 ** Determine if the session is empty
5667 if( strcmp(azCmd
[0], "isempty")==0 ){
5669 if( nCmd
!=1 ) goto session_syntax_error
;
5671 ii
= sqlite3session_isempty(pSession
->p
);
5672 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
5673 pSession
->zName
, ii
);
5678 ** List all currently open sessions
5680 if( strcmp(azCmd
[0],"list")==0 ){
5681 for(i
=0; i
<p
->nSession
; i
++){
5682 utf8_printf(p
->out
, "%d %s\n", i
, p
->aSession
[i
].zName
);
5686 /* .session open DB NAME
5687 ** Open a new session called NAME on the attached database DB.
5688 ** DB is normally "main".
5690 if( strcmp(azCmd
[0],"open")==0 ){
5692 if( nCmd
!=3 ) goto session_syntax_error
;
5694 if( zName
[0]==0 ) goto session_syntax_error
;
5695 for(i
=0; i
<p
->nSession
; i
++){
5696 if( strcmp(p
->aSession
[i
].zName
,zName
)==0 ){
5697 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
5698 goto meta_command_exit
;
5701 if( p
->nSession
>=ArraySize(p
->aSession
) ){
5702 raw_printf(stderr
, "Maximum of %d sessions\n", ArraySize(p
->aSession
));
5703 goto meta_command_exit
;
5705 pSession
= &p
->aSession
[p
->nSession
];
5706 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
5708 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
5710 goto meta_command_exit
;
5712 pSession
->nFilter
= 0;
5713 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
5715 pSession
->zName
= sqlite3_mprintf("%s", zName
);
5717 /* If no command name matches, show a syntax error */
5718 session_syntax_error
:
5724 /* Undocumented commands for internal testing. Subject to change
5725 ** without notice. */
5726 if( c
=='s' && n
>=10 && strncmp(azArg
[0], "selftest-", 9)==0 ){
5727 if( strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
5729 for(i
=1; i
<nArg
; i
++){
5730 v
= booleanValue(azArg
[i
]);
5731 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
5734 if( strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
5735 int i
; sqlite3_int64 v
;
5736 for(i
=1; i
<nArg
; i
++){
5738 v
= integerValue(azArg
[i
]);
5739 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
5740 utf8_printf(p
->out
, "%s", zBuf
);
5746 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"selftest",n
)==0 ){
5747 int bIsInit
= 0; /* True to initialize the SELFTEST table */
5748 int bVerbose
= 0; /* Verbose output */
5749 int bSelftestExists
; /* True if SELFTEST already exists */
5750 int i
, k
; /* Loop counters */
5751 int nTest
= 0; /* Number of tests runs */
5752 int nErr
= 0; /* Number of errors seen */
5753 ShellText str
; /* Answer for a query */
5754 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
5757 for(i
=1; i
<nArg
; i
++){
5758 const char *z
= azArg
[i
];
5759 if( z
[0]=='-' && z
[1]=='-' ) z
++;
5760 if( strcmp(z
,"-init")==0 ){
5763 if( strcmp(z
,"-v")==0 ){
5767 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
5768 azArg
[i
], azArg
[0]);
5769 raw_printf(stderr
, "Should be one of: --init -v\n");
5771 goto meta_command_exit
;
5774 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
5776 bSelftestExists
= 0;
5778 bSelftestExists
= 1;
5781 createSelftestTable(p
);
5782 bSelftestExists
= 1;
5785 appendText(&str
, "x", 0);
5786 for(k
=bSelftestExists
; k
>=0; k
--){
5788 rc
= sqlite3_prepare_v2(p
->db
,
5789 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
5792 rc
= sqlite3_prepare_v2(p
->db
,
5793 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
5794 " (1,'run','PRAGMA integrity_check','ok')",
5798 raw_printf(stderr
, "Error querying the selftest table\n");
5800 sqlite3_finalize(pStmt
);
5801 goto meta_command_exit
;
5803 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
5804 int tno
= sqlite3_column_int(pStmt
, 0);
5805 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
5806 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
5807 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
5811 char *zQuote
= sqlite3_mprintf("%q", zSql
);
5812 printf("%d: %s %s\n", tno
, zOp
, zSql
);
5813 sqlite3_free(zQuote
);
5815 if( strcmp(zOp
,"memo")==0 ){
5816 utf8_printf(p
->out
, "%s\n", zSql
);
5818 if( strcmp(zOp
,"run")==0 ){
5822 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
5825 utf8_printf(p
->out
, "Result: %s\n", str
.z
);
5827 if( rc
|| zErrMsg
){
5830 utf8_printf(p
->out
, "%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
5831 sqlite3_free(zErrMsg
);
5832 }else if( strcmp(zAns
,str
.z
)!=0 ){
5835 utf8_printf(p
->out
, "%d: Expected: [%s]\n", tno
, zAns
);
5836 utf8_printf(p
->out
, "%d: Got: [%s]\n", tno
, str
.z
);
5841 "Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
5845 } /* End loop over rows of content from SELFTEST */
5846 sqlite3_finalize(pStmt
);
5847 } /* End loop over k */
5849 utf8_printf(p
->out
, "%d errors out of %d tests\n", nErr
, nTest
);
5852 if( c
=='s' && strncmp(azArg
[0], "separator", n
)==0 ){
5853 if( nArg
<2 || nArg
>3 ){
5854 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
5858 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
5859 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
5862 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
5863 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
5867 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"sha3sum",n
)==0 ){
5868 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
5869 int i
; /* Loop counter */
5870 int bSchema
= 0; /* Also hash the schema */
5871 int bSeparate
= 0; /* Hash each table separately */
5872 int iSize
= 224; /* Hash algorithm to use */
5873 int bDebug
= 0; /* Only show the query that would have run */
5874 sqlite3_stmt
*pStmt
; /* For querying tables names */
5875 char *zSql
; /* SQL to be run */
5876 char *zSep
; /* Separator */
5877 ShellText sSql
; /* Complete SQL for the query to run the hash */
5878 ShellText sQuery
; /* Set of queries used to read all content */
5880 for(i
=1; i
<nArg
; i
++){
5881 const char *z
= azArg
[i
];
5884 if( z
[0]=='-' ) z
++;
5885 if( strcmp(z
,"schema")==0 ){
5888 if( strcmp(z
,"sha3-224")==0 || strcmp(z
,"sha3-256")==0
5889 || strcmp(z
,"sha3-384")==0 || strcmp(z
,"sha3-512")==0
5891 iSize
= atoi(&z
[5]);
5893 if( strcmp(z
,"debug")==0 ){
5897 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
5898 azArg
[i
], azArg
[0]);
5899 raw_printf(stderr
, "Should be one of: --schema"
5900 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
5902 goto meta_command_exit
;
5905 raw_printf(stderr
, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
5907 goto meta_command_exit
;
5911 if( sqlite3_strlike("sqlite_%", zLike
, 0)==0 ) bSchema
= 1;
5915 zSql
= "SELECT lower(name) FROM sqlite_master"
5916 " WHERE type='table' AND coalesce(rootpage,0)>1"
5917 " UNION ALL SELECT 'sqlite_master'"
5918 " ORDER BY 1 collate nocase";
5920 zSql
= "SELECT lower(name) FROM sqlite_master"
5921 " WHERE type='table' AND coalesce(rootpage,0)>1"
5922 " AND name NOT LIKE 'sqlite_%'"
5923 " ORDER BY 1 collate nocase";
5925 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
5928 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
5930 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
5931 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
5932 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
5933 if( strncmp(zTab
, "sqlite_",7)!=0 ){
5934 appendText(&sQuery
,"SELECT * FROM ", 0);
5935 appendText(&sQuery
,zTab
,'"');
5936 appendText(&sQuery
," NOT INDEXED;", 0);
5937 }else if( strcmp(zTab
, "sqlite_master")==0 ){
5938 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_master"
5939 " ORDER BY name;", 0);
5940 }else if( strcmp(zTab
, "sqlite_sequence")==0 ){
5941 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
5942 " ORDER BY name;", 0);
5943 }else if( strcmp(zTab
, "sqlite_stat1")==0 ){
5944 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
5945 " ORDER BY tbl,idx;", 0);
5946 }else if( strcmp(zTab
, "sqlite_stat3")==0
5947 || strcmp(zTab
, "sqlite_stat4")==0 ){
5948 appendText(&sQuery
, "SELECT * FROM ", 0);
5949 appendText(&sQuery
, zTab
, 0);
5950 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
5952 appendText(&sSql
, zSep
, 0);
5953 appendText(&sSql
, sQuery
.z
, '\'');
5955 appendText(&sSql
, ",", 0);
5956 appendText(&sSql
, zTab
, '\'');
5959 sqlite3_finalize(pStmt
);
5961 zSql
= sqlite3_mprintf(
5963 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
5964 " FROM [sha3sum$query]",
5967 zSql
= sqlite3_mprintf(
5969 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
5970 " FROM [sha3sum$query]",
5976 utf8_printf(p
->out
, "%s\n", zSql
);
5978 shell_exec(p
->db
, zSql
, shell_callback
, p
, 0);
5984 && (strncmp(azArg
[0], "shell", n
)==0 || strncmp(azArg
[0],"system",n
)==0)
5989 raw_printf(stderr
, "Usage: .system COMMAND\n");
5991 goto meta_command_exit
;
5993 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
5994 for(i
=2; i
<nArg
; i
++){
5995 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
6000 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
6003 if( c
=='s' && strncmp(azArg
[0], "show", n
)==0 ){
6004 static const char *azBool
[] = { "off", "on", "trigger", "full"};
6007 raw_printf(stderr
, "Usage: .show\n");
6009 goto meta_command_exit
;
6011 utf8_printf(p
->out
, "%12.12s: %s\n","echo",
6012 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
6013 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
6014 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
6015 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
6016 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
6017 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
6018 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
6019 output_c_string(p
->out
, p
->nullValue
);
6020 raw_printf(p
->out
, "\n");
6021 utf8_printf(p
->out
,"%12.12s: %s\n","output",
6022 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
6023 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
6024 output_c_string(p
->out
, p
->colSeparator
);
6025 raw_printf(p
->out
, "\n");
6026 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
6027 output_c_string(p
->out
, p
->rowSeparator
);
6028 raw_printf(p
->out
, "\n");
6029 utf8_printf(p
->out
, "%12.12s: %s\n","stats", azBool
[p
->statsOn
!=0]);
6030 utf8_printf(p
->out
, "%12.12s: ", "width");
6031 for (i
=0;i
<(int)ArraySize(p
->colWidth
) && p
->colWidth
[i
] != 0;i
++) {
6032 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
6034 raw_printf(p
->out
, "\n");
6035 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
6036 p
->zDbFilename
? p
->zDbFilename
: "");
6039 if( c
=='s' && strncmp(azArg
[0], "stats", n
)==0 ){
6041 p
->statsOn
= booleanValue(azArg
[1]);
6042 }else if( nArg
==1 ){
6043 display_stats(p
->db
, p
, 0);
6045 raw_printf(stderr
, "Usage: .stats ?on|off?\n");
6050 if( (c
=='t' && n
>1 && strncmp(azArg
[0], "tables", n
)==0)
6051 || (c
=='i' && (strncmp(azArg
[0], "indices", n
)==0
6052 || strncmp(azArg
[0], "indexes", n
)==0) )
6054 sqlite3_stmt
*pStmt
;
6061 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
6062 if( rc
) return shellDatabaseError(p
->db
);
6064 if( nArg
>2 && c
=='i' ){
6065 /* It is an historical accident that the .indexes command shows an error
6066 ** when called with the wrong number of arguments whereas the .tables
6067 ** command does not. */
6068 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
6070 goto meta_command_exit
;
6072 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
6073 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
6074 if( zDbName
==0 ) continue;
6075 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
6076 if( sqlite3_stricmp(zDbName
, "main")==0 ){
6077 appendText(&s
, "SELECT name FROM ", 0);
6079 appendText(&s
, "SELECT ", 0);
6080 appendText(&s
, zDbName
, '\'');
6081 appendText(&s
, "||'.'||name FROM ", 0);
6083 appendText(&s
, zDbName
, '"');
6084 appendText(&s
, ".sqlite_master ", 0);
6086 appendText(&s
," WHERE type IN ('table','view')"
6087 " AND name NOT LIKE 'sqlite_%'"
6088 " AND name LIKE ?1", 0);
6090 appendText(&s
," WHERE type='index'"
6091 " AND tbl_name LIKE ?1", 0);
6094 rc
= sqlite3_finalize(pStmt
);
6095 appendText(&s
, " ORDER BY 1", 0);
6096 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
6098 if( rc
) return shellDatabaseError(p
->db
);
6100 /* Run the SQL statement prepared by the above block. Store the results
6101 ** as an array of nul-terminated strings in azResult[]. */
6105 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
6107 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
6109 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6112 int n2
= nAlloc
*2 + 10;
6113 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
6115 rc
= shellNomemError();
6121 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
6122 if( 0==azResult
[nRow
] ){
6123 rc
= shellNomemError();
6128 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
6129 rc
= shellDatabaseError(p
->db
);
6132 /* Pretty-print the contents of array azResult[] to the output */
6133 if( rc
==0 && nRow
>0 ){
6134 int len
, maxlen
= 0;
6136 int nPrintCol
, nPrintRow
;
6137 for(i
=0; i
<nRow
; i
++){
6138 len
= strlen30(azResult
[i
]);
6139 if( len
>maxlen
) maxlen
= len
;
6141 nPrintCol
= 80/(maxlen
+2);
6142 if( nPrintCol
<1 ) nPrintCol
= 1;
6143 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
6144 for(i
=0; i
<nPrintRow
; i
++){
6145 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
6146 char *zSp
= j
<nPrintRow
? "" : " ";
6147 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
6148 azResult
[j
] ? azResult
[j
]:"");
6150 raw_printf(p
->out
, "\n");
6154 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
6155 sqlite3_free(azResult
);
6158 /* Begin redirecting output to the file "testcase-out.txt" */
6159 if( c
=='t' && strcmp(azArg
[0],"testcase")==0 ){
6161 p
->out
= output_file_open("testcase-out.txt");
6163 raw_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
6166 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
6168 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
6172 #ifndef SQLITE_UNTESTABLE
6173 if( c
=='t' && n
>=8 && strncmp(azArg
[0], "testctrl", n
)==0 ){
6174 static const struct {
6175 const char *zCtrlName
; /* Name of a test-control option */
6176 int ctrlCode
; /* Integer code for that option */
6177 const char *zUsage
; /* Usage notes */
6179 { "always", SQLITE_TESTCTRL_ALWAYS
, "BOOLEAN" },
6180 { "assert", SQLITE_TESTCTRL_ASSERT
, "BOOLEAN" },
6181 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
6182 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
6183 { "byteorder", SQLITE_TESTCTRL_BYTEORDER
, "" },
6184 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
6185 { "imposter", SQLITE_TESTCTRL_IMPOSTER
, "SCHEMA ON/OFF ROOTPAGE"},
6186 #ifdef SQLITE_N_KEYWORD
6187 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD
, "IDENTIFIER" },
6189 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,"BOOLEAN" },
6190 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
, "BOOLEAN" },
6191 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
, "DISABLE-MASK" },
6193 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE
, "" },
6195 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
, "OFFSET " },
6196 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET
, "" },
6197 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
, "" },
6198 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, "" },
6199 { "reserve", SQLITE_TESTCTRL_RESERVE
, "BYTES-OF-RESERVE" },
6203 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
6206 const char *zCmd
= 0;
6209 zCmd
= nArg
>=2 ? azArg
[1] : "help";
6211 /* The argument can optionally begin with "-" or "--" */
6212 if( zCmd
[0]=='-' && zCmd
[1] ){
6214 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
6217 /* --help lists all test-controls */
6218 if( strcmp(zCmd
,"help")==0 ){
6219 utf8_printf(p
->out
, "Available test-controls:\n");
6220 for(i
=0; i
<ArraySize(aCtrl
); i
++){
6221 utf8_printf(p
->out
, " .testctrl %s %s\n",
6222 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
6225 goto meta_command_exit
;
6228 /* convert testctrl text option to value. allow any unique prefix
6229 ** of the option name, or a numerical value. */
6230 n2
= strlen30(zCmd
);
6231 for(i
=0; i
<ArraySize(aCtrl
); i
++){
6232 if( strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
6234 testctrl
= aCtrl
[i
].ctrlCode
;
6237 utf8_printf(stderr
, "Error: ambiguous test-control: \"%s\"\n"
6238 "Use \".testctrl --help\" for help\n", zCmd
);
6240 goto meta_command_exit
;
6245 utf8_printf(stderr
,"Error: unknown test-control: %s\n"
6246 "Use \".testctrl --help\" for help\n", zCmd
);
6250 /* sqlite3_test_control(int, db, int) */
6251 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
6252 case SQLITE_TESTCTRL_RESERVE
:
6254 int opt
= (int)strtol(azArg
[2], 0, 0);
6255 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
6260 /* sqlite3_test_control(int) */
6261 case SQLITE_TESTCTRL_PRNG_SAVE
:
6262 case SQLITE_TESTCTRL_PRNG_RESTORE
:
6263 case SQLITE_TESTCTRL_PRNG_RESET
:
6264 case SQLITE_TESTCTRL_BYTEORDER
:
6266 rc2
= sqlite3_test_control(testctrl
);
6267 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
6271 /* sqlite3_test_control(int, uint) */
6272 case SQLITE_TESTCTRL_PENDING_BYTE
:
6274 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
6275 rc2
= sqlite3_test_control(testctrl
, opt
);
6280 /* sqlite3_test_control(int, int) */
6281 case SQLITE_TESTCTRL_ASSERT
:
6282 case SQLITE_TESTCTRL_ALWAYS
:
6284 int opt
= booleanValue(azArg
[2]);
6285 rc2
= sqlite3_test_control(testctrl
, opt
);
6290 /* sqlite3_test_control(int, int) */
6291 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
6292 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
6294 int opt
= booleanValue(azArg
[2]);
6295 rc2
= sqlite3_test_control(testctrl
, opt
);
6300 /* sqlite3_test_control(int, char *) */
6301 #ifdef SQLITE_N_KEYWORD
6302 case SQLITE_TESTCTRL_ISKEYWORD
:
6304 const char *opt
= azArg
[2];
6305 rc2
= sqlite3_test_control(testctrl
, opt
);
6311 case SQLITE_TESTCTRL_IMPOSTER
:
6313 rc2
= sqlite3_test_control(testctrl
, p
->db
,
6315 integerValue(azArg
[3]),
6316 integerValue(azArg
[4]));
6322 case SQLITE_TESTCTRL_PARSER_COVERAGE
:
6324 sqlite3_test_control(testctrl
, p
->out
);
6330 if( isOk
==0 && iCtrl
>=0 ){
6331 utf8_printf(p
->out
, "Usage: .testctrl %s %s\n", zCmd
, aCtrl
[iCtrl
].zUsage
);
6333 }else if( isOk
==1 ){
6334 raw_printf(p
->out
, "%d\n", rc2
);
6335 }else if( isOk
==2 ){
6336 raw_printf(p
->out
, "0x%08x\n", rc2
);
6339 #endif /* !defined(SQLITE_UNTESTABLE) */
6341 if( c
=='t' && n
>4 && strncmp(azArg
[0], "timeout", n
)==0 ){
6343 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
6346 if( c
=='t' && n
>=5 && strncmp(azArg
[0], "timer", n
)==0 ){
6348 enableTimer
= booleanValue(azArg
[1]);
6349 if( enableTimer
&& !HAS_TIMER
){
6350 raw_printf(stderr
, "Error: timer not available on this system.\n");
6354 raw_printf(stderr
, "Usage: .timer on|off\n");
6359 if( c
=='t' && strncmp(azArg
[0], "trace", n
)==0 ){
6362 raw_printf(stderr
, "Usage: .trace FILE|off\n");
6364 goto meta_command_exit
;
6366 output_file_close(p
->traceOut
);
6367 p
->traceOut
= output_file_open(azArg
[1]);
6368 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
6369 if( p
->traceOut
==0 ){
6370 sqlite3_trace_v2(p
->db
, 0, 0, 0);
6372 sqlite3_trace_v2(p
->db
, SQLITE_TRACE_STMT
, sql_trace_callback
,p
->traceOut
);
6377 #if SQLITE_USER_AUTHENTICATION
6378 if( c
=='u' && strncmp(azArg
[0], "user", n
)==0 ){
6380 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
6382 goto meta_command_exit
;
6385 if( strcmp(azArg
[1],"login")==0 ){
6387 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
6389 goto meta_command_exit
;
6391 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3],
6392 (int)strlen(azArg
[3]));
6394 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
6397 }else if( strcmp(azArg
[1],"add")==0 ){
6399 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
6401 goto meta_command_exit
;
6403 rc
= sqlite3_user_add(p
->db
, azArg
[2],
6404 azArg
[3], (int)strlen(azArg
[3]),
6405 booleanValue(azArg
[4]));
6407 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
6410 }else if( strcmp(azArg
[1],"edit")==0 ){
6412 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
6414 goto meta_command_exit
;
6416 rc
= sqlite3_user_change(p
->db
, azArg
[2],
6417 azArg
[3], (int)strlen(azArg
[3]),
6418 booleanValue(azArg
[4]));
6420 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
6423 }else if( strcmp(azArg
[1],"delete")==0 ){
6425 raw_printf(stderr
, "Usage: .user delete USER\n");
6427 goto meta_command_exit
;
6429 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
6431 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
6435 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
6437 goto meta_command_exit
;
6440 #endif /* SQLITE_USER_AUTHENTICATION */
6442 if( c
=='v' && strncmp(azArg
[0], "version", n
)==0 ){
6443 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
6444 sqlite3_libversion(), sqlite3_sourceid());
6447 if( c
=='v' && strncmp(azArg
[0], "vfsinfo", n
)==0 ){
6448 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
6449 sqlite3_vfs
*pVfs
= 0;
6451 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
6453 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
6454 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
6455 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
6456 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
6461 if( c
=='v' && strncmp(azArg
[0], "vfslist", n
)==0 ){
6463 sqlite3_vfs
*pCurrent
= 0;
6465 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
6467 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
6468 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
6469 pVfs
==pCurrent
? " <--- CURRENT" : "");
6470 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
6471 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
6472 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
6474 raw_printf(p
->out
, "-----------------------------------\n");
6479 if( c
=='v' && strncmp(azArg
[0], "vfsname", n
)==0 ){
6480 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
6483 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
6485 utf8_printf(p
->out
, "%s\n", zVfsName
);
6486 sqlite3_free(zVfsName
);
6491 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6492 if( c
=='w' && strncmp(azArg
[0], "wheretrace", n
)==0 ){
6493 sqlite3WhereTrace
= nArg
>=2 ? booleanValue(azArg
[1]) : 0xff;
6497 if( c
=='w' && strncmp(azArg
[0], "width", n
)==0 ){
6499 assert( nArg
<=ArraySize(azArg
) );
6500 for(j
=1; j
<nArg
&& j
<ArraySize(p
->colWidth
); j
++){
6501 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
6506 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
6507 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
6514 if( p
->outCount
==0 ) output_reset(p
);
6520 ** Return TRUE if a semicolon occurs anywhere in the first N characters
6523 static int line_contains_semicolon(const char *z
, int N
){
6525 for(i
=0; i
<N
; i
++){ if( z
[i
]==';' ) return 1; }
6530 ** Test to see if a line consists entirely of whitespace.
6532 static int _all_whitespace(const char *z
){
6534 if( IsSpace(z
[0]) ) continue;
6535 if( *z
=='/' && z
[1]=='*' ){
6537 while( *z
&& (*z
!='*' || z
[1]!='/') ){ z
++; }
6538 if( *z
==0 ) return 0;
6542 if( *z
=='-' && z
[1]=='-' ){
6544 while( *z
&& *z
!='\n' ){ z
++; }
6545 if( *z
==0 ) return 1;
6554 ** Return TRUE if the line typed in is an SQL command terminator other
6555 ** than a semi-colon. The SQL Server style "go" command is understood
6556 ** as is the Oracle "/".
6558 static int line_is_command_terminator(const char *zLine
){
6559 while( IsSpace(zLine
[0]) ){ zLine
++; };
6560 if( zLine
[0]=='/' && _all_whitespace(&zLine
[1]) ){
6561 return 1; /* Oracle */
6563 if( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o'
6564 && _all_whitespace(&zLine
[2]) ){
6565 return 1; /* SQL Server */
6571 ** Return true if zSql is a complete SQL statement. Return false if it
6572 ** ends in the middle of a string literal or C-style comment.
6574 static int line_is_complete(char *zSql
, int nSql
){
6576 if( zSql
==0 ) return 1;
6579 rc
= sqlite3_complete(zSql
);
6585 ** Run a single line of SQL
6587 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
6592 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
6594 rc
= shell_exec(p
->db
, zSql
, shell_callback
, p
, &zErrMsg
);
6596 if( rc
|| zErrMsg
){
6598 if( in
!=0 || !stdin_is_interactive
){
6599 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
6600 "Error: near line %d:", startline
);
6602 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "Error:");
6605 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrMsg
);
6606 sqlite3_free(zErrMsg
);
6609 utf8_printf(stderr
, "%s %s\n", zPrefix
, sqlite3_errmsg(p
->db
));
6612 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
6613 raw_printf(p
->out
, "changes: %3d total_changes: %d\n",
6614 sqlite3_changes(p
->db
), sqlite3_total_changes(p
->db
));
6621 ** Read input from *in and process it. If *in==0 then input
6622 ** is interactive - the user is typing it it. Otherwise, input
6623 ** is coming from a file or device. A prompt is issued and history
6624 ** is saved only if input is interactive. An interrupt signal will
6625 ** cause this routine to exit immediately, unless input is interactive.
6627 ** Return the number of errors.
6629 static int process_input(ShellState
*p
, FILE *in
){
6630 char *zLine
= 0; /* A single input line */
6631 char *zSql
= 0; /* Accumulated SQL text */
6632 int nLine
; /* Length of current line */
6633 int nSql
= 0; /* Bytes of zSql[] used */
6634 int nAlloc
= 0; /* Allocated zSql[] space */
6635 int nSqlPrior
= 0; /* Bytes of zSql[] used by prior line */
6636 int rc
; /* Error code */
6637 int errCnt
= 0; /* Number of errors seen */
6638 int lineno
= 0; /* Current line number */
6639 int startline
= 0; /* Line number for start of current input */
6641 while( errCnt
==0 || !bail_on_error
|| (in
==0 && stdin_is_interactive
) ){
6643 zLine
= one_input_line(in
, zLine
, nSql
>0);
6646 if( in
==0 && stdin_is_interactive
) printf("\n");
6649 if( seenInterrupt
){
6654 if( nSql
==0 && _all_whitespace(zLine
) ){
6655 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
6658 if( zLine
&& zLine
[0]=='.' && nSql
==0 ){
6659 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
6660 rc
= do_meta_command(zLine
, p
);
6661 if( rc
==2 ){ /* exit requested */
6668 if( line_is_command_terminator(zLine
) && line_is_complete(zSql
, nSql
) ){
6669 memcpy(zLine
,";",2);
6671 nLine
= strlen30(zLine
);
6672 if( nSql
+nLine
+2>=nAlloc
){
6673 nAlloc
= nSql
+nLine
+100;
6674 zSql
= realloc(zSql
, nAlloc
);
6676 raw_printf(stderr
, "Error: out of memory\n");
6683 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
6684 assert( nAlloc
>0 && zSql
!=0 );
6685 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
6689 zSql
[nSql
++] = '\n';
6690 memcpy(zSql
+nSql
, zLine
, nLine
+1);
6693 if( nSql
&& line_contains_semicolon(&zSql
[nSqlPrior
], nSql
-nSqlPrior
)
6694 && sqlite3_complete(zSql
) ){
6695 errCnt
+= runOneSqlLine(p
, zSql
, in
, startline
);
6701 }else if( nSql
&& _all_whitespace(zSql
) ){
6702 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zSql
);
6706 if( nSql
&& !_all_whitespace(zSql
) ){
6707 runOneSqlLine(p
, zSql
, in
, startline
);
6715 ** Return a pathname which is the user's home directory. A
6716 ** 0 return indicates an error of some kind.
6718 static char *find_home_dir(int clearFlag
){
6719 static char *home_dir
= NULL
;
6725 if( home_dir
) return home_dir
;
6727 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6728 && !defined(__RTP__) && !defined(_WRS_KERNEL)
6730 struct passwd
*pwent
;
6731 uid_t uid
= getuid();
6732 if( (pwent
=getpwuid(uid
)) != NULL
) {
6733 home_dir
= pwent
->pw_dir
;
6738 #if defined(_WIN32_WCE)
6739 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6744 #if defined(_WIN32) || defined(WIN32)
6746 home_dir
= getenv("USERPROFILE");
6751 home_dir
= getenv("HOME");
6754 #if defined(_WIN32) || defined(WIN32)
6756 char *zDrive
, *zPath
;
6758 zDrive
= getenv("HOMEDRIVE");
6759 zPath
= getenv("HOMEPATH");
6760 if( zDrive
&& zPath
){
6761 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
6762 home_dir
= malloc( n
);
6763 if( home_dir
==0 ) return 0;
6764 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
6771 #endif /* !_WIN32_WCE */
6774 int n
= strlen30(home_dir
) + 1;
6775 char *z
= malloc( n
);
6776 if( z
) memcpy(z
, home_dir
, n
);
6784 ** Read input from the file given by sqliterc_override. Or if that
6785 ** parameter is NULL, take input from ~/.sqliterc
6787 ** Returns the number of errors.
6789 static void process_sqliterc(
6790 ShellState
*p
, /* Configuration data */
6791 const char *sqliterc_override
/* Name of config file. NULL to use default */
6793 char *home_dir
= NULL
;
6794 const char *sqliterc
= sqliterc_override
;
6798 if (sqliterc
== NULL
) {
6799 home_dir
= find_home_dir(0);
6801 raw_printf(stderr
, "-- warning: cannot find home directory;"
6802 " cannot read ~/.sqliterc\n");
6805 sqlite3_initialize();
6806 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
6809 in
= fopen(sqliterc
,"rb");
6811 if( stdin_is_interactive
){
6812 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
6814 process_input(p
,in
);
6821 ** Show available command line options
6823 static const char zOptions
[] =
6824 " -ascii set output mode to 'ascii'\n"
6825 " -bail stop after hitting an error\n"
6826 " -batch force batch I/O\n"
6827 " -column set output mode to 'column'\n"
6828 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
6829 " -csv set output mode to 'csv'\n"
6830 " -echo print commands before execution\n"
6831 " -init FILENAME read/process named file\n"
6832 " -[no]header turn headers on or off\n"
6833 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6834 " -heap SIZE Size of heap for memsys3 or memsys5\n"
6836 " -help show this message\n"
6837 " -html set output mode to HTML\n"
6838 " -interactive force interactive I/O\n"
6839 " -line set output mode to 'line'\n"
6840 " -list set output mode to 'list'\n"
6841 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
6842 " -mmap N default mmap size set to N\n"
6843 #ifdef SQLITE_ENABLE_MULTIPLEX
6844 " -multiplex enable the multiplexor VFS\n"
6846 " -newline SEP set output row separator. Default: '\\n'\n"
6847 " -nullvalue TEXT set text string for NULL values. Default ''\n"
6848 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
6849 " -quote set output mode to 'quote'\n"
6850 " -separator SEP set output column separator. Default: '|'\n"
6851 " -stats print memory stats before each finalize\n"
6852 " -version show SQLite version\n"
6853 " -vfs NAME use NAME as the default VFS\n"
6854 #ifdef SQLITE_ENABLE_VFSTRACE
6855 " -vfstrace enable tracing of all VFS calls\n"
6858 static void usage(int showDetail
){
6860 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
6861 "FILENAME is the name of an SQLite database. A new database is created\n"
6862 "if the file does not previously exist.\n", Argv0
);
6864 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
6866 raw_printf(stderr
, "Use the -help option for additional information\n");
6872 ** Initialize the state information in data
6874 static void main_init(ShellState
*data
) {
6875 memset(data
, 0, sizeof(*data
));
6876 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
6877 data
->autoExplain
= 1;
6878 memcpy(data
->colSeparator
,SEP_Column
, 2);
6879 memcpy(data
->rowSeparator
,SEP_Row
, 2);
6880 data
->showHeader
= 0;
6881 data
->shellFlgs
= SHFLG_Lookaside
;
6882 sqlite3_config(SQLITE_CONFIG_URI
, 1);
6883 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
6884 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
6885 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
6886 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
6890 ** Output text to the console in a font that attracts extra attention.
6893 static void printBold(const char *zText
){
6894 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
6895 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
6896 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
6897 SetConsoleTextAttribute(out
,
6898 FOREGROUND_RED
|FOREGROUND_INTENSITY
6900 printf("%s", zText
);
6901 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
6904 static void printBold(const char *zText
){
6905 printf("\033[1m%s\033[0m", zText
);
6910 ** Get the argument to an --option. Throw an error and die if no argument
6913 static char *cmdline_option_value(int argc
, char **argv
, int i
){
6915 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
6916 argv
[0], argv
[argc
-1]);
6922 #ifndef SQLITE_SHELL_IS_UTF8
6923 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
6924 # define SQLITE_SHELL_IS_UTF8 (0)
6926 # define SQLITE_SHELL_IS_UTF8 (1)
6930 #if SQLITE_SHELL_IS_UTF8
6931 int SQLITE_CDECL
main(int argc
, char **argv
){
6933 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
6938 const char *zInitFile
= 0;
6941 int warnInmemoryDb
= 0;
6946 setBinaryMode(stdin
, 0);
6947 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
6948 stdin_is_interactive
= isatty(0);
6949 stdout_is_console
= isatty(1);
6951 #if USE_SYSTEM_SQLITE+0!=1
6952 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
6953 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
6954 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
6959 #if !SQLITE_SHELL_IS_UTF8
6960 sqlite3_initialize();
6961 argv
= sqlite3_malloc64(sizeof(argv
[0])*argc
);
6963 raw_printf(stderr
, "out of memory\n");
6966 for(i
=0; i
<argc
; i
++){
6967 argv
[i
] = sqlite3_win32_unicode_to_utf8(wargv
[i
]);
6969 raw_printf(stderr
, "out of memory\n");
6974 assert( argc
>=1 && argv
&& argv
[0] );
6977 /* Make sure we have a valid signal handler early, before anything
6981 signal(SIGINT
, interrupt_handler
);
6982 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
6983 SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
);
6986 #ifdef SQLITE_SHELL_DBNAME_PROC
6988 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
6989 ** of a C-function that will provide the name of the database file. Use
6990 ** this compile-time option to embed this shell program in larger
6992 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
6993 SQLITE_SHELL_DBNAME_PROC(&data
.zDbFilename
);
6998 /* Do an initial pass through the command-line argument to locate
6999 ** the name of the database file, the name of the initialization file,
7000 ** the size of the alternative malloc heap,
7001 ** and the first command to execute.
7003 for(i
=1; i
<argc
; i
++){
7007 if( data
.zDbFilename
==0 ){
7008 data
.zDbFilename
= z
;
7010 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7011 ** mean that nothing is read from stdin */
7014 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
7016 raw_printf(stderr
, "out of memory\n");
7022 if( z
[1]=='-' ) z
++;
7023 if( strcmp(z
,"-separator")==0
7024 || strcmp(z
,"-nullvalue")==0
7025 || strcmp(z
,"-newline")==0
7026 || strcmp(z
,"-cmd")==0
7028 (void)cmdline_option_value(argc
, argv
, ++i
);
7029 }else if( strcmp(z
,"-init")==0 ){
7030 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
7031 }else if( strcmp(z
,"-batch")==0 ){
7032 /* Need to check for batch mode here to so we can avoid printing
7033 ** informational messages (like from process_sqliterc) before
7034 ** we do the actual processing of arguments later in a second pass.
7036 stdin_is_interactive
= 0;
7037 }else if( strcmp(z
,"-heap")==0 ){
7038 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7040 sqlite3_int64 szHeap
;
7042 zSize
= cmdline_option_value(argc
, argv
, ++i
);
7043 szHeap
= integerValue(zSize
);
7044 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
7045 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
7047 (void)cmdline_option_value(argc
, argv
, ++i
);
7049 }else if( strcmp(z
,"-pagecache")==0 ){
7051 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
7052 if( sz
>70000 ) sz
= 70000;
7054 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
7055 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
7056 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
7057 data
.shellFlgs
|= SHFLG_Pagecache
;
7058 }else if( strcmp(z
,"-lookaside")==0 ){
7060 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
7062 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
7064 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
7065 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
7066 #ifdef SQLITE_ENABLE_VFSTRACE
7067 }else if( strcmp(z
,"-vfstrace")==0 ){
7068 extern int vfstrace_register(
7069 const char *zTraceName
,
7070 const char *zOldVfsName
,
7071 int (*xOut
)(const char*,void*),
7075 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
7077 #ifdef SQLITE_ENABLE_MULTIPLEX
7078 }else if( strcmp(z
,"-multiplex")==0 ){
7079 extern int sqlite3_multiple_initialize(const char*,int);
7080 sqlite3_multiplex_initialize(0, 1);
7082 }else if( strcmp(z
,"-mmap")==0 ){
7083 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
7084 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
7085 }else if( strcmp(z
,"-vfs")==0 ){
7086 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(cmdline_option_value(argc
,argv
,++i
));
7088 sqlite3_vfs_register(pVfs
, 1);
7090 utf8_printf(stderr
, "no such VFS: \"%s\"\n", argv
[i
]);
7095 if( data
.zDbFilename
==0 ){
7096 #ifndef SQLITE_OMIT_MEMORYDB
7097 data
.zDbFilename
= ":memory:";
7098 warnInmemoryDb
= argc
==1;
7100 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
7106 /* Go ahead and open the database file if it already exists. If the
7107 ** file does not exist, delay opening it. This prevents empty database
7108 ** files from being created if a user mistypes the database name argument
7109 ** to the sqlite command-line tool.
7111 if( access(data
.zDbFilename
, 0)==0 ){
7115 /* Process the initialization file if there is one. If no -init option
7116 ** is given on the command line, look for a file named ~/.sqliterc and
7117 ** try to process it.
7119 process_sqliterc(&data
,zInitFile
);
7121 /* Make a second pass through the command-line argument and set
7122 ** options. This second pass is delayed until after the initialization
7123 ** file is processed so that the command-line arguments will override
7124 ** settings in the initialization file.
7126 for(i
=1; i
<argc
; i
++){
7128 if( z
[0]!='-' ) continue;
7129 if( z
[1]=='-' ){ z
++; }
7130 if( strcmp(z
,"-init")==0 ){
7132 }else if( strcmp(z
,"-html")==0 ){
7133 data
.mode
= MODE_Html
;
7134 }else if( strcmp(z
,"-list")==0 ){
7135 data
.mode
= MODE_List
;
7136 }else if( strcmp(z
,"-quote")==0 ){
7137 data
.mode
= MODE_Quote
;
7138 }else if( strcmp(z
,"-line")==0 ){
7139 data
.mode
= MODE_Line
;
7140 }else if( strcmp(z
,"-column")==0 ){
7141 data
.mode
= MODE_Column
;
7142 }else if( strcmp(z
,"-csv")==0 ){
7143 data
.mode
= MODE_Csv
;
7144 memcpy(data
.colSeparator
,",",2);
7145 }else if( strcmp(z
,"-ascii")==0 ){
7146 data
.mode
= MODE_Ascii
;
7147 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
7149 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
7151 }else if( strcmp(z
,"-separator")==0 ){
7152 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
7153 "%s",cmdline_option_value(argc
,argv
,++i
));
7154 }else if( strcmp(z
,"-newline")==0 ){
7155 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
7156 "%s",cmdline_option_value(argc
,argv
,++i
));
7157 }else if( strcmp(z
,"-nullvalue")==0 ){
7158 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
7159 "%s",cmdline_option_value(argc
,argv
,++i
));
7160 }else if( strcmp(z
,"-header")==0 ){
7161 data
.showHeader
= 1;
7162 }else if( strcmp(z
,"-noheader")==0 ){
7163 data
.showHeader
= 0;
7164 }else if( strcmp(z
,"-echo")==0 ){
7165 ShellSetFlag(&data
, SHFLG_Echo
);
7166 }else if( strcmp(z
,"-eqp")==0 ){
7167 data
.autoEQP
= AUTOEQP_on
;
7168 }else if( strcmp(z
,"-eqpfull")==0 ){
7169 data
.autoEQP
= AUTOEQP_full
;
7170 }else if( strcmp(z
,"-stats")==0 ){
7172 }else if( strcmp(z
,"-scanstats")==0 ){
7173 data
.scanstatsOn
= 1;
7174 }else if( strcmp(z
,"-backslash")==0 ){
7175 /* Undocumented command-line option: -backslash
7176 ** Causes C-style backslash escapes to be evaluated in SQL statements
7177 ** prior to sending the SQL into SQLite. Useful for injecting
7178 ** crazy bytes in the middle of SQL statements for testing and debugging.
7180 ShellSetFlag(&data
, SHFLG_Backslash
);
7181 }else if( strcmp(z
,"-bail")==0 ){
7183 }else if( strcmp(z
,"-version")==0 ){
7184 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
7186 }else if( strcmp(z
,"-interactive")==0 ){
7187 stdin_is_interactive
= 1;
7188 }else if( strcmp(z
,"-batch")==0 ){
7189 stdin_is_interactive
= 0;
7190 }else if( strcmp(z
,"-heap")==0 ){
7192 }else if( strcmp(z
,"-pagecache")==0 ){
7194 }else if( strcmp(z
,"-lookaside")==0 ){
7196 }else if( strcmp(z
,"-mmap")==0 ){
7198 }else if( strcmp(z
,"-vfs")==0 ){
7200 #ifdef SQLITE_ENABLE_VFSTRACE
7201 }else if( strcmp(z
,"-vfstrace")==0 ){
7204 #ifdef SQLITE_ENABLE_MULTIPLEX
7205 }else if( strcmp(z
,"-multiplex")==0 ){
7208 }else if( strcmp(z
,"-help")==0 ){
7210 }else if( strcmp(z
,"-cmd")==0 ){
7211 /* Run commands that follow -cmd first and separately from commands
7212 ** that simply appear on the command-line. This seems goofy. It would
7213 ** be better if all commands ran in the order that they appear. But
7214 ** we retain the goofy behavior for historical compatibility. */
7215 if( i
==argc
-1 ) break;
7216 z
= cmdline_option_value(argc
,argv
,++i
);
7218 rc
= do_meta_command(z
, &data
);
7219 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
7222 rc
= shell_exec(data
.db
, z
, shell_callback
, &data
, &zErrMsg
);
7224 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
7225 if( bail_on_error
) return rc
!=0 ? rc
: 1;
7227 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
7228 if( bail_on_error
) return rc
;
7232 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
7233 raw_printf(stderr
,"Use -help for a list of options.\n");
7236 data
.cMode
= data
.mode
;
7240 /* Run all arguments that do not begin with '-' as if they were separate
7241 ** command-line inputs, except for the argToSkip argument which contains
7242 ** the database filename.
7244 for(i
=0; i
<nCmd
; i
++){
7245 if( azCmd
[i
][0]=='.' ){
7246 rc
= do_meta_command(azCmd
[i
], &data
);
7247 if( rc
) return rc
==2 ? 0 : rc
;
7250 rc
= shell_exec(data
.db
, azCmd
[i
], shell_callback
, &data
, &zErrMsg
);
7252 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
7253 return rc
!=0 ? rc
: 1;
7255 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
7262 /* Run commands received from standard input
7264 if( stdin_is_interactive
){
7269 "SQLite version %s %.19s\n" /*extra-version-info*/
7270 "Enter \".help\" for usage hints.\n",
7271 sqlite3_libversion(), sqlite3_sourceid()
7273 if( warnInmemoryDb
){
7274 printf("Connected to a ");
7275 printBold("transient in-memory database");
7276 printf(".\nUse \".open FILENAME\" to reopen on a "
7277 "persistent database.\n");
7279 zHome
= find_home_dir(0);
7281 nHistory
= strlen30(zHome
) + 20;
7282 if( (zHistory
= malloc(nHistory
))!=0 ){
7283 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
7286 if( zHistory
){ shell_read_history(zHistory
); }
7287 #if HAVE_READLINE || HAVE_EDITLINE
7288 rl_attempted_completion_function
= readline_completion
;
7289 #elif HAVE_LINENOISE
7290 linenoiseSetCompletionCallback(linenoise_completion
);
7292 rc
= process_input(&data
, 0);
7294 shell_stifle_history(2000);
7295 shell_write_history(zHistory
);
7299 rc
= process_input(&data
, stdin
);
7302 set_table_name(&data
, 0);
7304 session_close_all(&data
);
7305 sqlite3_close(data
.db
);
7307 sqlite3_free(data
.zFreeOnClose
);
7309 #if !SQLITE_SHELL_IS_UTF8
7310 for(i
=0; i
<argc
; i
++) sqlite3_free(argv
[i
]);