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 ** If requested, include the SQLite compiler options file for MSVC.
23 #if defined(INCLUDE_MSVC_H)
28 ** No support for loadable extensions in VxWorks.
30 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
31 # define SQLITE_OMIT_LOAD_EXTENSION 1
35 ** Enable large-file support for fopen() and friends on unix.
37 #ifndef SQLITE_DISABLE_LFS
38 # define _LARGE_FILE 1
39 # ifndef _FILE_OFFSET_BITS
40 # define _FILE_OFFSET_BITS 64
42 # define _LARGEFILE_SOURCE 1
50 #if SQLITE_USER_AUTHENTICATION
51 # include "sqlite3userauth.h"
56 #if !defined(_WIN32) && !defined(WIN32)
58 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
62 # include <sys/types.h>
66 # include <readline/readline.h>
67 # include <readline/history.h>
71 # include <editline/readline.h>
74 #if HAVE_EDITLINE || HAVE_READLINE
76 # define shell_add_history(X) add_history(X)
77 # define shell_read_history(X) read_history(X)
78 # define shell_write_history(X) write_history(X)
79 # define shell_stifle_history(X) stifle_history(X)
80 # define shell_readline(X) readline(X)
84 # include "linenoise.h"
85 # define shell_add_history(X) linenoiseHistoryAdd(X)
86 # define shell_read_history(X) linenoiseHistoryLoad(X)
87 # define shell_write_history(X) linenoiseHistorySave(X)
88 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
89 # define shell_readline(X) linenoise(X)
93 # define shell_read_history(X)
94 # define shell_write_history(X)
95 # define shell_stifle_history(X)
97 # define SHELL_USE_LOCAL_GETLINE 1
101 #if defined(_WIN32) || defined(WIN32)
104 # define isatty(h) _isatty(h)
106 # define access(f,m) _access((f),(m))
109 # define popen _popen
111 # define pclose _pclose
113 /* Make sure isatty() has a prototype. */
114 extern int isatty(int);
116 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
117 /* popen and pclose are not C89 functions and so are
118 ** sometimes omitted from the <stdio.h> header */
119 extern FILE *popen(const char*,const char*);
120 extern int pclose(FILE*);
122 # define SQLITE_OMIT_POPEN 1
126 #if defined(_WIN32_WCE)
127 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
128 * thus we always assume that we have a console. That can be
129 * overridden with the -batch command line option.
134 /* ctype macros that work with signed characters */
135 #define IsSpace(X) isspace((unsigned char)X)
136 #define IsDigit(X) isdigit((unsigned char)X)
137 #define ToLower(X) (char)tolower((unsigned char)X)
139 #if defined(_WIN32) || defined(WIN32)
142 /* string conversion routines only needed on Win32 */
143 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
144 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
145 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
146 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
149 /* On Windows, we normally run with output mode of TEXT so that \n characters
150 ** are automatically translated into \r\n. However, this behavior needs
151 ** to be disabled in some cases (ex: when generating CSV output and when
152 ** rendering quoted strings that contain \n characters). The following
153 ** routines take care of that.
155 #if defined(_WIN32) || defined(WIN32)
156 static void setBinaryMode(FILE *file
, int isOutput
){
157 if( isOutput
) fflush(file
);
158 _setmode(_fileno(file
), _O_BINARY
);
160 static void setTextMode(FILE *file
, int isOutput
){
161 if( isOutput
) fflush(file
);
162 _setmode(_fileno(file
), _O_TEXT
);
165 # define setBinaryMode(X,Y)
166 # define setTextMode(X,Y)
170 /* True if the timer is enabled */
171 static int enableTimer
= 0;
173 /* Return the current wall-clock time */
174 static sqlite3_int64
timeOfDay(void){
175 static sqlite3_vfs
*clockVfs
= 0;
177 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
178 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
179 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
182 clockVfs
->xCurrentTime(clockVfs
, &r
);
183 t
= (sqlite3_int64
)(r
*86400000.0);
188 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
189 #include <sys/time.h>
190 #include <sys/resource.h>
192 /* VxWorks does not support getrusage() as far as we can determine */
193 #if defined(_WRS_KERNEL) || defined(__RTP__)
195 struct timeval ru_utime
; /* user CPU time used */
196 struct timeval ru_stime
; /* system CPU time used */
198 #define getrusage(A,B) memset(B,0,sizeof(*B))
201 /* Saved resource information for the beginning of an operation */
202 static struct rusage sBegin
; /* CPU time at start */
203 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
206 ** Begin timing an operation
208 static void beginTimer(void){
210 getrusage(RUSAGE_SELF
, &sBegin
);
211 iBegin
= timeOfDay();
215 /* Return the difference of two time_structs in seconds */
216 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
217 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
218 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
222 ** Print the timing results.
224 static void endTimer(void){
226 sqlite3_int64 iEnd
= timeOfDay();
228 getrusage(RUSAGE_SELF
, &sEnd
);
229 printf("Run Time: real %.3f user %f sys %f\n",
230 (iEnd
- iBegin
)*0.001,
231 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
232 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
236 #define BEGIN_TIMER beginTimer()
237 #define END_TIMER endTimer()
240 #elif (defined(_WIN32) || defined(WIN32))
242 /* Saved resource information for the beginning of an operation */
243 static HANDLE hProcess
;
244 static FILETIME ftKernelBegin
;
245 static FILETIME ftUserBegin
;
246 static sqlite3_int64 ftWallBegin
;
247 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
248 LPFILETIME
, LPFILETIME
);
249 static GETPROCTIMES getProcessTimesAddr
= NULL
;
252 ** Check to see if we have timer support. Return 1 if necessary
253 ** support found (or found previously).
255 static int hasTimer(void){
256 if( getProcessTimesAddr
){
259 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
260 ** versions. See if the version we are running on has it, and if it
261 ** does, save off a pointer to it and the current process handle.
263 hProcess
= GetCurrentProcess();
265 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
266 if( NULL
!= hinstLib
){
267 getProcessTimesAddr
=
268 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
269 if( NULL
!= getProcessTimesAddr
){
272 FreeLibrary(hinstLib
);
280 ** Begin timing an operation
282 static void beginTimer(void){
283 if( enableTimer
&& getProcessTimesAddr
){
284 FILETIME ftCreation
, ftExit
;
285 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
286 &ftKernelBegin
,&ftUserBegin
);
287 ftWallBegin
= timeOfDay();
291 /* Return the difference of two FILETIME structs in seconds */
292 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
293 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
294 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
295 return (double) ((i64End
- i64Start
) / 10000000.0);
299 ** Print the timing results.
301 static void endTimer(void){
302 if( enableTimer
&& getProcessTimesAddr
){
303 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
304 sqlite3_int64 ftWallEnd
= timeOfDay();
305 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
306 printf("Run Time: real %.3f user %f sys %f\n",
307 (ftWallEnd
- ftWallBegin
)*0.001,
308 timeDiff(&ftUserBegin
, &ftUserEnd
),
309 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
313 #define BEGIN_TIMER beginTimer()
314 #define END_TIMER endTimer()
315 #define HAS_TIMER hasTimer()
324 ** Used to prevent warnings about unused parameters
326 #define UNUSED_PARAMETER(x) (void)(x)
329 ** If the following flag is set, then command execution stops
330 ** at an error if we are not interactive.
332 static int bail_on_error
= 0;
335 ** Threat stdin as an interactive input if the following variable
336 ** is true. Otherwise, assume stdin is connected to a file or pipe.
338 static int stdin_is_interactive
= 1;
341 ** On Windows systems we have to know if standard output is a console
342 ** in order to translate UTF-8 into MBCS. The following variable is
343 ** true if translation is required.
345 static int stdout_is_console
= 1;
348 ** The following is the open SQLite database. We make a pointer
349 ** to this database a static variable so that it can be accessed
350 ** by the SIGINT handler to interrupt database processing.
352 static sqlite3
*globalDb
= 0;
355 ** True if an interrupt (Control-C) has been received.
357 static volatile int seenInterrupt
= 0;
360 ** This is the name of our program. It is set in main(), used
361 ** in a number of other places, mostly for error messages.
366 ** Prompt strings. Initialized in main. Settable with
367 ** .prompt main continue
369 static char mainPrompt
[20]; /* First line prompt. default: "sqlite> "*/
370 static char continuePrompt
[20]; /* Continuation prompt. default: " ...> " */
373 ** Render output like fprintf(). Except, if the output is going to the
374 ** console and if this is running on a Windows machine, translate the
375 ** output from UTF-8 into MBCS.
377 #if defined(_WIN32) || defined(WIN32)
378 void utf8_printf(FILE *out
, const char *zFormat
, ...){
380 va_start(ap
, zFormat
);
381 if( stdout_is_console
&& (out
==stdout
|| out
==stderr
) ){
382 char *z1
= sqlite3_vmprintf(zFormat
, ap
);
383 char *z2
= sqlite3_win32_utf8_to_mbcs_v2(z1
, 0);
388 vfprintf(out
, zFormat
, ap
);
392 #elif !defined(utf8_printf)
393 # define utf8_printf fprintf
397 ** Render output like fprintf(). This should not be used on anything that
398 ** includes string formatting (e.g. "%s").
400 #if !defined(raw_printf)
401 # define raw_printf fprintf
405 ** Write I/O traces to the following stream.
407 #ifdef SQLITE_ENABLE_IOTRACE
408 static FILE *iotrace
= 0;
412 ** This routine works like printf in that its first argument is a
413 ** format string and subsequent arguments are values to be substituted
414 ** in place of % fields. The result of formatting this string
415 ** is written to iotrace.
417 #ifdef SQLITE_ENABLE_IOTRACE
418 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
421 if( iotrace
==0 ) return;
422 va_start(ap
, zFormat
);
423 z
= sqlite3_vmprintf(zFormat
, ap
);
425 utf8_printf(iotrace
, "%s", z
);
432 ** Determines if a string is a number of not.
434 static int isNumber(const char *z
, int *realnum
){
435 if( *z
=='-' || *z
=='+' ) z
++;
440 if( realnum
) *realnum
= 0;
441 while( IsDigit(*z
) ){ z
++; }
444 if( !IsDigit(*z
) ) return 0;
445 while( IsDigit(*z
) ){ z
++; }
446 if( realnum
) *realnum
= 1;
448 if( *z
=='e' || *z
=='E' ){
450 if( *z
=='+' || *z
=='-' ) z
++;
451 if( !IsDigit(*z
) ) return 0;
452 while( IsDigit(*z
) ){ z
++; }
453 if( realnum
) *realnum
= 1;
459 ** A global char* and an SQL function to access its current value
460 ** from within an SQL statement. This program used to use the
461 ** sqlite_exec_printf() API to substitue a string into an SQL statement.
462 ** The correct way to do this with sqlite3 is to use the bind API, but
463 ** since the shell is built around the callback paradigm it would be a lot
464 ** of work. Instead just use this hack, which is quite harmless.
466 static const char *zShellStatic
= 0;
467 static void shellstaticFunc(
468 sqlite3_context
*context
,
473 assert( zShellStatic
);
474 UNUSED_PARAMETER(argc
);
475 UNUSED_PARAMETER(argv
);
476 sqlite3_result_text(context
, zShellStatic
, -1, SQLITE_STATIC
);
481 ** Compute a string length that is limited to what can be stored in
482 ** lower 30 bits of a 32-bit signed integer.
484 static int strlen30(const char *z
){
486 while( *z2
){ z2
++; }
487 return 0x3fffffff & (int)(z2
- z
);
491 ** This routine reads a line of text from FILE in, stores
492 ** the text in memory obtained from malloc() and returns a pointer
493 ** to the text. NULL is returned at end of file, or if malloc()
496 ** If zLine is not NULL then it is a malloced buffer returned from
497 ** a previous call to this routine that may be reused.
499 static char *local_getline(char *zLine
, FILE *in
){
500 int nLine
= zLine
==0 ? 0 : 100;
505 nLine
= nLine
*2 + 100;
506 zLine
= realloc(zLine
, nLine
);
507 if( zLine
==0 ) return 0;
509 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
517 while( zLine
[n
] ) n
++;
518 if( n
>0 && zLine
[n
-1]=='\n' ){
520 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
525 #if defined(_WIN32) || defined(WIN32)
526 /* For interactive input on Windows systems, translate the
527 ** multi-byte characterset characters into UTF-8. */
528 if( stdin_is_interactive
&& in
==stdin
){
529 char *zTrans
= sqlite3_win32_mbcs_to_utf8_v2(zLine
, 0);
531 int nTrans
= strlen30(zTrans
)+1;
533 zLine
= realloc(zLine
, nTrans
);
535 sqlite3_free(zTrans
);
539 memcpy(zLine
, zTrans
, nTrans
);
540 sqlite3_free(zTrans
);
543 #endif /* defined(_WIN32) || defined(WIN32) */
548 ** Retrieve a single line of input text.
550 ** If in==0 then read from standard input and prompt before each line.
551 ** If isContinuation is true, then a continuation prompt is appropriate.
552 ** If isContinuation is zero, then the main prompt should be used.
554 ** If zPrior is not NULL then it is a buffer from a prior call to this
555 ** routine that can be reused.
557 ** The result is stored in space obtained from malloc() and must either
558 ** be freed by the caller or else passed back into this routine via the
559 ** zPrior argument for reuse.
561 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
565 zResult
= local_getline(zPrior
, in
);
567 zPrompt
= isContinuation
? continuePrompt
: mainPrompt
;
568 #if SHELL_USE_LOCAL_GETLINE
569 printf("%s", zPrompt
);
571 zResult
= local_getline(zPrior
, stdin
);
574 zResult
= shell_readline(zPrompt
);
575 if( zResult
&& *zResult
) shell_add_history(zResult
);
581 #if defined(SQLITE_ENABLE_SESSION)
583 ** State information for a single open session
585 typedef struct OpenSession OpenSession
;
587 char *zName
; /* Symbolic name for this session */
588 int nFilter
; /* Number of xFilter rejection GLOB patterns */
589 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
590 sqlite3_session
*p
; /* The open session */
595 ** Shell output mode information from before ".explain on",
596 ** saved so that it can be restored by ".explain off"
598 typedef struct SavedModeInfo SavedModeInfo
;
599 struct SavedModeInfo
{
600 int valid
; /* Is there legit data in here? */
601 int mode
; /* Mode prior to ".explain on" */
602 int showHeader
; /* The ".header" setting prior to ".explain on" */
603 int colWidth
[100]; /* Column widths prior to ".explain on" */
607 ** State information about the database connection is contained in an
608 ** instance of the following structure.
610 typedef struct ShellState ShellState
;
612 sqlite3
*db
; /* The database */
613 int echoOn
; /* True to echo input commands */
614 int autoExplain
; /* Automatically turn on .explain mode */
615 int autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
616 int statsOn
; /* True to display memory stats before each finalize */
617 int scanstatsOn
; /* True to display scan stats before each finalize */
618 int countChanges
; /* True to display change counts */
619 int backslashOn
; /* Resolve C-style \x escapes in SQL input text */
620 int outCount
; /* Revert to stdout when reaching zero */
621 int cnt
; /* Number of records displayed so far */
622 FILE *out
; /* Write results here */
623 FILE *traceOut
; /* Output for sqlite3_trace() */
624 int nErr
; /* Number of errors seen */
625 int mode
; /* An output mode setting */
626 int cMode
; /* temporary output mode for the current query */
627 int normalMode
; /* Output mode before ".explain on" */
628 int writableSchema
; /* True if PRAGMA writable_schema=ON */
629 int showHeader
; /* True to show column names in List or Column mode */
630 int nCheck
; /* Number of ".check" commands run */
631 unsigned shellFlgs
; /* Various flags */
632 char *zDestTable
; /* Name of destination table when MODE_Insert */
633 char zTestcase
[30]; /* Name of current test case */
634 char colSeparator
[20]; /* Column separator character for several modes */
635 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
636 int colWidth
[100]; /* Requested width of each column when in column mode*/
637 int actualWidth
[100]; /* Actual width of each column */
638 char nullValue
[20]; /* The text to print when a NULL comes back from
640 char outfile
[FILENAME_MAX
]; /* Filename for *out */
641 const char *zDbFilename
; /* name of the database file */
642 char *zFreeOnClose
; /* Filename to free when closing */
643 const char *zVfs
; /* Name of VFS to use */
644 sqlite3_stmt
*pStmt
; /* Current statement if any. */
645 FILE *pLog
; /* Write log output here */
646 int *aiIndent
; /* Array of indents used in MODE_Explain */
647 int nIndent
; /* Size of array aiIndent[] */
648 int iIndent
; /* Index of current op in aiIndent[] */
649 #if defined(SQLITE_ENABLE_SESSION)
650 int nSession
; /* Number of active sessions */
651 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
656 ** These are the allowed shellFlgs values
658 #define SHFLG_Scratch 0x00001 /* The --scratch option is used */
659 #define SHFLG_Pagecache 0x00002 /* The --pagecache option is used */
660 #define SHFLG_Lookaside 0x00004 /* Lookaside memory is used */
663 ** These are the allowed modes.
665 #define MODE_Line 0 /* One column per line. Blank line between records */
666 #define MODE_Column 1 /* One record per line in neat columns */
667 #define MODE_List 2 /* One record per line with a separator */
668 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
669 #define MODE_Html 4 /* Generate an XHTML table */
670 #define MODE_Insert 5 /* Generate SQL "insert" statements */
671 #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
672 #define MODE_Csv 7 /* Quote strings, numbers are plain */
673 #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
674 #define MODE_Ascii 9 /* Use ASCII unit and record separators (0x1F/0x1E) */
675 #define MODE_Pretty 10 /* Pretty-print schemas */
677 static const char *modeDescr
[] = {
692 ** These are the column/row/line separators used by the various
693 ** import/export modes.
695 #define SEP_Column "|"
698 #define SEP_Space " "
699 #define SEP_Comma ","
700 #define SEP_CrLf "\r\n"
701 #define SEP_Unit "\x1F"
702 #define SEP_Record "\x1E"
705 ** Number of elements in an array
707 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
710 ** A callback for the sqlite3_log() interface.
712 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
713 ShellState
*p
= (ShellState
*)pArg
;
714 if( p
->pLog
==0 ) return;
715 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
720 ** Output the given string as a hex-encoded blob (eg. X'1234' )
722 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
724 char *zBlob
= (char *)pBlob
;
725 raw_printf(out
,"X'");
726 for(i
=0; i
<nBlob
; i
++){ raw_printf(out
,"%02x",zBlob
[i
]&0xff); }
731 ** Output the given string as a quoted string using SQL quoting conventions.
733 static void output_quoted_string(FILE *out
, const char *z
){
736 setBinaryMode(out
, 1);
738 if( z
[i
]=='\'' ) nSingle
++;
741 utf8_printf(out
,"'%s'",z
);
745 for(i
=0; z
[i
] && z
[i
]!='\''; i
++){}
747 raw_printf(out
,"''");
749 }else if( z
[i
]=='\'' ){
750 utf8_printf(out
,"%.*s''",i
,z
);
753 utf8_printf(out
,"%s",z
);
763 ** Output the given string as a quoted according to C or TCL quoting rules.
765 static void output_c_string(FILE *out
, const char *z
){
768 while( (c
= *(z
++))!=0 ){
784 }else if( !isprint(c
&0xff) ){
785 raw_printf(out
, "\\%03o", c
&0xff);
794 ** Output the given string with characters that are special to
797 static void output_html_string(FILE *out
, const char *z
){
809 utf8_printf(out
,"%.*s",i
,z
);
812 raw_printf(out
,"<");
813 }else if( z
[i
]=='&' ){
814 raw_printf(out
,"&");
815 }else if( z
[i
]=='>' ){
816 raw_printf(out
,">");
817 }else if( z
[i
]=='\"' ){
818 raw_printf(out
,""");
819 }else if( z
[i
]=='\'' ){
820 raw_printf(out
,"'");
829 ** If a field contains any character identified by a 1 in the following
830 ** array, then the string must be quoted for CSV.
832 static const char needCsvQuote
[] = {
833 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
834 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
835 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
836 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
837 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
838 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
839 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
840 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
841 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
842 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
843 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
844 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
845 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
846 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
847 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
848 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
852 ** Output a single term of CSV. Actually, p->colSeparator is used for
853 ** the separator, which may or may not be a comma. p->nullValue is
854 ** the null value. Strings are quoted if necessary. The separator
855 ** is only issued if bSep is true.
857 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
860 utf8_printf(out
,"%s",p
->nullValue
);
863 int nSep
= strlen30(p
->colSeparator
);
865 if( needCsvQuote
[((unsigned char*)z
)[i
]]
866 || (z
[i
]==p
->colSeparator
[0] &&
867 (nSep
==1 || memcmp(z
, p
->colSeparator
, nSep
)==0)) ){
875 if( z
[i
]=='"' ) putc('"', out
);
880 utf8_printf(out
, "%s", z
);
884 utf8_printf(p
->out
, "%s", p
->colSeparator
);
890 ** This routine runs when the user presses Ctrl-C
892 static void interrupt_handler(int NotUsed
){
893 UNUSED_PARAMETER(NotUsed
);
895 if( seenInterrupt
>2 ) exit(1);
896 if( globalDb
) sqlite3_interrupt(globalDb
);
900 #ifndef SQLITE_OMIT_AUTHORIZATION
902 ** When the ".auth ON" is set, the following authorizer callback is
903 ** invoked. It always returns SQLITE_OK.
905 static int shellAuth(
913 ShellState
*p
= (ShellState
*)pClientData
;
914 static const char *azAction
[] = { 0,
915 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
916 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
917 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
918 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
919 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
920 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
921 "PRAGMA", "READ", "SELECT",
922 "TRANSACTION", "UPDATE", "ATTACH",
923 "DETACH", "ALTER_TABLE", "REINDEX",
924 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
925 "FUNCTION", "SAVEPOINT", "RECURSIVE"
933 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
935 raw_printf(p
->out
, " ");
937 output_c_string(p
->out
, az
[i
]);
939 raw_printf(p
->out
, "NULL");
942 raw_printf(p
->out
, "\n");
949 ** This is the callback routine that the shell
950 ** invokes for each row of a query result.
952 static int shell_callback(
954 int nArg
, /* Number of result columns */
955 char **azArg
, /* Text of each result column */
956 char **azCol
, /* Column names */
957 int *aiType
/* Column types */
960 ShellState
*p
= (ShellState
*)pArg
;
965 if( azArg
==0 ) break;
966 for(i
=0; i
<nArg
; i
++){
967 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
970 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
971 for(i
=0; i
<nArg
; i
++){
972 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
973 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
979 static const int aExplainWidths
[] = {4, 13, 4, 4, 4, 13, 2, 13};
983 if( p
->cMode
==MODE_Column
){
984 colWidth
= p
->colWidth
;
985 showHdr
= p
->showHeader
;
986 rowSep
= p
->rowSeparator
;
988 colWidth
= aExplainWidths
;
993 for(i
=0; i
<nArg
; i
++){
995 if( i
<ArraySize(p
->colWidth
) ){
1001 w
= strlen30(azCol
[i
] ? azCol
[i
] : "");
1003 n
= strlen30(azArg
&& azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1006 if( i
<ArraySize(p
->actualWidth
) ){
1007 p
->actualWidth
[i
] = w
;
1011 utf8_printf(p
->out
,"%*.*s%s",-w
,-w
,azCol
[i
],
1012 i
==nArg
-1 ? rowSep
: " ");
1014 utf8_printf(p
->out
,"%-*.*s%s",w
,w
,azCol
[i
],
1015 i
==nArg
-1 ? rowSep
: " ");
1020 for(i
=0; i
<nArg
; i
++){
1022 if( i
<ArraySize(p
->actualWidth
) ){
1023 w
= p
->actualWidth
[i
];
1028 utf8_printf(p
->out
,"%-*.*s%s",w
,w
,
1029 "----------------------------------------------------------"
1030 "----------------------------------------------------------",
1031 i
==nArg
-1 ? rowSep
: " ");
1035 if( azArg
==0 ) break;
1036 for(i
=0; i
<nArg
; i
++){
1038 if( i
<ArraySize(p
->actualWidth
) ){
1039 w
= p
->actualWidth
[i
];
1043 if( p
->cMode
==MODE_Explain
&& azArg
[i
] && strlen30(azArg
[i
])>w
){
1044 w
= strlen30(azArg
[i
]);
1046 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
1047 if( p
->iIndent
<p
->nIndent
){
1048 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
1053 utf8_printf(p
->out
,"%*.*s%s",-w
,-w
,
1054 azArg
[i
] ? azArg
[i
] : p
->nullValue
,
1055 i
==nArg
-1 ? rowSep
: " ");
1057 utf8_printf(p
->out
,"%-*.*s%s",w
,w
,
1058 azArg
[i
] ? azArg
[i
] : p
->nullValue
,
1059 i
==nArg
-1 ? rowSep
: " ");
1064 case MODE_Semi
: { /* .schema and .fullschema output */
1065 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
1068 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
1076 if( azArg
[0]==0 ) break;
1077 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
1078 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
1080 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
1083 z
= sqlite3_mprintf("%s", azArg
[0]);
1085 for(i
=0; IsSpace(z
[i
]); i
++){}
1086 for(; (c
= z
[i
])!=0; i
++){
1088 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
1089 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
1094 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
1096 if( strlen30(z
)>=79 ){
1097 for(i
=j
=0; (c
= z
[i
])!=0; i
++){
1100 }else if( c
=='"' || c
=='\'' || c
=='`' ){
1108 if( nLine
>0 && nParen
==0 && j
>0 ){
1109 utf8_printf(p
->out
, "%.*s\n", j
, z
);
1114 if( nParen
==1 && (c
=='(' || c
==',' || c
=='\n') ){
1116 utf8_printf(p
->out
, "%.*s\n ", j
, z
);
1119 while( IsSpace(z
[i
+1]) ){ i
++; }
1124 utf8_printf(p
->out
, "%s;\n", z
);
1129 if( p
->cnt
++==0 && p
->showHeader
){
1130 for(i
=0; i
<nArg
; i
++){
1131 utf8_printf(p
->out
,"%s%s",azCol
[i
],
1132 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
1135 if( azArg
==0 ) break;
1136 for(i
=0; i
<nArg
; i
++){
1138 if( z
==0 ) z
= p
->nullValue
;
1139 utf8_printf(p
->out
, "%s", z
);
1141 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1143 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1149 if( p
->cnt
++==0 && p
->showHeader
){
1150 raw_printf(p
->out
,"<TR>");
1151 for(i
=0; i
<nArg
; i
++){
1152 raw_printf(p
->out
,"<TH>");
1153 output_html_string(p
->out
, azCol
[i
]);
1154 raw_printf(p
->out
,"</TH>\n");
1156 raw_printf(p
->out
,"</TR>\n");
1158 if( azArg
==0 ) break;
1159 raw_printf(p
->out
,"<TR>");
1160 for(i
=0; i
<nArg
; i
++){
1161 raw_printf(p
->out
,"<TD>");
1162 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1163 raw_printf(p
->out
,"</TD>\n");
1165 raw_printf(p
->out
,"</TR>\n");
1169 if( p
->cnt
++==0 && p
->showHeader
){
1170 for(i
=0; i
<nArg
; i
++){
1171 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
1172 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1174 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1176 if( azArg
==0 ) break;
1177 for(i
=0; i
<nArg
; i
++){
1178 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1179 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1181 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1185 setBinaryMode(p
->out
, 1);
1186 if( p
->cnt
++==0 && p
->showHeader
){
1187 for(i
=0; i
<nArg
; i
++){
1188 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
1190 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1193 for(i
=0; i
<nArg
; i
++){
1194 output_csv(p
, azArg
[i
], i
<nArg
-1);
1196 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1198 setTextMode(p
->out
, 1);
1203 if( azArg
==0 ) break;
1204 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
1205 if( p
->showHeader
){
1206 raw_printf(p
->out
,"(");
1207 for(i
=0; i
<nArg
; i
++){
1208 char *zSep
= i
>0 ? ",": "";
1209 utf8_printf(p
->out
, "%s%s", zSep
, azCol
[i
]);
1211 raw_printf(p
->out
,")");
1213 raw_printf(p
->out
," VALUES(");
1214 for(i
=0; i
<nArg
; i
++){
1215 char *zSep
= i
>0 ? ",": "";
1216 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
1217 utf8_printf(p
->out
,"%sNULL",zSep
);
1218 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
1219 if( zSep
[0] ) utf8_printf(p
->out
,"%s",zSep
);
1220 output_quoted_string(p
->out
, azArg
[i
]);
1221 }else if( aiType
&& (aiType
[i
]==SQLITE_INTEGER
1222 || aiType
[i
]==SQLITE_FLOAT
) ){
1223 utf8_printf(p
->out
,"%s%s",zSep
, azArg
[i
]);
1224 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
1225 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
1226 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
1227 if( zSep
[0] ) utf8_printf(p
->out
,"%s",zSep
);
1228 output_hex_blob(p
->out
, pBlob
, nBlob
);
1229 }else if( isNumber(azArg
[i
], 0) ){
1230 utf8_printf(p
->out
,"%s%s",zSep
, azArg
[i
]);
1232 if( zSep
[0] ) utf8_printf(p
->out
,"%s",zSep
);
1233 output_quoted_string(p
->out
, azArg
[i
]);
1236 raw_printf(p
->out
,");\n");
1240 if( p
->cnt
++==0 && p
->showHeader
){
1241 for(i
=0; i
<nArg
; i
++){
1242 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1243 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
1245 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1247 if( azArg
==0 ) break;
1248 for(i
=0; i
<nArg
; i
++){
1249 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
1250 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1252 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1260 ** This is the callback routine that the SQLite library
1261 ** invokes for each row of a query result.
1263 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
1264 /* since we don't have type info, call the shell_callback with a NULL value */
1265 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
1269 ** Set the destination table field of the ShellState structure to
1270 ** the name of the table given. Escape any quote characters in the
1273 static void set_table_name(ShellState
*p
, const char *zName
){
1278 if( p
->zDestTable
){
1279 free(p
->zDestTable
);
1282 if( zName
==0 ) return;
1283 needQuote
= !isalpha((unsigned char)*zName
) && *zName
!='_';
1284 for(i
=n
=0; zName
[i
]; i
++, n
++){
1285 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ){
1287 if( zName
[i
]=='\'' ) n
++;
1290 if( needQuote
) n
+= 2;
1291 z
= p
->zDestTable
= malloc( n
+1 );
1293 raw_printf(stderr
,"Error: out of memory\n");
1297 if( needQuote
) z
[n
++] = '\'';
1298 for(i
=0; zName
[i
]; i
++){
1300 if( zName
[i
]=='\'' ) z
[n
++] = '\'';
1302 if( needQuote
) z
[n
++] = '\'';
1306 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1307 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1308 ** added to zIn, and the result returned in memory obtained from malloc().
1309 ** zIn, if it was not NULL, is freed.
1311 ** If the third argument, quote, is not '\0', then it is used as a
1312 ** quote character for zAppend.
1314 static char *appendText(char *zIn
, char const *zAppend
, char quote
){
1317 int nAppend
= strlen30(zAppend
);
1318 int nIn
= (zIn
?strlen30(zIn
):0);
1320 len
= nAppend
+nIn
+1;
1323 for(i
=0; i
<nAppend
; i
++){
1324 if( zAppend
[i
]==quote
) len
++;
1328 zIn
= (char *)realloc(zIn
, len
);
1334 char *zCsr
= &zIn
[nIn
];
1336 for(i
=0; i
<nAppend
; i
++){
1337 *zCsr
++ = zAppend
[i
];
1338 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
1342 assert( (zCsr
-zIn
)==len
);
1344 memcpy(&zIn
[nIn
], zAppend
, nAppend
);
1353 ** Execute a query statement that will generate SQL output. Print
1354 ** the result columns, comma-separated, on a line and then add a
1355 ** semicolon terminator to the end of that line.
1357 ** If the number of columns is 1 and that column contains text "--"
1358 ** then write the semicolon on a separate line. That way, if a
1359 ** "--" comment occurs at the end of the statement, the comment
1360 ** won't consume the semicolon terminator.
1362 static int run_table_dump_query(
1363 ShellState
*p
, /* Query context */
1364 const char *zSelect
, /* SELECT statement to extract content */
1365 const char *zFirstRow
/* Print before first row, if not NULL */
1367 sqlite3_stmt
*pSelect
;
1372 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
1373 if( rc
!=SQLITE_OK
|| !pSelect
){
1374 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
1375 sqlite3_errmsg(p
->db
));
1376 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
1379 rc
= sqlite3_step(pSelect
);
1380 nResult
= sqlite3_column_count(pSelect
);
1381 while( rc
==SQLITE_ROW
){
1383 utf8_printf(p
->out
, "%s", zFirstRow
);
1386 z
= (const char*)sqlite3_column_text(pSelect
, 0);
1387 utf8_printf(p
->out
, "%s", z
);
1388 for(i
=1; i
<nResult
; i
++){
1389 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
1392 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
1394 raw_printf(p
->out
, "\n;\n");
1396 raw_printf(p
->out
, ";\n");
1398 rc
= sqlite3_step(pSelect
);
1400 rc
= sqlite3_finalize(pSelect
);
1401 if( rc
!=SQLITE_OK
){
1402 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
1403 sqlite3_errmsg(p
->db
));
1404 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
1410 ** Allocate space and save off current error string.
1412 static char *save_err_msg(
1413 sqlite3
*db
/* Database to query */
1415 int nErrMsg
= 1+strlen30(sqlite3_errmsg(db
));
1416 char *zErrMsg
= sqlite3_malloc64(nErrMsg
);
1418 memcpy(zErrMsg
, sqlite3_errmsg(db
), nErrMsg
);
1425 ** Attempt to display I/O stats on Linux using /proc/PID/io
1427 static void displayLinuxIoStats(FILE *out
){
1430 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
1431 in
= fopen(z
, "rb");
1433 while( fgets(z
, sizeof(z
), in
)!=0 ){
1434 static const struct {
1435 const char *zPattern
;
1438 { "rchar: ", "Bytes received by read():" },
1439 { "wchar: ", "Bytes sent to write():" },
1440 { "syscr: ", "Read() system calls:" },
1441 { "syscw: ", "Write() system calls:" },
1442 { "read_bytes: ", "Bytes read from storage:" },
1443 { "write_bytes: ", "Bytes written to storage:" },
1444 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
1447 for(i
=0; i
<ArraySize(aTrans
); i
++){
1448 int n
= (int)strlen(aTrans
[i
].zPattern
);
1449 if( strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
1450 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
1461 ** Display memory stats.
1463 static int display_stats(
1464 sqlite3
*db
, /* Database to query */
1465 ShellState
*pArg
, /* Pointer to ShellState */
1466 int bReset
/* True to reset the stats */
1471 if( pArg
&& pArg
->out
){
1474 sqlite3_status(SQLITE_STATUS_MEMORY_USED
, &iCur
, &iHiwtr
, bReset
);
1475 raw_printf(pArg
->out
,
1476 "Memory Used: %d (max %d) bytes\n",
1479 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT
, &iCur
, &iHiwtr
, bReset
);
1480 raw_printf(pArg
->out
, "Number of Outstanding Allocations: %d (max %d)\n",
1482 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
1484 sqlite3_status(SQLITE_STATUS_PAGECACHE_USED
, &iCur
, &iHiwtr
, bReset
);
1485 raw_printf(pArg
->out
,
1486 "Number of Pcache Pages Used: %d (max %d) pages\n",
1490 sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW
, &iCur
, &iHiwtr
, bReset
);
1491 raw_printf(pArg
->out
,
1492 "Number of Pcache Overflow Bytes: %d (max %d) bytes\n",
1494 if( pArg
->shellFlgs
& SHFLG_Scratch
){
1496 sqlite3_status(SQLITE_STATUS_SCRATCH_USED
, &iCur
, &iHiwtr
, bReset
);
1497 raw_printf(pArg
->out
,
1498 "Number of Scratch Allocations Used: %d (max %d)\n",
1502 sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW
, &iCur
, &iHiwtr
, bReset
);
1503 raw_printf(pArg
->out
,
1504 "Number of Scratch Overflow Bytes: %d (max %d) bytes\n",
1507 sqlite3_status(SQLITE_STATUS_MALLOC_SIZE
, &iCur
, &iHiwtr
, bReset
);
1508 raw_printf(pArg
->out
, "Largest Allocation: %d bytes\n",
1511 sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE
, &iCur
, &iHiwtr
, bReset
);
1512 raw_printf(pArg
->out
, "Largest Pcache Allocation: %d bytes\n",
1515 sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE
, &iCur
, &iHiwtr
, bReset
);
1516 raw_printf(pArg
->out
, "Largest Scratch Allocation: %d bytes\n",
1518 #ifdef YYTRACKMAXSTACKDEPTH
1520 sqlite3_status(SQLITE_STATUS_PARSER_STACK
, &iCur
, &iHiwtr
, bReset
);
1521 raw_printf(pArg
->out
, "Deepest Parser Stack: %d (max %d)\n",
1526 if( pArg
&& pArg
->out
&& db
){
1527 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
1529 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
1530 &iCur
, &iHiwtr
, bReset
);
1531 raw_printf(pArg
->out
,
1532 "Lookaside Slots Used: %d (max %d)\n",
1534 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
1535 &iCur
, &iHiwtr
, bReset
);
1536 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
1538 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
1539 &iCur
, &iHiwtr
, bReset
);
1540 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
1542 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
1543 &iCur
, &iHiwtr
, bReset
);
1544 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
1548 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
1549 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
1552 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
1553 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
1555 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
1556 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
1558 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
1559 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
1561 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
1562 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
1565 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
1566 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
1570 if( pArg
&& pArg
->out
&& db
&& pArg
->pStmt
){
1571 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
1573 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
1574 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
1575 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
1576 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
1577 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
1578 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
1579 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
1583 displayLinuxIoStats(pArg
->out
);
1586 /* Do not remove this machine readable comment: extra-stats-output-here */
1592 ** Display scan stats.
1594 static void display_scanstats(
1595 sqlite3
*db
, /* Database to query */
1596 ShellState
*pArg
/* Pointer to ShellState */
1598 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
1599 UNUSED_PARAMETER(db
);
1600 UNUSED_PARAMETER(pArg
);
1603 raw_printf(pArg
->out
, "-------- scanstats --------\n");
1605 for(k
=0; k
<=mx
; k
++){
1606 double rEstLoop
= 1.0;
1608 sqlite3_stmt
*p
= pArg
->pStmt
;
1609 sqlite3_int64 nLoop
, nVisit
;
1612 const char *zExplain
;
1613 if( sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NLOOP
, (void*)&nLoop
) ){
1616 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_SELECTID
, (void*)&iSid
);
1617 if( iSid
>mx
) mx
= iSid
;
1618 if( iSid
!=k
) continue;
1620 rEstLoop
= (double)nLoop
;
1621 if( k
>0 ) raw_printf(pArg
->out
, "-------- subquery %d -------\n", k
);
1624 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NVISIT
, (void*)&nVisit
);
1625 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EST
, (void*)&rEst
);
1626 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EXPLAIN
, (void*)&zExplain
);
1627 utf8_printf(pArg
->out
, "Loop %2d: %s\n", n
, zExplain
);
1629 raw_printf(pArg
->out
,
1630 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
1631 nLoop
, nVisit
, (sqlite3_int64
)(rEstLoop
+0.5), rEst
1635 raw_printf(pArg
->out
, "---------------------------\n");
1640 ** Parameter azArray points to a zero-terminated array of strings. zStr
1641 ** points to a single nul-terminated string. Return non-zero if zStr
1642 ** is equal, according to strcmp(), to any of the strings in the array.
1643 ** Otherwise, return zero.
1645 static int str_in_array(const char *zStr
, const char **azArray
){
1647 for(i
=0; azArray
[i
]; i
++){
1648 if( 0==strcmp(zStr
, azArray
[i
]) ) return 1;
1654 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
1655 ** and populate the ShellState.aiIndent[] array with the number of
1656 ** spaces each opcode should be indented before it is output.
1658 ** The indenting rules are:
1660 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
1661 ** all opcodes that occur between the p2 jump destination and the opcode
1662 ** itself by 2 spaces.
1664 ** * For each "Goto", if the jump destination is earlier in the program
1665 ** and ends on one of:
1666 ** Yield SeekGt SeekLt RowSetRead Rewind
1667 ** or if the P1 parameter is one instead of zero,
1668 ** then indent all opcodes between the earlier instruction
1669 ** and "Goto" by 2 spaces.
1671 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
1672 const char *zSql
; /* The text of the SQL statement */
1673 const char *z
; /* Used to check if this is an EXPLAIN */
1674 int *abYield
= 0; /* True if op is an OP_Yield */
1675 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
1676 int iOp
; /* Index of operation in p->aiIndent[] */
1678 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
1679 "NextIfOpen", "PrevIfOpen", 0 };
1680 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
1682 const char *azGoto
[] = { "Goto", 0 };
1684 /* Try to figure out if this is really an EXPLAIN statement. If this
1685 ** cannot be verified, return early. */
1686 if( sqlite3_column_count(pSql
)!=8 ){
1690 zSql
= sqlite3_sql(pSql
);
1691 if( zSql
==0 ) return;
1692 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
1693 if( sqlite3_strnicmp(z
, "explain", 7) ){
1698 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
1700 int iAddr
= sqlite3_column_int(pSql
, 0);
1701 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
1703 /* Set p2 to the P2 field of the current opcode. Then, assuming that
1704 ** p2 is an instruction address, set variable p2op to the index of that
1705 ** instruction in the aiIndent[] array. p2 and p2op may be different if
1706 ** the current instruction is part of a sub-program generated by an
1707 ** SQL trigger or foreign key. */
1708 int p2
= sqlite3_column_int(pSql
, 3);
1709 int p2op
= (p2
+ (iOp
-iAddr
));
1711 /* Grow the p->aiIndent array as required */
1714 /* Do further verfication that this is explain output. Abort if
1716 static const char *explainCols
[] = {
1717 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
1719 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
1720 if( strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
1722 sqlite3_reset(pSql
);
1728 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
1729 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
1731 abYield
[iOp
] = str_in_array(zOp
, azYield
);
1732 p
->aiIndent
[iOp
] = 0;
1735 if( str_in_array(zOp
, azNext
) ){
1736 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
1738 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
1739 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
1741 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
1746 sqlite3_free(abYield
);
1747 sqlite3_reset(pSql
);
1751 ** Free the array allocated by explain_data_prepare().
1753 static void explain_data_delete(ShellState
*p
){
1754 sqlite3_free(p
->aiIndent
);
1761 ** Disable and restore .wheretrace and .selecttrace settings.
1763 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
1764 extern int sqlite3SelectTrace
;
1765 static int savedSelectTrace
;
1767 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
1768 extern int sqlite3WhereTrace
;
1769 static int savedWhereTrace
;
1771 static void disable_debug_trace_modes(void){
1772 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
1773 savedSelectTrace
= sqlite3SelectTrace
;
1774 sqlite3SelectTrace
= 0;
1776 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
1777 savedWhereTrace
= sqlite3WhereTrace
;
1778 sqlite3WhereTrace
= 0;
1781 static void restore_debug_trace_modes(void){
1782 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
1783 sqlite3SelectTrace
= savedSelectTrace
;
1785 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
1786 sqlite3WhereTrace
= savedWhereTrace
;
1791 ** Run a prepared statement
1793 static void exec_prepared_stmt(
1794 ShellState
*pArg
, /* Pointer to ShellState */
1795 sqlite3_stmt
*pStmt
, /* Statment to run */
1796 int (*xCallback
)(void*,int,char**,char**,int*) /* Callback function */
1800 /* perform the first step. this will tell us if we
1801 ** have a result set or not and how wide it is.
1803 rc
= sqlite3_step(pStmt
);
1804 /* if we have a result set... */
1805 if( SQLITE_ROW
== rc
){
1806 /* if we have a callback... */
1808 /* allocate space for col name ptr, value ptr, and type */
1809 int nCol
= sqlite3_column_count(pStmt
);
1810 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
1814 char **azCols
= (char **)pData
; /* Names of result columns */
1815 char **azVals
= &azCols
[nCol
]; /* Results */
1816 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
1818 assert(sizeof(int) <= sizeof(char *));
1819 /* save off ptrs to column names */
1820 for(i
=0; i
<nCol
; i
++){
1821 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
1824 /* extract the data and data types */
1825 for(i
=0; i
<nCol
; i
++){
1826 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
1827 if( x
==SQLITE_BLOB
&& pArg
&& pArg
->cMode
==MODE_Insert
){
1830 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
1832 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
1834 break; /* from for */
1838 /* if data and types extracted successfully... */
1839 if( SQLITE_ROW
== rc
){
1840 /* call the supplied callback with the result row data */
1841 if( xCallback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
1844 rc
= sqlite3_step(pStmt
);
1847 } while( SQLITE_ROW
== rc
);
1848 sqlite3_free(pData
);
1852 rc
= sqlite3_step(pStmt
);
1853 } while( rc
== SQLITE_ROW
);
1859 ** Execute a statement or set of statements. Print
1860 ** any result rows/columns depending on the current mode
1861 ** set via the supplied callback.
1863 ** This is very similar to SQLite's built-in sqlite3_exec()
1864 ** function except it takes a slightly different callback
1865 ** and callback data argument.
1867 static int shell_exec(
1868 sqlite3
*db
, /* An open database */
1869 const char *zSql
, /* SQL to be evaluated */
1870 int (*xCallback
)(void*,int,char**,char**,int*), /* Callback function */
1871 /* (not the same as sqlite3_exec) */
1872 ShellState
*pArg
, /* Pointer to ShellState */
1873 char **pzErrMsg
/* Error msg written here */
1875 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
1876 int rc
= SQLITE_OK
; /* Return Code */
1878 const char *zLeftover
; /* Tail of unprocessed SQL */
1884 while( zSql
[0] && (SQLITE_OK
== rc
) ){
1885 static const char *zStmtSql
;
1886 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
1887 if( SQLITE_OK
!= rc
){
1889 *pzErrMsg
= save_err_msg(db
);
1893 /* this happens for a comment or white-space */
1895 while( IsSpace(zSql
[0]) ) zSql
++;
1898 zStmtSql
= sqlite3_sql(pStmt
);
1899 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
1901 /* save off the prepared statment handle and reset row count */
1903 pArg
->pStmt
= pStmt
;
1907 /* echo the sql statement if echo on */
1908 if( pArg
&& pArg
->echoOn
){
1909 utf8_printf(pArg
->out
, "%s\n", zStmtSql
? zStmtSql
: zSql
);
1912 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
1913 if( pArg
&& pArg
->autoEQP
&& sqlite3_strlike("EXPLAIN%",zStmtSql
,0)!=0 ){
1914 sqlite3_stmt
*pExplain
;
1916 disable_debug_trace_modes();
1917 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
1918 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
1919 if( rc
==SQLITE_OK
){
1920 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
1921 raw_printf(pArg
->out
,"--EQP-- %d,",sqlite3_column_int(pExplain
, 0));
1922 raw_printf(pArg
->out
,"%d,", sqlite3_column_int(pExplain
, 1));
1923 raw_printf(pArg
->out
,"%d,", sqlite3_column_int(pExplain
, 2));
1924 utf8_printf(pArg
->out
,"%s\n", sqlite3_column_text(pExplain
, 3));
1927 sqlite3_finalize(pExplain
);
1929 if( pArg
->autoEQP
>=2 ){
1930 /* Also do an EXPLAIN for ".eqp full" mode */
1931 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
1932 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
1933 if( rc
==SQLITE_OK
){
1934 pArg
->cMode
= MODE_Explain
;
1935 explain_data_prepare(pArg
, pExplain
);
1936 exec_prepared_stmt(pArg
, pExplain
, xCallback
);
1937 explain_data_delete(pArg
);
1939 sqlite3_finalize(pExplain
);
1942 restore_debug_trace_modes();
1946 pArg
->cMode
= pArg
->mode
;
1947 if( pArg
->autoExplain
1948 && sqlite3_column_count(pStmt
)==8
1949 && sqlite3_strlike("EXPLAIN%", zStmtSql
,0)==0
1951 pArg
->cMode
= MODE_Explain
;
1954 /* If the shell is currently in ".explain" mode, gather the extra
1955 ** data required to add indents to the output.*/
1956 if( pArg
->cMode
==MODE_Explain
){
1957 explain_data_prepare(pArg
, pStmt
);
1961 exec_prepared_stmt(pArg
, pStmt
, xCallback
);
1962 explain_data_delete(pArg
);
1964 /* print usage stats if stats on */
1965 if( pArg
&& pArg
->statsOn
){
1966 display_stats(db
, pArg
, 0);
1969 /* print loop-counters if required */
1970 if( pArg
&& pArg
->scanstatsOn
){
1971 display_scanstats(db
, pArg
);
1974 /* Finalize the statement just executed. If this fails, save a
1975 ** copy of the error message. Otherwise, set zSql to point to the
1976 ** next statement to execute. */
1977 rc2
= sqlite3_finalize(pStmt
);
1978 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
1979 if( rc
==SQLITE_OK
){
1981 while( IsSpace(zSql
[0]) ) zSql
++;
1982 }else if( pzErrMsg
){
1983 *pzErrMsg
= save_err_msg(db
);
1986 /* clear saved stmt handle */
1998 ** This is a different callback routine used for dumping the database.
1999 ** Each row received by this callback consists of a table name,
2000 ** the table type ("index" or "table") and SQL to create the table.
2001 ** This routine should print text sufficient to recreate the table.
2003 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
2008 const char *zPrepStmt
= 0;
2009 ShellState
*p
= (ShellState
*)pArg
;
2011 UNUSED_PARAMETER(azCol
);
2012 if( nArg
!=3 ) return 1;
2017 if( strcmp(zTable
, "sqlite_sequence")==0 ){
2018 zPrepStmt
= "DELETE FROM sqlite_sequence;\n";
2019 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 ){
2020 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
2021 }else if( strncmp(zTable
, "sqlite_", 7)==0 ){
2023 }else if( strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
2025 if( !p
->writableSchema
){
2026 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
2027 p
->writableSchema
= 1;
2029 zIns
= sqlite3_mprintf(
2030 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2031 "VALUES('table','%q','%q',0,'%q');",
2032 zTable
, zTable
, zSql
);
2033 utf8_printf(p
->out
, "%s\n", zIns
);
2037 utf8_printf(p
->out
, "%s;\n", zSql
);
2040 if( strcmp(zType
, "table")==0 ){
2041 sqlite3_stmt
*pTableInfo
= 0;
2043 char *zTableInfo
= 0;
2047 zTableInfo
= appendText(zTableInfo
, "PRAGMA table_info(", 0);
2048 zTableInfo
= appendText(zTableInfo
, zTable
, '"');
2049 zTableInfo
= appendText(zTableInfo
, ");", 0);
2051 rc
= sqlite3_prepare_v2(p
->db
, zTableInfo
, -1, &pTableInfo
, 0);
2053 if( rc
!=SQLITE_OK
|| !pTableInfo
){
2057 zSelect
= appendText(zSelect
, "SELECT 'INSERT INTO ' || ", 0);
2058 /* Always quote the table name, even if it appears to be pure ascii,
2059 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2060 zTmp
= appendText(zTmp
, zTable
, '"');
2062 zSelect
= appendText(zSelect
, zTmp
, '\'');
2065 zSelect
= appendText(zSelect
, " || ' VALUES(' || ", 0);
2066 rc
= sqlite3_step(pTableInfo
);
2067 while( rc
==SQLITE_ROW
){
2068 const char *zText
= (const char *)sqlite3_column_text(pTableInfo
, 1);
2069 zSelect
= appendText(zSelect
, "quote(", 0);
2070 zSelect
= appendText(zSelect
, zText
, '"');
2071 rc
= sqlite3_step(pTableInfo
);
2072 if( rc
==SQLITE_ROW
){
2073 zSelect
= appendText(zSelect
, "), ", 0);
2075 zSelect
= appendText(zSelect
, ") ", 0);
2079 rc
= sqlite3_finalize(pTableInfo
);
2080 if( rc
!=SQLITE_OK
|| nRow
==0 ){
2084 zSelect
= appendText(zSelect
, "|| ')' FROM ", 0);
2085 zSelect
= appendText(zSelect
, zTable
, '"');
2087 rc
= run_table_dump_query(p
, zSelect
, zPrepStmt
);
2088 if( rc
==SQLITE_CORRUPT
){
2089 zSelect
= appendText(zSelect
, " ORDER BY rowid DESC", 0);
2090 run_table_dump_query(p
, zSelect
, 0);
2098 ** Run zQuery. Use dump_callback() as the callback routine so that
2099 ** the contents of the query are output as SQL statements.
2101 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
2102 ** "ORDER BY rowid DESC" to the end.
2104 static int run_schema_dump_query(
2110 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
2111 if( rc
==SQLITE_CORRUPT
){
2113 int len
= strlen30(zQuery
);
2114 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
2116 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
2120 zQ2
= malloc( len
+100 );
2121 if( zQ2
==0 ) return rc
;
2122 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
2123 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
2125 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
2127 rc
= SQLITE_CORRUPT
;
2136 ** Text of a help message
2138 static char zHelp
[] =
2139 #ifndef SQLITE_OMIT_AUTHORIZATION
2140 ".auth ON|OFF Show authorizer callbacks\n"
2142 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
2143 ".bail on|off Stop after hitting an error. Default OFF\n"
2144 ".binary on|off Turn binary output on or off. Default OFF\n"
2145 ".changes on|off Show number of rows changed by SQL\n"
2146 ".check GLOB Fail if output since .testcase does not match\n"
2147 ".clone NEWDB Clone data into NEWDB from the existing database\n"
2148 ".databases List names and files of attached databases\n"
2149 ".dbinfo ?DB? Show status information about the database\n"
2150 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
2151 " If TABLE specified, only dump tables matching\n"
2152 " LIKE pattern TABLE.\n"
2153 ".echo on|off Turn command echo on or off\n"
2154 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
2155 ".exit Exit this program\n"
2156 ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
2157 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
2158 ".headers on|off Turn display of headers on or off\n"
2159 ".help Show this message\n"
2160 ".import FILE TABLE Import data from FILE into TABLE\n"
2161 ".indexes ?TABLE? Show names of all indexes\n"
2162 " If TABLE specified, only show indexes for tables\n"
2163 " matching LIKE pattern TABLE.\n"
2164 #ifdef SQLITE_ENABLE_IOTRACE
2165 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
2167 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
2168 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2169 ".load FILE ?ENTRY? Load an extension library\n"
2171 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
2172 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
2173 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
2174 " csv Comma-separated values\n"
2175 " column Left-aligned columns. (See .width)\n"
2176 " html HTML <table> code\n"
2177 " insert SQL insert statements for TABLE\n"
2178 " line One value per line\n"
2179 " list Values delimited by .separator strings\n"
2180 " tabs Tab-separated values\n"
2181 " tcl TCL list elements\n"
2182 ".nullvalue STRING Use STRING in place of NULL values\n"
2183 ".once FILENAME Output for the next SQL command only to FILENAME\n"
2184 ".open ?--new? ?FILE? Close existing database and reopen FILE\n"
2185 " The --new starts with an empty file\n"
2186 ".output ?FILENAME? Send output to FILENAME or stdout\n"
2187 ".print STRING... Print literal STRING\n"
2188 ".prompt MAIN CONTINUE Replace the standard prompts\n"
2189 ".quit Exit this program\n"
2190 ".read FILENAME Execute SQL in FILENAME\n"
2191 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
2192 ".save FILE Write in-memory database into FILE\n"
2193 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
2194 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
2195 " Add --indent for pretty-printing\n"
2196 ".separator COL ?ROW? Change the column separator and optionally the row\n"
2197 " separator for both the output mode and .import\n"
2198 #if defined(SQLITE_ENABLE_SESSION)
2199 ".session CMD ... Create or control sessions\n"
2201 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
2202 ".show Show the current values for various settings\n"
2203 ".stats ?on|off? Show stats or turn stats on or off\n"
2204 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
2205 ".tables ?TABLE? List names of tables\n"
2206 " If TABLE specified, only list tables matching\n"
2207 " LIKE pattern TABLE.\n"
2208 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
2209 ".timeout MS Try opening locked tables for MS milliseconds\n"
2210 ".timer on|off Turn SQL timer on or off\n"
2211 ".trace FILE|off Output each SQL statement as it is run\n"
2212 ".vfsinfo ?AUX? Information about the top-level VFS\n"
2213 ".vfslist List all available VFSes\n"
2214 ".vfsname ?AUX? Print the name of the VFS stack\n"
2215 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
2216 " Negative values right-justify\n"
2219 #if defined(SQLITE_ENABLE_SESSION)
2221 ** Print help information for the ".sessions" command
2223 void session_help(ShellState
*p
){
2225 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
2226 "If ?NAME? is omitted, the first defined session is used.\n"
2228 " attach TABLE Attach TABLE\n"
2229 " changeset FILE Write a changeset into FILE\n"
2230 " close Close one session\n"
2231 " enable ?BOOLEAN? Set or query the enable bit\n"
2232 " filter GLOB... Reject tables matching GLOBs\n"
2233 " indirect ?BOOLEAN? Mark or query the indirect status\n"
2234 " isempty Query whether the session is empty\n"
2235 " list List currently open session names\n"
2236 " open DB NAME Open a new session on DB\n"
2237 " patchset FILE Write a patchset into FILE\n"
2243 /* Forward reference */
2244 static int process_input(ShellState
*p
, FILE *in
);
2248 ** Read the content of a file into memory obtained from sqlite3_malloc64().
2249 ** The caller is responsible for freeing the memory.
2251 ** NULL is returned if any error is encountered.
2253 static char *readFile(const char *zName
){
2254 FILE *in
= fopen(zName
, "rb");
2258 if( in
==0 ) return 0;
2259 fseek(in
, 0, SEEK_END
);
2262 pBuf
= sqlite3_malloc64( nIn
+1 );
2263 if( pBuf
==0 ) return 0;
2264 nRead
= fread(pBuf
, nIn
, 1, in
);
2275 ** Implementation of the "readfile(X)" SQL function. The entire content
2276 ** of the file named X is read and returned as a BLOB. NULL is returned
2277 ** if the file does not exist or is unreadable.
2279 static void readfileFunc(
2280 sqlite3_context
*context
,
2282 sqlite3_value
**argv
2287 UNUSED_PARAMETER(argc
);
2288 zName
= (const char*)sqlite3_value_text(argv
[0]);
2289 if( zName
==0 ) return;
2290 pBuf
= readFile(zName
);
2291 if( pBuf
) sqlite3_result_blob(context
, pBuf
, -1, sqlite3_free
);
2295 ** Implementation of the "writefile(X,Y)" SQL function. The argument Y
2296 ** is written into file X. The number of bytes written is returned. Or
2297 ** NULL is returned if something goes wrong, such as being unable to open
2298 ** file X for writing.
2300 static void writefileFunc(
2301 sqlite3_context
*context
,
2303 sqlite3_value
**argv
2310 UNUSED_PARAMETER(argc
);
2311 zFile
= (const char*)sqlite3_value_text(argv
[0]);
2312 if( zFile
==0 ) return;
2313 out
= fopen(zFile
, "wb");
2314 if( out
==0 ) return;
2315 z
= (const char*)sqlite3_value_blob(argv
[1]);
2319 rc
= fwrite(z
, 1, sqlite3_value_bytes(argv
[1]), out
);
2322 sqlite3_result_int64(context
, rc
);
2325 #if defined(SQLITE_ENABLE_SESSION)
2327 ** Close a single OpenSession object and release all of its associated
2330 static void session_close(OpenSession
*pSession
){
2332 sqlite3session_delete(pSession
->p
);
2333 sqlite3_free(pSession
->zName
);
2334 for(i
=0; i
<pSession
->nFilter
; i
++){
2335 sqlite3_free(pSession
->azFilter
[i
]);
2337 sqlite3_free(pSession
->azFilter
);
2338 memset(pSession
, 0, sizeof(OpenSession
));
2343 ** Close all OpenSession objects and release all associated resources.
2345 #if defined(SQLITE_ENABLE_SESSION)
2346 static void session_close_all(ShellState
*p
){
2348 for(i
=0; i
<p
->nSession
; i
++){
2349 session_close(&p
->aSession
[i
]);
2354 # define session_close_all(X)
2358 ** Implementation of the xFilter function for an open session. Omit
2359 ** any tables named by ".session filter" but let all other table through.
2361 #if defined(SQLITE_ENABLE_SESSION)
2362 static int session_filter(void *pCtx
, const char *zTab
){
2363 OpenSession
*pSession
= (OpenSession
*)pCtx
;
2365 for(i
=0; i
<pSession
->nFilter
; i
++){
2366 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
2373 ** Make sure the database is open. If it is not, then open it. If
2374 ** the database fails to open, print an error message and exit.
2376 static void open_db(ShellState
*p
, int keepAlive
){
2378 sqlite3_initialize();
2379 sqlite3_open(p
->zDbFilename
, &p
->db
);
2381 if( p
->db
&& sqlite3_errcode(p
->db
)==SQLITE_OK
){
2382 sqlite3_create_function(p
->db
, "shellstatic", 0, SQLITE_UTF8
, 0,
2383 shellstaticFunc
, 0, 0);
2385 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
2386 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
2387 p
->zDbFilename
, sqlite3_errmsg(p
->db
));
2388 if( keepAlive
) return;
2391 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2392 sqlite3_enable_load_extension(p
->db
, 1);
2394 sqlite3_create_function(p
->db
, "readfile", 1, SQLITE_UTF8
, 0,
2395 readfileFunc
, 0, 0);
2396 sqlite3_create_function(p
->db
, "writefile", 2, SQLITE_UTF8
, 0,
2397 writefileFunc
, 0, 0);
2402 ** Do C-language style dequoting.
2408 ** \v -> vertical tab
2410 ** \r -> carriage return
2415 ** \NNN -> ascii character NNN in octal
2417 static void resolve_backslashes(char *z
){
2420 while( *z
&& *z
!='\\' ) z
++;
2421 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
2422 if( c
=='\\' && z
[i
+1]!=0 ){
2440 }else if( c
=='\'' ){
2442 }else if( c
=='\\' ){
2444 }else if( c
>='0' && c
<='7' ){
2446 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
2448 c
= (c
<<3) + z
[i
] - '0';
2449 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
2451 c
= (c
<<3) + z
[i
] - '0';
2462 ** Return the value of a hexadecimal digit. Return -1 if the input
2463 ** is not a hex digit.
2465 static int hexDigitValue(char c
){
2466 if( c
>='0' && c
<='9' ) return c
- '0';
2467 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
2468 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
2473 ** Interpret zArg as an integer value, possibly with suffixes.
2475 static sqlite3_int64
integerValue(const char *zArg
){
2476 sqlite3_int64 v
= 0;
2477 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
2479 { "MiB", 1024*1024 },
2480 { "GiB", 1024*1024*1024 },
2483 { "GB", 1000000000 },
2486 { "G", 1000000000 },
2493 }else if( zArg
[0]=='+' ){
2496 if( zArg
[0]=='0' && zArg
[1]=='x' ){
2499 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
2504 while( IsDigit(zArg
[0]) ){
2505 v
= v
*10 + zArg
[0] - '0';
2509 for(i
=0; i
<ArraySize(aMult
); i
++){
2510 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
2511 v
*= aMult
[i
].iMult
;
2515 return isNeg
? -v
: v
;
2519 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
2520 ** for TRUE and FALSE. Return the integer value if appropriate.
2522 static int booleanValue(char *zArg
){
2524 if( zArg
[0]=='0' && zArg
[1]=='x' ){
2525 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
2527 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
2529 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
2530 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
2533 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
2536 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
2542 ** Close an output file, assuming it is not stderr or stdout
2544 static void output_file_close(FILE *f
){
2545 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
2549 ** Try to open an output file. The names "stdout" and "stderr" are
2550 ** recognized and do the right thing. NULL is returned if the output
2551 ** filename is "off".
2553 static FILE *output_file_open(const char *zFile
){
2555 if( strcmp(zFile
,"stdout")==0 ){
2557 }else if( strcmp(zFile
, "stderr")==0 ){
2559 }else if( strcmp(zFile
, "off")==0 ){
2562 f
= fopen(zFile
, "wb");
2564 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
2571 ** A routine for handling output from sqlite3_trace().
2573 static int sql_trace_callback(
2579 FILE *f
= (FILE*)pArg
;
2580 UNUSED_PARAMETER(mType
);
2581 UNUSED_PARAMETER(pP
);
2583 const char *z
= (const char*)pX
;
2584 int i
= (int)strlen(z
);
2585 while( i
>0 && z
[i
-1]==';' ){ i
--; }
2586 utf8_printf(f
, "%.*s;\n", i
, z
);
2592 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
2593 ** a useful spot to set a debugger breakpoint.
2595 static void test_breakpoint(void){
2596 static int nCall
= 0;
2601 ** An object used to read a CSV and other files for import.
2603 typedef struct ImportCtx ImportCtx
;
2605 const char *zFile
; /* Name of the input file */
2606 FILE *in
; /* Read the CSV text from this input stream */
2607 char *z
; /* Accumulated text for a field */
2608 int n
; /* Number of bytes in z */
2609 int nAlloc
; /* Space allocated for z[] */
2610 int nLine
; /* Current line number */
2611 int cTerm
; /* Character that terminated the most recent field */
2612 int cColSep
; /* The column separator character. (Usually ",") */
2613 int cRowSep
; /* The row separator character. (Usually "\n") */
2616 /* Append a single byte to z[] */
2617 static void import_append_char(ImportCtx
*p
, int c
){
2618 if( p
->n
+1>=p
->nAlloc
){
2619 p
->nAlloc
+= p
->nAlloc
+ 100;
2620 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
2622 raw_printf(stderr
, "out of memory\n");
2626 p
->z
[p
->n
++] = (char)c
;
2629 /* Read a single field of CSV text. Compatible with rfc4180 and extended
2630 ** with the option of having a separator other than ",".
2632 ** + Input comes from p->in.
2633 ** + Store results in p->z of length p->n. Space to hold p->z comes
2634 ** from sqlite3_malloc64().
2635 ** + Use p->cSep as the column separator. The default is ",".
2636 ** + Use p->rSep as the row separator. The default is "\n".
2637 ** + Keep track of the line number in p->nLine.
2638 ** + Store the character that terminates the field in p->cTerm. Store
2639 ** EOF on end-of-file.
2640 ** + Report syntax errors on stderr
2642 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
2644 int cSep
= p
->cColSep
;
2645 int rSep
= p
->cRowSep
;
2648 if( c
==EOF
|| seenInterrupt
){
2654 int startLine
= p
->nLine
;
2659 if( c
==rSep
) p
->nLine
++;
2666 if( (c
==cSep
&& pc
==cQuote
)
2667 || (c
==rSep
&& pc
==cQuote
)
2668 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
2669 || (c
==EOF
&& pc
==cQuote
)
2671 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
2675 if( pc
==cQuote
&& c
!='\r' ){
2676 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
2677 p
->zFile
, p
->nLine
, cQuote
);
2680 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
2681 p
->zFile
, startLine
, cQuote
);
2685 import_append_char(p
, c
);
2690 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
2691 import_append_char(p
, c
);
2696 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
2700 if( p
->z
) p
->z
[p
->n
] = 0;
2704 /* Read a single field of ASCII delimited text.
2706 ** + Input comes from p->in.
2707 ** + Store results in p->z of length p->n. Space to hold p->z comes
2708 ** from sqlite3_malloc64().
2709 ** + Use p->cSep as the column separator. The default is "\x1F".
2710 ** + Use p->rSep as the row separator. The default is "\x1E".
2711 ** + Keep track of the row number in p->nLine.
2712 ** + Store the character that terminates the field in p->cTerm. Store
2713 ** EOF on end-of-file.
2714 ** + Report syntax errors on stderr
2716 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
2718 int cSep
= p
->cColSep
;
2719 int rSep
= p
->cRowSep
;
2722 if( c
==EOF
|| seenInterrupt
){
2726 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
2727 import_append_char(p
, c
);
2734 if( p
->z
) p
->z
[p
->n
] = 0;
2739 ** Try to transfer data for table zTable. If an error is seen while
2740 ** moving forward, try to go backwards. The backwards movement won't
2741 ** work for WITHOUT ROWID tables.
2743 static void tryToCloneData(
2748 sqlite3_stmt
*pQuery
= 0;
2749 sqlite3_stmt
*pInsert
= 0;
2754 int nTable
= (int)strlen(zTable
);
2757 const int spinRate
= 10000;
2759 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
2760 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
2762 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
2763 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
2767 n
= sqlite3_column_count(pQuery
);
2768 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
2770 raw_printf(stderr
, "out of memory\n");
2773 sqlite3_snprintf(200+nTable
,zInsert
,
2774 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
2775 i
= (int)strlen(zInsert
);
2777 memcpy(zInsert
+i
, ",?", 2);
2780 memcpy(zInsert
+i
, ");", 3);
2781 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
2783 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
2784 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
2789 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
2791 switch( sqlite3_column_type(pQuery
, i
) ){
2793 sqlite3_bind_null(pInsert
, i
+1);
2796 case SQLITE_INTEGER
: {
2797 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
2800 case SQLITE_FLOAT
: {
2801 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
2805 sqlite3_bind_text(pInsert
, i
+1,
2806 (const char*)sqlite3_column_text(pQuery
,i
),
2811 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
2812 sqlite3_column_bytes(pQuery
,i
),
2818 rc
= sqlite3_step(pInsert
);
2819 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
2820 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
2821 sqlite3_errmsg(newDb
));
2823 sqlite3_reset(pInsert
);
2825 if( (cnt
%spinRate
)==0 ){
2826 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
2830 if( rc
==SQLITE_DONE
) break;
2831 sqlite3_finalize(pQuery
);
2832 sqlite3_free(zQuery
);
2833 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
2835 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
2837 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
2840 } /* End for(k=0...) */
2843 sqlite3_finalize(pQuery
);
2844 sqlite3_finalize(pInsert
);
2845 sqlite3_free(zQuery
);
2846 sqlite3_free(zInsert
);
2851 ** Try to transfer all rows of the schema that match zWhere. For
2852 ** each row, invoke xForEach() on the object defined by that row.
2853 ** If an error is encountered while moving forward through the
2854 ** sqlite_master table, try again moving backwards.
2856 static void tryToCloneSchema(
2860 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
2862 sqlite3_stmt
*pQuery
= 0;
2865 const unsigned char *zName
;
2866 const unsigned char *zSql
;
2869 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
2870 " WHERE %s", zWhere
);
2871 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
2873 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
2874 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
2876 goto end_schema_xfer
;
2878 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
2879 zName
= sqlite3_column_text(pQuery
, 0);
2880 zSql
= sqlite3_column_text(pQuery
, 1);
2881 printf("%s... ", zName
); fflush(stdout
);
2882 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
2884 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
2885 sqlite3_free(zErrMsg
);
2889 xForEach(p
, newDb
, (const char*)zName
);
2893 if( rc
!=SQLITE_DONE
){
2894 sqlite3_finalize(pQuery
);
2895 sqlite3_free(zQuery
);
2896 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
2897 " WHERE %s ORDER BY rowid DESC", zWhere
);
2898 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
2900 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
2901 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
2903 goto end_schema_xfer
;
2905 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
2906 zName
= sqlite3_column_text(pQuery
, 0);
2907 zSql
= sqlite3_column_text(pQuery
, 1);
2908 printf("%s... ", zName
); fflush(stdout
);
2909 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
2911 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
2912 sqlite3_free(zErrMsg
);
2916 xForEach(p
, newDb
, (const char*)zName
);
2922 sqlite3_finalize(pQuery
);
2923 sqlite3_free(zQuery
);
2927 ** Open a new database file named "zNewDb". Try to recover as much information
2928 ** as possible out of the main database (which might be corrupt) and write it
2931 static void tryToClone(ShellState
*p
, const char *zNewDb
){
2934 if( access(zNewDb
,0)==0 ){
2935 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
2938 rc
= sqlite3_open(zNewDb
, &newDb
);
2940 utf8_printf(stderr
, "Cannot create output database: %s\n",
2941 sqlite3_errmsg(newDb
));
2943 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
2944 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
2945 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
2946 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
2947 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
2948 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
2950 sqlite3_close(newDb
);
2954 ** Change the output file back to stdout
2956 static void output_reset(ShellState
*p
){
2957 if( p
->outfile
[0]=='|' ){
2958 #ifndef SQLITE_OMIT_POPEN
2962 output_file_close(p
->out
);
2969 ** Run an SQL command and return the single integer result.
2971 static int db_int(ShellState
*p
, const char *zSql
){
2972 sqlite3_stmt
*pStmt
;
2974 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
2975 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
2976 res
= sqlite3_column_int(pStmt
,0);
2978 sqlite3_finalize(pStmt
);
2983 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
2985 static unsigned int get2byteInt(unsigned char *a
){
2986 return (a
[0]<<8) + a
[1];
2988 static unsigned int get4byteInt(unsigned char *a
){
2989 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
2993 ** Implementation of the ".info" command.
2995 ** Return 1 on error, 2 to exit, and 0 otherwise.
2997 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
2998 static const struct { const char *zName
; int ofst
; } aField
[] = {
2999 { "file change counter:", 24 },
3000 { "database page count:", 28 },
3001 { "freelist page count:", 36 },
3002 { "schema cookie:", 40 },
3003 { "schema format:", 44 },
3004 { "default cache size:", 48 },
3005 { "autovacuum top root:", 52 },
3006 { "incremental vacuum:", 64 },
3007 { "text encoding:", 56 },
3008 { "user version:", 60 },
3009 { "application id:", 68 },
3010 { "software version:", 96 },
3012 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
3013 { "number of tables:",
3014 "SELECT count(*) FROM %s WHERE type='table'" },
3015 { "number of indexes:",
3016 "SELECT count(*) FROM %s WHERE type='index'" },
3017 { "number of triggers:",
3018 "SELECT count(*) FROM %s WHERE type='trigger'" },
3019 { "number of views:",
3020 "SELECT count(*) FROM %s WHERE type='view'" },
3022 "SELECT total(length(sql)) FROM %s" },
3024 sqlite3_file
*pFile
= 0;
3027 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
3028 unsigned char aHdr
[100];
3030 if( p
->db
==0 ) return 1;
3031 sqlite3_file_control(p
->db
, zDb
, SQLITE_FCNTL_FILE_POINTER
, &pFile
);
3032 if( pFile
==0 || pFile
->pMethods
==0 || pFile
->pMethods
->xRead
==0 ){
3035 i
= pFile
->pMethods
->xRead(pFile
, aHdr
, 100, 0);
3037 raw_printf(stderr
, "unable to read database header\n");
3040 i
= get2byteInt(aHdr
+16);
3041 if( i
==1 ) i
= 65536;
3042 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
3043 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
3044 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
3045 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
3046 for(i
=0; i
<ArraySize(aField
); i
++){
3047 int ofst
= aField
[i
].ofst
;
3048 unsigned int val
= get4byteInt(aHdr
+ ofst
);
3049 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
3052 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
3053 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
3054 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
3057 raw_printf(p
->out
, "\n");
3060 zSchemaTab
= sqlite3_mprintf("main.sqlite_master");
3061 }else if( strcmp(zDb
,"temp")==0 ){
3062 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_master");
3064 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_master", zDb
);
3066 for(i
=0; i
<ArraySize(aQuery
); i
++){
3067 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
3068 int val
= db_int(p
, zSql
);
3070 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
3072 sqlite3_free(zSchemaTab
);
3077 ** Print the current sqlite3_errmsg() value to stderr and return 1.
3079 static int shellDatabaseError(sqlite3
*db
){
3080 const char *zErr
= sqlite3_errmsg(db
);
3081 utf8_printf(stderr
, "Error: %s\n", zErr
);
3086 ** Print an out-of-memory message to stderr and return 1.
3088 static int shellNomemError(void){
3089 raw_printf(stderr
, "Error: out of memory\n");
3094 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
3095 ** if they match and FALSE (0) if they do not match.
3099 ** '*' Matches any sequence of zero or more characters.
3101 ** '?' Matches exactly one character.
3103 ** [...] Matches one character from the enclosed list of
3106 ** [^...] Matches one character not in the enclosed list.
3108 ** '#' Matches any sequence of one or more digits with an
3109 ** optional + or - sign in front
3111 ** ' ' Any span of whitespace matches any other span of
3114 ** Extra whitespace at the end of z[] is ignored.
3116 static int testcase_glob(const char *zGlob
, const char *z
){
3121 while( (c
= (*(zGlob
++)))!=0 ){
3123 if( !IsSpace(*z
) ) return 0;
3124 while( IsSpace(*zGlob
) ) zGlob
++;
3125 while( IsSpace(*z
) ) z
++;
3127 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
3128 if( c
=='?' && (*(z
++))==0 ) return 0;
3133 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
3138 while( (c2
= (*(z
++)))!=0 ){
3141 if( c2
==0 ) return 0;
3143 if( testcase_glob(zGlob
,z
) ) return 1;
3147 if( (*(z
++))==0 ) return 0;
3153 if( c
==0 ) return 0;
3160 if( c
==']' ) seen
= 1;
3163 while( c2
&& c2
!=']' ){
3164 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
3166 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
3176 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
3178 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
3179 if( !IsDigit(z
[0]) ) return 0;
3181 while( IsDigit(z
[0]) ){ z
++; }
3183 if( c
!=(*(z
++)) ) return 0;
3186 while( IsSpace(*z
) ){ z
++; }
3192 ** Compare the string as a command-line option with either one or two
3193 ** initial "-" characters.
3195 static int optionMatch(const char *zStr
, const char *zOpt
){
3196 if( zStr
[0]!='-' ) return 0;
3198 if( zStr
[0]=='-' ) zStr
++;
3199 return strcmp(zStr
, zOpt
)==0;
3205 int shellDeleteFile(const char *zFilename
){
3208 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
3212 rc
= unlink(zFilename
);
3218 ** If an input line begins with "." then invoke this routine to
3219 ** process that line.
3221 ** Return 1 on error, 2 to exit, and 0 otherwise.
3223 static int do_meta_command(char *zLine
, ShellState
*p
){
3230 /* Parse the input line into tokens.
3232 while( zLine
[h
] && nArg
<ArraySize(azArg
) ){
3233 while( IsSpace(zLine
[h
]) ){ h
++; }
3234 if( zLine
[h
]==0 ) break;
3235 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
3236 int delim
= zLine
[h
++];
3237 azArg
[nArg
++] = &zLine
[h
];
3238 while( zLine
[h
] && zLine
[h
]!=delim
){
3239 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
3242 if( zLine
[h
]==delim
){
3245 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
3247 azArg
[nArg
++] = &zLine
[h
];
3248 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
3249 if( zLine
[h
] ) zLine
[h
++] = 0;
3250 resolve_backslashes(azArg
[nArg
-1]);
3254 /* Process the input line.
3256 if( nArg
==0 ) return 0; /* no tokens, no error */
3257 n
= strlen30(azArg
[0]);
3260 #ifndef SQLITE_OMIT_AUTHORIZATION
3261 if( c
=='a' && strncmp(azArg
[0], "auth", n
)==0 ){
3263 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
3265 goto meta_command_exit
;
3268 if( booleanValue(azArg
[1]) ){
3269 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
3271 sqlite3_set_authorizer(p
->db
, 0, 0);
3276 if( (c
=='b' && n
>=3 && strncmp(azArg
[0], "backup", n
)==0)
3277 || (c
=='s' && n
>=3 && strncmp(azArg
[0], "save", n
)==0)
3279 const char *zDestFile
= 0;
3280 const char *zDb
= 0;
3282 sqlite3_backup
*pBackup
;
3284 for(j
=1; j
<nArg
; j
++){
3285 const char *z
= azArg
[j
];
3287 while( z
[0]=='-' ) z
++;
3288 /* No options to process at this time */
3290 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
3293 }else if( zDestFile
==0 ){
3294 zDestFile
= azArg
[j
];
3297 zDestFile
= azArg
[j
];
3299 raw_printf(stderr
, "too many arguments to .backup\n");
3304 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
3307 if( zDb
==0 ) zDb
= "main";
3308 rc
= sqlite3_open(zDestFile
, &pDest
);
3309 if( rc
!=SQLITE_OK
){
3310 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
3311 sqlite3_close(pDest
);
3315 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
3317 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
3318 sqlite3_close(pDest
);
3321 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
3322 sqlite3_backup_finish(pBackup
);
3323 if( rc
==SQLITE_DONE
){
3326 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
3329 sqlite3_close(pDest
);
3332 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "bail", n
)==0 ){
3334 bail_on_error
= booleanValue(azArg
[1]);
3336 raw_printf(stderr
, "Usage: .bail on|off\n");
3341 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "binary", n
)==0 ){
3343 if( booleanValue(azArg
[1]) ){
3344 setBinaryMode(p
->out
, 1);
3346 setTextMode(p
->out
, 1);
3349 raw_printf(stderr
, "Usage: .binary on|off\n");
3354 /* The undocumented ".breakpoint" command causes a call to the no-op
3355 ** routine named test_breakpoint().
3357 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "breakpoint", n
)==0 ){
3361 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "changes", n
)==0 ){
3363 p
->countChanges
= booleanValue(azArg
[1]);
3365 raw_printf(stderr
, "Usage: .changes on|off\n");
3370 /* Cancel output redirection, if it is currently set (by .testcase)
3371 ** Then read the content of the testcase-out.txt file and compare against
3372 ** azArg[1]. If there are differences, report an error and exit.
3374 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "check", n
)==0 ){
3378 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
3380 }else if( (zRes
= readFile("testcase-out.txt"))==0 ){
3381 raw_printf(stderr
, "Error: cannot read 'testcase-out.txt'\n");
3383 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
3385 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
3386 p
->zTestcase
, azArg
[1], zRes
);
3389 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
3395 if( c
=='c' && strncmp(azArg
[0], "clone", n
)==0 ){
3397 tryToClone(p
, azArg
[1]);
3399 raw_printf(stderr
, "Usage: .clone FILENAME\n");
3404 if( c
=='d' && n
>1 && strncmp(azArg
[0], "databases", n
)==0 ){
3408 memcpy(&data
, p
, sizeof(data
));
3409 data
.showHeader
= 1;
3410 data
.cMode
= data
.mode
= MODE_Column
;
3411 data
.colWidth
[0] = 3;
3412 data
.colWidth
[1] = 15;
3413 data
.colWidth
[2] = 58;
3415 sqlite3_exec(p
->db
, "PRAGMA database_list; ", callback
, &data
, &zErrMsg
);
3417 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
3418 sqlite3_free(zErrMsg
);
3423 if( c
=='d' && strncmp(azArg
[0], "dbinfo", n
)==0 ){
3424 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
3427 if( c
=='d' && strncmp(azArg
[0], "dump", n
)==0 ){
3429 /* When playing back a "dump", the content might appear in an order
3430 ** which causes immediate foreign key constraints to be violated.
3431 ** So disable foreign-key constraint enforcement to prevent problems. */
3432 if( nArg
!=1 && nArg
!=2 ){
3433 raw_printf(stderr
, "Usage: .dump ?LIKE-PATTERN?\n");
3435 goto meta_command_exit
;
3437 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
3438 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
3439 p
->writableSchema
= 0;
3440 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
3443 run_schema_dump_query(p
,
3444 "SELECT name, type, sql FROM sqlite_master "
3445 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
3447 run_schema_dump_query(p
,
3448 "SELECT name, type, sql FROM sqlite_master "
3449 "WHERE name=='sqlite_sequence'"
3451 run_table_dump_query(p
,
3452 "SELECT sql FROM sqlite_master "
3453 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
3457 for(i
=1; i
<nArg
; i
++){
3458 zShellStatic
= azArg
[i
];
3459 run_schema_dump_query(p
,
3460 "SELECT name, type, sql FROM sqlite_master "
3461 "WHERE tbl_name LIKE shellstatic() AND type=='table'"
3462 " AND sql NOT NULL");
3463 run_table_dump_query(p
,
3464 "SELECT sql FROM sqlite_master "
3465 "WHERE sql NOT NULL"
3466 " AND type IN ('index','trigger','view')"
3467 " AND tbl_name LIKE shellstatic()", 0
3472 if( p
->writableSchema
){
3473 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
3474 p
->writableSchema
= 0;
3476 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3477 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
3478 raw_printf(p
->out
, p
->nErr
? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
3481 if( c
=='e' && strncmp(azArg
[0], "echo", n
)==0 ){
3483 p
->echoOn
= booleanValue(azArg
[1]);
3485 raw_printf(stderr
, "Usage: .echo on|off\n");
3490 if( c
=='e' && strncmp(azArg
[0], "eqp", n
)==0 ){
3492 if( strcmp(azArg
[1],"full")==0 ){
3495 p
->autoEQP
= booleanValue(azArg
[1]);
3498 raw_printf(stderr
, "Usage: .eqp on|off|full\n");
3503 if( c
=='e' && strncmp(azArg
[0], "exit", n
)==0 ){
3504 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
3508 if( c
=='e' && strncmp(azArg
[0], "explain", n
)==0 ){
3511 if( strcmp(azArg
[1],"auto")==0 ){
3514 val
= booleanValue(azArg
[1]);
3517 if( val
==1 && p
->mode
!=MODE_Explain
){
3518 p
->normalMode
= p
->mode
;
3519 p
->mode
= MODE_Explain
;
3522 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
3524 }else if( val
==99 ){
3525 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
3530 if( c
=='f' && strncmp(azArg
[0], "fullschema", n
)==0 ){
3534 memcpy(&data
, p
, sizeof(data
));
3535 data
.showHeader
= 0;
3536 data
.cMode
= data
.mode
= MODE_Semi
;
3537 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
3538 data
.cMode
= data
.mode
= MODE_Pretty
;
3542 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
3544 goto meta_command_exit
;
3547 rc
= sqlite3_exec(p
->db
,
3549 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
3550 " FROM sqlite_master UNION ALL"
3551 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
3552 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
3554 callback
, &data
, &zErrMsg
3556 if( rc
==SQLITE_OK
){
3557 sqlite3_stmt
*pStmt
;
3558 rc
= sqlite3_prepare_v2(p
->db
,
3559 "SELECT rowid FROM sqlite_master"
3560 " WHERE name GLOB 'sqlite_stat[134]'",
3562 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
3563 sqlite3_finalize(pStmt
);
3566 raw_printf(p
->out
, "/* No STAT tables available */\n");
3568 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
3569 sqlite3_exec(p
->db
, "SELECT 'ANALYZE sqlite_master'",
3570 callback
, &data
, &zErrMsg
);
3571 data
.cMode
= data
.mode
= MODE_Insert
;
3572 data
.zDestTable
= "sqlite_stat1";
3573 shell_exec(p
->db
, "SELECT * FROM sqlite_stat1",
3574 shell_callback
, &data
,&zErrMsg
);
3575 data
.zDestTable
= "sqlite_stat3";
3576 shell_exec(p
->db
, "SELECT * FROM sqlite_stat3",
3577 shell_callback
, &data
,&zErrMsg
);
3578 data
.zDestTable
= "sqlite_stat4";
3579 shell_exec(p
->db
, "SELECT * FROM sqlite_stat4",
3580 shell_callback
, &data
, &zErrMsg
);
3581 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
3585 if( c
=='h' && strncmp(azArg
[0], "headers", n
)==0 ){
3587 p
->showHeader
= booleanValue(azArg
[1]);
3589 raw_printf(stderr
, "Usage: .headers on|off\n");
3594 if( c
=='h' && strncmp(azArg
[0], "help", n
)==0 ){
3595 utf8_printf(p
->out
, "%s", zHelp
);
3598 if( c
=='i' && strncmp(azArg
[0], "import", n
)==0 ){
3599 char *zTable
; /* Insert data into this table */
3600 char *zFile
; /* Name of file to extra content from */
3601 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
3602 int nCol
; /* Number of columns in the table */
3603 int nByte
; /* Number of bytes in an SQL string */
3604 int i
, j
; /* Loop counters */
3605 int needCommit
; /* True to COMMIT or ROLLBACK at end */
3606 int nSep
; /* Number of bytes in p->colSeparator[] */
3607 char *zSql
; /* An SQL statement */
3608 ImportCtx sCtx
; /* Reader context */
3609 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
3610 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close file */
3613 raw_printf(stderr
, "Usage: .import FILE TABLE\n");
3614 goto meta_command_exit
;
3619 memset(&sCtx
, 0, sizeof(sCtx
));
3621 nSep
= strlen30(p
->colSeparator
);
3624 "Error: non-null column separator required for import\n");
3628 raw_printf(stderr
, "Error: multi-character column separators not allowed"
3632 nSep
= strlen30(p
->rowSeparator
);
3634 raw_printf(stderr
, "Error: non-null row separator required for import\n");
3637 if( nSep
==2 && p
->mode
==MODE_Csv
&& strcmp(p
->rowSeparator
, SEP_CrLf
)==0 ){
3638 /* When importing CSV (only), if the row separator is set to the
3639 ** default output row separator, change it to the default input
3640 ** row separator. This avoids having to maintain different input
3641 ** and output row separators. */
3642 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
3643 nSep
= strlen30(p
->rowSeparator
);
3646 raw_printf(stderr
, "Error: multi-character row separators not allowed"
3652 if( sCtx
.zFile
[0]=='|' ){
3653 #ifdef SQLITE_OMIT_POPEN
3654 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
3657 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
3658 sCtx
.zFile
= "<pipe>";
3662 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
3665 if( p
->mode
==MODE_Ascii
){
3666 xRead
= ascii_read_one_field
;
3668 xRead
= csv_read_one_field
;
3671 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
3674 sCtx
.cColSep
= p
->colSeparator
[0];
3675 sCtx
.cRowSep
= p
->rowSeparator
[0];
3676 zSql
= sqlite3_mprintf("SELECT * FROM %s", zTable
);
3678 raw_printf(stderr
, "Error: out of memory\n");
3682 nByte
= strlen30(zSql
);
3683 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3684 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
3685 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
3686 char *zCreate
= sqlite3_mprintf("CREATE TABLE %s", zTable
);
3688 while( xRead(&sCtx
) ){
3689 zCreate
= sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate
, cSep
, sCtx
.z
);
3691 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
3694 sqlite3_free(zCreate
);
3695 sqlite3_free(sCtx
.z
);
3697 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
3700 zCreate
= sqlite3_mprintf("%z\n)", zCreate
);
3701 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
3702 sqlite3_free(zCreate
);
3704 utf8_printf(stderr
, "CREATE TABLE %s(...) failed: %s\n", zTable
,
3705 sqlite3_errmsg(p
->db
));
3706 sqlite3_free(sCtx
.z
);
3710 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3714 if (pStmt
) sqlite3_finalize(pStmt
);
3715 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
3719 nCol
= sqlite3_column_count(pStmt
);
3720 sqlite3_finalize(pStmt
);
3722 if( nCol
==0 ) return 0; /* no columns, no error */
3723 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
3725 raw_printf(stderr
, "Error: out of memory\n");
3729 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO \"%w\" VALUES(?", zTable
);
3731 for(i
=1; i
<nCol
; i
++){
3737 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3740 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
3741 if (pStmt
) sqlite3_finalize(pStmt
);
3745 needCommit
= sqlite3_get_autocommit(p
->db
);
3746 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
3748 int startLine
= sCtx
.nLine
;
3749 for(i
=0; i
<nCol
; i
++){
3750 char *z
= xRead(&sCtx
);
3752 ** Did we reach end-of-file before finding any columns?
3753 ** If so, stop instead of NULL filling the remaining columns.
3755 if( z
==0 && i
==0 ) break;
3757 ** Did we reach end-of-file OR end-of-line before finding any
3758 ** columns in ASCII mode? If so, stop instead of NULL filling
3759 ** the remaining columns.
3761 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
3762 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
3763 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
3764 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
3765 "filling the rest with NULL\n",
3766 sCtx
.zFile
, startLine
, nCol
, i
+1);
3768 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
3771 if( sCtx
.cTerm
==sCtx
.cColSep
){
3775 }while( sCtx
.cTerm
==sCtx
.cColSep
);
3776 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
3778 sCtx
.zFile
, startLine
, nCol
, i
);
3781 sqlite3_step(pStmt
);
3782 rc
= sqlite3_reset(pStmt
);
3783 if( rc
!=SQLITE_OK
){
3784 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
3785 startLine
, sqlite3_errmsg(p
->db
));
3788 }while( sCtx
.cTerm
!=EOF
);
3791 sqlite3_free(sCtx
.z
);
3792 sqlite3_finalize(pStmt
);
3793 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
3796 if( c
=='i' && (strncmp(azArg
[0], "indices", n
)==0
3797 || strncmp(azArg
[0], "indexes", n
)==0) ){
3801 memcpy(&data
, p
, sizeof(data
));
3802 data
.showHeader
= 0;
3803 data
.cMode
= data
.mode
= MODE_List
;
3805 rc
= sqlite3_exec(p
->db
,
3806 "SELECT name FROM sqlite_master "
3807 "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
3809 "SELECT name FROM sqlite_temp_master "
3810 "WHERE type='index' "
3812 callback
, &data
, &zErrMsg
3814 }else if( nArg
==2 ){
3815 zShellStatic
= azArg
[1];
3816 rc
= sqlite3_exec(p
->db
,
3817 "SELECT name FROM sqlite_master "
3818 "WHERE type='index' AND tbl_name LIKE shellstatic() "
3820 "SELECT name FROM sqlite_temp_master "
3821 "WHERE type='index' AND tbl_name LIKE shellstatic() "
3823 callback
, &data
, &zErrMsg
3827 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
3829 goto meta_command_exit
;
3832 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
3833 sqlite3_free(zErrMsg
);
3835 }else if( rc
!= SQLITE_OK
){
3837 "Error: querying sqlite_master and sqlite_temp_master\n");
3842 #ifdef SQLITE_ENABLE_IOTRACE
3843 if( c
=='i' && strncmp(azArg
[0], "iotrace", n
)==0 ){
3844 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
3845 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
3849 }else if( strcmp(azArg
[1], "-")==0 ){
3850 sqlite3IoTrace
= iotracePrintf
;
3853 iotrace
= fopen(azArg
[1], "w");
3855 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
3859 sqlite3IoTrace
= iotracePrintf
;
3864 if( c
=='l' && n
>=5 && strncmp(azArg
[0], "limits", n
)==0 ){
3865 static const struct {
3866 const char *zLimitName
; /* Name of a limit */
3867 int limitCode
; /* Integer code for that limit */
3869 { "length", SQLITE_LIMIT_LENGTH
},
3870 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
3871 { "column", SQLITE_LIMIT_COLUMN
},
3872 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
3873 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
3874 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
3875 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
3876 { "attached", SQLITE_LIMIT_ATTACHED
},
3877 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
3878 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
3879 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
3880 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
3885 for(i
=0; i
<ArraySize(aLimit
); i
++){
3886 printf("%20s %d\n", aLimit
[i
].zLimitName
,
3887 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
3890 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
3892 goto meta_command_exit
;
3895 n2
= strlen30(azArg
[1]);
3896 for(i
=0; i
<ArraySize(aLimit
); i
++){
3897 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
3901 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
3903 goto meta_command_exit
;
3908 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
3909 "enter \".limits\" with no arguments for a list.\n",
3912 goto meta_command_exit
;
3915 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
3916 (int)integerValue(azArg
[2]));
3918 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
3919 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
3923 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3924 if( c
=='l' && strncmp(azArg
[0], "load", n
)==0 ){
3925 const char *zFile
, *zProc
;
3928 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
3930 goto meta_command_exit
;
3933 zProc
= nArg
>=3 ? azArg
[2] : 0;
3935 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
3936 if( rc
!=SQLITE_OK
){
3937 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
3938 sqlite3_free(zErrMsg
);
3944 if( c
=='l' && strncmp(azArg
[0], "log", n
)==0 ){
3946 raw_printf(stderr
, "Usage: .log FILENAME\n");
3949 const char *zFile
= azArg
[1];
3950 output_file_close(p
->pLog
);
3951 p
->pLog
= output_file_open(zFile
);
3955 if( c
=='m' && strncmp(azArg
[0], "mode", n
)==0 ){
3956 const char *zMode
= nArg
>=2 ? azArg
[1] : "";
3957 int n2
= (int)strlen(zMode
);
3959 if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"lines",n2
)==0 ){
3960 p
->mode
= MODE_Line
;
3961 }else if( c2
=='c' && strncmp(azArg
[1],"columns",n2
)==0 ){
3962 p
->mode
= MODE_Column
;
3963 }else if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"list",n2
)==0 ){
3964 p
->mode
= MODE_List
;
3965 }else if( c2
=='h' && strncmp(azArg
[1],"html",n2
)==0 ){
3966 p
->mode
= MODE_Html
;
3967 }else if( c2
=='t' && strncmp(azArg
[1],"tcl",n2
)==0 ){
3969 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
3970 }else if( c2
=='c' && strncmp(azArg
[1],"csv",n2
)==0 ){
3972 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
3973 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
3974 }else if( c2
=='t' && strncmp(azArg
[1],"tabs",n2
)==0 ){
3975 p
->mode
= MODE_List
;
3976 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
3977 }else if( c2
=='i' && strncmp(azArg
[1],"insert",n2
)==0 ){
3978 p
->mode
= MODE_Insert
;
3979 set_table_name(p
, nArg
>=3 ? azArg
[2] : "table");
3980 }else if( c2
=='a' && strncmp(azArg
[1],"ascii",n2
)==0 ){
3981 p
->mode
= MODE_Ascii
;
3982 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
3983 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
3985 raw_printf(stderr
, "Error: mode should be one of: "
3986 "ascii column csv html insert line list tabs tcl\n");
3992 if( c
=='n' && strncmp(azArg
[0], "nullvalue", n
)==0 ){
3994 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
3995 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
3997 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
4002 if( c
=='o' && strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
4003 char *zNewFilename
; /* Name of the database file to open */
4004 int iName
= 1; /* Index in azArg[] of the filename */
4005 int newFlag
= 0; /* True to delete file before opening */
4006 /* Close the existing database */
4007 session_close_all(p
);
4008 sqlite3_close(p
->db
);
4010 sqlite3_free(p
->zFreeOnClose
);
4011 p
->zFreeOnClose
= 0;
4012 /* Check for command-line arguments */
4013 for(iName
=1; iName
<nArg
&& azArg
[iName
][0]=='-'; iName
++){
4014 const char *z
= azArg
[iName
];
4015 if( optionMatch(z
,"new") ){
4017 }else if( z
[0]=='-' ){
4018 utf8_printf(stderr
, "unknown option: %s\n", z
);
4020 goto meta_command_exit
;
4023 /* If a filename is specified, try to open it first */
4024 zNewFilename
= nArg
>iName
? sqlite3_mprintf("%s", azArg
[iName
]) : 0;
4026 if( newFlag
) shellDeleteFile(zNewFilename
);
4027 p
->zDbFilename
= zNewFilename
;
4030 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
4031 sqlite3_free(zNewFilename
);
4033 p
->zFreeOnClose
= zNewFilename
;
4037 /* As a fall-back open a TEMP database */
4044 && (strncmp(azArg
[0], "output", n
)==0 || strncmp(azArg
[0], "once", n
)==0)
4046 const char *zFile
= nArg
>=2 ? azArg
[1] : "stdout";
4048 utf8_printf(stderr
, "Usage: .%s FILE\n", azArg
[0]);
4050 goto meta_command_exit
;
4052 if( n
>1 && strncmp(azArg
[0], "once", n
)==0 ){
4054 raw_printf(stderr
, "Usage: .once FILE\n");
4056 goto meta_command_exit
;
4063 if( zFile
[0]=='|' ){
4064 #ifdef SQLITE_OMIT_POPEN
4065 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
4069 p
->out
= popen(zFile
+ 1, "w");
4071 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
4075 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
4079 p
->out
= output_file_open(zFile
);
4081 if( strcmp(zFile
,"off")!=0 ){
4082 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
4087 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
4092 if( c
=='p' && n
>=3 && strncmp(azArg
[0], "print", n
)==0 ){
4094 for(i
=1; i
<nArg
; i
++){
4095 if( i
>1 ) raw_printf(p
->out
, " ");
4096 utf8_printf(p
->out
, "%s", azArg
[i
]);
4098 raw_printf(p
->out
, "\n");
4101 if( c
=='p' && strncmp(azArg
[0], "prompt", n
)==0 ){
4103 strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
4106 strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
4110 if( c
=='q' && strncmp(azArg
[0], "quit", n
)==0 ){
4114 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "read", n
)==0 ){
4117 raw_printf(stderr
, "Usage: .read FILE\n");
4119 goto meta_command_exit
;
4121 alt
= fopen(azArg
[1], "rb");
4123 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
4126 rc
= process_input(p
, alt
);
4131 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "restore", n
)==0 ){
4132 const char *zSrcFile
;
4135 sqlite3_backup
*pBackup
;
4139 zSrcFile
= azArg
[1];
4141 }else if( nArg
==3 ){
4142 zSrcFile
= azArg
[2];
4145 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
4147 goto meta_command_exit
;
4149 rc
= sqlite3_open(zSrcFile
, &pSrc
);
4150 if( rc
!=SQLITE_OK
){
4151 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
4152 sqlite3_close(pSrc
);
4156 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
4158 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
4159 sqlite3_close(pSrc
);
4162 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
4163 || rc
==SQLITE_BUSY
){
4164 if( rc
==SQLITE_BUSY
){
4165 if( nTimeout
++ >= 3 ) break;
4169 sqlite3_backup_finish(pBackup
);
4170 if( rc
==SQLITE_DONE
){
4172 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
4173 raw_printf(stderr
, "Error: source database is busy\n");
4176 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
4179 sqlite3_close(pSrc
);
4183 if( c
=='s' && strncmp(azArg
[0], "scanstats", n
)==0 ){
4185 p
->scanstatsOn
= booleanValue(azArg
[1]);
4186 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
4187 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
4190 raw_printf(stderr
, "Usage: .scanstats on|off\n");
4195 if( c
=='s' && strncmp(azArg
[0], "schema", n
)==0 ){
4199 memcpy(&data
, p
, sizeof(data
));
4200 data
.showHeader
= 0;
4201 data
.cMode
= data
.mode
= MODE_Semi
;
4202 if( nArg
>=2 && optionMatch(azArg
[1], "indent") ){
4203 data
.cMode
= data
.mode
= MODE_Pretty
;
4205 if( nArg
==2 ) azArg
[1] = azArg
[2];
4207 if( nArg
==2 && azArg
[1][0]!='-' ){
4209 for(i
=0; azArg
[1][i
]; i
++) azArg
[1][i
] = ToLower(azArg
[1][i
]);
4210 if( strcmp(azArg
[1],"sqlite_master")==0 ){
4211 char *new_argv
[2], *new_colv
[2];
4212 new_argv
[0] = "CREATE TABLE sqlite_master (\n"
4216 " rootpage integer,\n"
4220 new_colv
[0] = "sql";
4222 callback(&data
, 1, new_argv
, new_colv
);
4224 }else if( strcmp(azArg
[1],"sqlite_temp_master")==0 ){
4225 char *new_argv
[2], *new_colv
[2];
4226 new_argv
[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
4230 " rootpage integer,\n"
4234 new_colv
[0] = "sql";
4236 callback(&data
, 1, new_argv
, new_colv
);
4239 zShellStatic
= azArg
[1];
4240 rc
= sqlite3_exec(p
->db
,
4242 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4243 " FROM sqlite_master UNION ALL"
4244 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4245 "WHERE lower(tbl_name) LIKE shellstatic()"
4246 " AND type!='meta' AND sql NOTNULL "
4248 callback
, &data
, &zErrMsg
);
4251 }else if( nArg
==1 ){
4252 rc
= sqlite3_exec(p
->db
,
4254 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4255 " FROM sqlite_master UNION ALL"
4256 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4257 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
4259 callback
, &data
, &zErrMsg
4262 raw_printf(stderr
, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
4264 goto meta_command_exit
;
4267 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
4268 sqlite3_free(zErrMsg
);
4270 }else if( rc
!= SQLITE_OK
){
4271 raw_printf(stderr
,"Error: querying schema information\n");
4278 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
4279 if( c
=='s' && n
==11 && strncmp(azArg
[0], "selecttrace", n
)==0 ){
4280 sqlite3SelectTrace
= integerValue(azArg
[1]);
4284 #if defined(SQLITE_ENABLE_SESSION)
4285 if( c
=='s' && strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
4286 OpenSession
*pSession
= &p
->aSession
[0];
4287 char **azCmd
= &azArg
[1];
4289 int nCmd
= nArg
- 1;
4291 if( nArg
<=1 ) goto session_syntax_error
;
4294 for(iSes
=0; iSes
<p
->nSession
; iSes
++){
4295 if( strcmp(p
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
4297 if( iSes
<p
->nSession
){
4298 pSession
= &p
->aSession
[iSes
];
4302 pSession
= &p
->aSession
[0];
4307 /* .session attach TABLE
4308 ** Invoke the sqlite3session_attach() interface to attach a particular
4309 ** table so that it is never filtered.
4311 if( strcmp(azCmd
[0],"attach")==0 ){
4312 if( nCmd
!=2 ) goto session_syntax_error
;
4313 if( pSession
->p
==0 ){
4315 raw_printf(stderr
, "ERROR: No sessions are open\n");
4317 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
4319 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
4325 /* .session changeset FILE
4326 ** .session patchset FILE
4327 ** Write a changeset or patchset into a file. The file is overwritten.
4329 if( strcmp(azCmd
[0],"changeset")==0 || strcmp(azCmd
[0],"patchset")==0 ){
4331 if( nCmd
!=2 ) goto session_syntax_error
;
4332 if( pSession
->p
==0 ) goto session_not_open
;
4333 out
= fopen(azCmd
[1], "wb");
4335 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n", azCmd
[1]);
4339 if( azCmd
[0][0]=='c' ){
4340 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
4342 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
4345 printf("Error: error code %d\n", rc
);
4349 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
4350 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
4353 sqlite3_free(pChng
);
4359 ** Close the identified session
4361 if( strcmp(azCmd
[0], "close")==0 ){
4362 if( nCmd
!=1 ) goto session_syntax_error
;
4364 session_close(pSession
);
4365 p
->aSession
[iSes
] = p
->aSession
[--p
->nSession
];
4369 /* .session enable ?BOOLEAN?
4370 ** Query or set the enable flag
4372 if( strcmp(azCmd
[0], "enable")==0 ){
4374 if( nCmd
>2 ) goto session_syntax_error
;
4375 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
4377 ii
= sqlite3session_enable(pSession
->p
, ii
);
4378 utf8_printf(p
->out
, "session %s enable flag = %d\n",
4379 pSession
->zName
, ii
);
4383 /* .session filter GLOB ....
4384 ** Set a list of GLOB patterns of table names to be excluded.
4386 if( strcmp(azCmd
[0], "filter")==0 ){
4388 if( nCmd
<2 ) goto session_syntax_error
;
4390 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
4391 sqlite3_free(pSession
->azFilter
[ii
]);
4393 sqlite3_free(pSession
->azFilter
);
4394 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
4395 pSession
->azFilter
= sqlite3_malloc( nByte
);
4396 if( pSession
->azFilter
==0 ){
4397 raw_printf(stderr
, "Error: out or memory\n");
4400 for(ii
=1; ii
<nCmd
; ii
++){
4401 pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
4403 pSession
->nFilter
= ii
-1;
4407 /* .session indirect ?BOOLEAN?
4408 ** Query or set the indirect flag
4410 if( strcmp(azCmd
[0], "indirect")==0 ){
4412 if( nCmd
>2 ) goto session_syntax_error
;
4413 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
4415 ii
= sqlite3session_indirect(pSession
->p
, ii
);
4416 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
4417 pSession
->zName
, ii
);
4422 ** Determine if the session is empty
4424 if( strcmp(azCmd
[0], "isempty")==0 ){
4426 if( nCmd
!=1 ) goto session_syntax_error
;
4428 ii
= sqlite3session_isempty(pSession
->p
);
4429 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
4430 pSession
->zName
, ii
);
4435 ** List all currently open sessions
4437 if( strcmp(azCmd
[0],"list")==0 ){
4438 for(i
=0; i
<p
->nSession
; i
++){
4439 utf8_printf(p
->out
, "%d %s\n", i
, p
->aSession
[i
].zName
);
4443 /* .session open DB NAME
4444 ** Open a new session called NAME on the attached database DB.
4445 ** DB is normally "main".
4447 if( strcmp(azCmd
[0],"open")==0 ){
4449 if( nCmd
!=3 ) goto session_syntax_error
;
4451 if( zName
[0]==0 ) goto session_syntax_error
;
4452 for(i
=0; i
<p
->nSession
; i
++){
4453 if( strcmp(p
->aSession
[i
].zName
,zName
)==0 ){
4454 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
4455 goto meta_command_exit
;
4458 if( p
->nSession
>=ArraySize(p
->aSession
) ){
4459 raw_printf(stderr
, "Maximum of %d sessions\n", ArraySize(p
->aSession
));
4460 goto meta_command_exit
;
4462 pSession
= &p
->aSession
[p
->nSession
];
4463 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
4465 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
4467 goto meta_command_exit
;
4469 pSession
->nFilter
= 0;
4470 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
4472 pSession
->zName
= sqlite3_mprintf("%s", zName
);
4474 /* If no command name matches, show a syntax error */
4475 session_syntax_error
:
4481 /* Undocumented commands for internal testing. Subject to change
4482 ** without notice. */
4483 if( c
=='s' && n
>=10 && strncmp(azArg
[0], "selftest-", 9)==0 ){
4484 if( strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
4486 for(i
=1; i
<nArg
; i
++){
4487 v
= booleanValue(azArg
[i
]);
4488 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
4491 if( strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
4492 int i
; sqlite3_int64 v
;
4493 for(i
=1; i
<nArg
; i
++){
4495 v
= integerValue(azArg
[i
]);
4496 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
4497 utf8_printf(p
->out
, "%s", zBuf
);
4503 if( c
=='s' && strncmp(azArg
[0], "separator", n
)==0 ){
4504 if( nArg
<2 || nArg
>3 ){
4505 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
4509 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
4510 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
4513 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
4514 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
4519 && (strncmp(azArg
[0], "shell", n
)==0 || strncmp(azArg
[0],"system",n
)==0)
4524 raw_printf(stderr
, "Usage: .system COMMAND\n");
4526 goto meta_command_exit
;
4528 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
4529 for(i
=2; i
<nArg
; i
++){
4530 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
4535 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
4538 if( c
=='s' && strncmp(azArg
[0], "show", n
)==0 ){
4539 static const char *azBool
[] = { "off", "on", "full", "unk" };
4542 raw_printf(stderr
, "Usage: .show\n");
4544 goto meta_command_exit
;
4546 utf8_printf(p
->out
, "%12.12s: %s\n","echo", azBool
[p
->echoOn
!=0]);
4547 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
4548 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
4549 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
4550 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
4551 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
4552 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
4553 output_c_string(p
->out
, p
->nullValue
);
4554 raw_printf(p
->out
, "\n");
4555 utf8_printf(p
->out
,"%12.12s: %s\n","output",
4556 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
4557 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
4558 output_c_string(p
->out
, p
->colSeparator
);
4559 raw_printf(p
->out
, "\n");
4560 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
4561 output_c_string(p
->out
, p
->rowSeparator
);
4562 raw_printf(p
->out
, "\n");
4563 utf8_printf(p
->out
, "%12.12s: %s\n","stats", azBool
[p
->statsOn
!=0]);
4564 utf8_printf(p
->out
, "%12.12s: ", "width");
4565 for (i
=0;i
<(int)ArraySize(p
->colWidth
) && p
->colWidth
[i
] != 0;i
++) {
4566 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
4568 raw_printf(p
->out
, "\n");
4569 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
4570 p
->zDbFilename
? p
->zDbFilename
: "");
4573 if( c
=='s' && strncmp(azArg
[0], "stats", n
)==0 ){
4575 p
->statsOn
= booleanValue(azArg
[1]);
4576 }else if( nArg
==1 ){
4577 display_stats(p
->db
, p
, 0);
4579 raw_printf(stderr
, "Usage: .stats ?on|off?\n");
4584 if( c
=='t' && n
>1 && strncmp(azArg
[0], "tables", n
)==0 ){
4585 sqlite3_stmt
*pStmt
;
4591 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
4592 if( rc
) return shellDatabaseError(p
->db
);
4594 /* Create an SQL statement to query for the list of tables in the
4595 ** main and all attached databases where the table name matches the
4596 ** LIKE pattern bound to variable "?1". */
4597 zSql
= sqlite3_mprintf(
4598 "SELECT name FROM sqlite_master"
4599 " WHERE type IN ('table','view')"
4600 " AND name NOT LIKE 'sqlite_%%'"
4601 " AND name LIKE ?1");
4602 while( zSql
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
4603 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
4604 if( zDbName
==0 || strcmp(zDbName
,"main")==0 ) continue;
4605 if( strcmp(zDbName
,"temp")==0 ){
4606 zSql
= sqlite3_mprintf(
4608 "SELECT 'temp.' || name FROM sqlite_temp_master"
4609 " WHERE type IN ('table','view')"
4610 " AND name NOT LIKE 'sqlite_%%'"
4611 " AND name LIKE ?1", zSql
);
4613 zSql
= sqlite3_mprintf(
4615 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
4616 " WHERE type IN ('table','view')"
4617 " AND name NOT LIKE 'sqlite_%%'"
4618 " AND name LIKE ?1", zSql
, zDbName
, zDbName
);
4621 rc
= sqlite3_finalize(pStmt
);
4622 if( zSql
&& rc
==SQLITE_OK
){
4623 zSql
= sqlite3_mprintf("%z ORDER BY 1", zSql
);
4624 if( zSql
) rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4627 if( !zSql
) return shellNomemError();
4628 if( rc
) return shellDatabaseError(p
->db
);
4630 /* Run the SQL statement prepared by the above block. Store the results
4631 ** as an array of nul-terminated strings in azResult[]. */
4635 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
4637 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
4639 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
4642 int n2
= nAlloc
*2 + 10;
4643 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
4645 rc
= shellNomemError();
4651 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
4652 if( 0==azResult
[nRow
] ){
4653 rc
= shellNomemError();
4658 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
4659 rc
= shellDatabaseError(p
->db
);
4662 /* Pretty-print the contents of array azResult[] to the output */
4663 if( rc
==0 && nRow
>0 ){
4664 int len
, maxlen
= 0;
4666 int nPrintCol
, nPrintRow
;
4667 for(i
=0; i
<nRow
; i
++){
4668 len
= strlen30(azResult
[i
]);
4669 if( len
>maxlen
) maxlen
= len
;
4671 nPrintCol
= 80/(maxlen
+2);
4672 if( nPrintCol
<1 ) nPrintCol
= 1;
4673 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
4674 for(i
=0; i
<nPrintRow
; i
++){
4675 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
4676 char *zSp
= j
<nPrintRow
? "" : " ";
4677 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
4678 azResult
[j
] ? azResult
[j
]:"");
4680 raw_printf(p
->out
, "\n");
4684 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
4685 sqlite3_free(azResult
);
4688 /* Begin redirecting output to the file "testcase-out.txt" */
4689 if( c
=='t' && strcmp(azArg
[0],"testcase")==0 ){
4691 p
->out
= output_file_open("testcase-out.txt");
4693 utf8_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
4696 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
4698 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
4702 if( c
=='t' && n
>=8 && strncmp(azArg
[0], "testctrl", n
)==0 && nArg
>=2 ){
4703 static const struct {
4704 const char *zCtrlName
; /* Name of a test-control option */
4705 int ctrlCode
; /* Integer code for that option */
4707 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE
},
4708 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
},
4709 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET
},
4710 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST
},
4711 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL
},
4712 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS
},
4713 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
},
4714 { "assert", SQLITE_TESTCTRL_ASSERT
},
4715 { "always", SQLITE_TESTCTRL_ALWAYS
},
4716 { "reserve", SQLITE_TESTCTRL_RESERVE
},
4717 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
},
4718 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD
},
4719 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC
},
4720 { "byteorder", SQLITE_TESTCTRL_BYTEORDER
},
4721 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
},
4722 { "imposter", SQLITE_TESTCTRL_IMPOSTER
},
4729 /* convert testctrl text option to value. allow any unique prefix
4730 ** of the option name, or a numerical value. */
4731 n2
= strlen30(azArg
[1]);
4732 for(i
=0; i
<ArraySize(aCtrl
); i
++){
4733 if( strncmp(azArg
[1], aCtrl
[i
].zCtrlName
, n2
)==0 ){
4735 testctrl
= aCtrl
[i
].ctrlCode
;
4737 utf8_printf(stderr
, "ambiguous option name: \"%s\"\n", azArg
[1]);
4743 if( testctrl
<0 ) testctrl
= (int)integerValue(azArg
[1]);
4744 if( (testctrl
<SQLITE_TESTCTRL_FIRST
) || (testctrl
>SQLITE_TESTCTRL_LAST
) ){
4745 utf8_printf(stderr
,"Error: invalid testctrl option: %s\n", azArg
[1]);
4749 /* sqlite3_test_control(int, db, int) */
4750 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
4751 case SQLITE_TESTCTRL_RESERVE
:
4753 int opt
= (int)strtol(azArg
[2], 0, 0);
4754 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
4755 raw_printf(p
->out
, "%d (0x%08x)\n", rc2
, rc2
);
4757 utf8_printf(stderr
,"Error: testctrl %s takes a single int option\n",
4762 /* sqlite3_test_control(int) */
4763 case SQLITE_TESTCTRL_PRNG_SAVE
:
4764 case SQLITE_TESTCTRL_PRNG_RESTORE
:
4765 case SQLITE_TESTCTRL_PRNG_RESET
:
4766 case SQLITE_TESTCTRL_BYTEORDER
:
4768 rc2
= sqlite3_test_control(testctrl
);
4769 raw_printf(p
->out
, "%d (0x%08x)\n", rc2
, rc2
);
4771 utf8_printf(stderr
,"Error: testctrl %s takes no options\n",
4776 /* sqlite3_test_control(int, uint) */
4777 case SQLITE_TESTCTRL_PENDING_BYTE
:
4779 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
4780 rc2
= sqlite3_test_control(testctrl
, opt
);
4781 raw_printf(p
->out
, "%d (0x%08x)\n", rc2
, rc2
);
4783 utf8_printf(stderr
,"Error: testctrl %s takes a single unsigned"
4784 " int option\n", azArg
[1]);
4788 /* sqlite3_test_control(int, int) */
4789 case SQLITE_TESTCTRL_ASSERT
:
4790 case SQLITE_TESTCTRL_ALWAYS
:
4791 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
4793 int opt
= booleanValue(azArg
[2]);
4794 rc2
= sqlite3_test_control(testctrl
, opt
);
4795 raw_printf(p
->out
, "%d (0x%08x)\n", rc2
, rc2
);
4797 utf8_printf(stderr
,"Error: testctrl %s takes a single int option\n",
4802 /* sqlite3_test_control(int, char *) */
4803 #ifdef SQLITE_N_KEYWORD
4804 case SQLITE_TESTCTRL_ISKEYWORD
:
4806 const char *opt
= azArg
[2];
4807 rc2
= sqlite3_test_control(testctrl
, opt
);
4808 raw_printf(p
->out
, "%d (0x%08x)\n", rc2
, rc2
);
4811 "Error: testctrl %s takes a single char * option\n",
4817 case SQLITE_TESTCTRL_IMPOSTER
:
4819 rc2
= sqlite3_test_control(testctrl
, p
->db
,
4821 integerValue(azArg
[3]),
4822 integerValue(azArg
[4]));
4823 raw_printf(p
->out
, "%d (0x%08x)\n", rc2
, rc2
);
4825 raw_printf(stderr
,"Usage: .testctrl imposter dbName onoff tnum\n");
4829 case SQLITE_TESTCTRL_BITVEC_TEST
:
4830 case SQLITE_TESTCTRL_FAULT_INSTALL
:
4831 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS
:
4832 case SQLITE_TESTCTRL_SCRATCHMALLOC
:
4835 "Error: CLI support for testctrl %s not implemented\n",
4842 if( c
=='t' && n
>4 && strncmp(azArg
[0], "timeout", n
)==0 ){
4844 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
4847 if( c
=='t' && n
>=5 && strncmp(azArg
[0], "timer", n
)==0 ){
4849 enableTimer
= booleanValue(azArg
[1]);
4850 if( enableTimer
&& !HAS_TIMER
){
4851 raw_printf(stderr
, "Error: timer not available on this system.\n");
4855 raw_printf(stderr
, "Usage: .timer on|off\n");
4860 if( c
=='t' && strncmp(azArg
[0], "trace", n
)==0 ){
4863 raw_printf(stderr
, "Usage: .trace FILE|off\n");
4865 goto meta_command_exit
;
4867 output_file_close(p
->traceOut
);
4868 p
->traceOut
= output_file_open(azArg
[1]);
4869 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
4870 if( p
->traceOut
==0 ){
4871 sqlite3_trace_v2(p
->db
, 0, 0, 0);
4873 sqlite3_trace_v2(p
->db
, SQLITE_TRACE_STMT
, sql_trace_callback
,p
->traceOut
);
4878 #if SQLITE_USER_AUTHENTICATION
4879 if( c
=='u' && strncmp(azArg
[0], "user", n
)==0 ){
4881 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
4883 goto meta_command_exit
;
4886 if( strcmp(azArg
[1],"login")==0 ){
4888 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
4890 goto meta_command_exit
;
4892 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3],
4893 (int)strlen(azArg
[3]));
4895 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
4898 }else if( strcmp(azArg
[1],"add")==0 ){
4900 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
4902 goto meta_command_exit
;
4904 rc
= sqlite3_user_add(p
->db
, azArg
[2],
4905 azArg
[3], (int)strlen(azArg
[3]),
4906 booleanValue(azArg
[4]));
4908 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
4911 }else if( strcmp(azArg
[1],"edit")==0 ){
4913 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
4915 goto meta_command_exit
;
4917 rc
= sqlite3_user_change(p
->db
, azArg
[2],
4918 azArg
[3], (int)strlen(azArg
[3]),
4919 booleanValue(azArg
[4]));
4921 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
4924 }else if( strcmp(azArg
[1],"delete")==0 ){
4926 raw_printf(stderr
, "Usage: .user delete USER\n");
4928 goto meta_command_exit
;
4930 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
4932 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
4936 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
4938 goto meta_command_exit
;
4941 #endif /* SQLITE_USER_AUTHENTICATION */
4943 if( c
=='v' && strncmp(azArg
[0], "version", n
)==0 ){
4944 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
4945 sqlite3_libversion(), sqlite3_sourceid());
4948 if( c
=='v' && strncmp(azArg
[0], "vfsinfo", n
)==0 ){
4949 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
4952 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
4954 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
4955 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
4956 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
4957 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
4962 if( c
=='v' && strncmp(azArg
[0], "vfslist", n
)==0 ){
4964 sqlite3_vfs
*pCurrent
= 0;
4966 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
4968 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
4969 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
4970 pVfs
==pCurrent
? " <--- CURRENT" : "");
4971 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
4972 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
4973 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
4975 raw_printf(p
->out
, "-----------------------------------\n");
4980 if( c
=='v' && strncmp(azArg
[0], "vfsname", n
)==0 ){
4981 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
4984 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
4986 utf8_printf(p
->out
, "%s\n", zVfsName
);
4987 sqlite3_free(zVfsName
);
4992 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
4993 if( c
=='w' && strncmp(azArg
[0], "wheretrace", n
)==0 ){
4994 sqlite3WhereTrace
= nArg
>=2 ? booleanValue(azArg
[1]) : 0xff;
4998 if( c
=='w' && strncmp(azArg
[0], "width", n
)==0 ){
5000 assert( nArg
<=ArraySize(azArg
) );
5001 for(j
=1; j
<nArg
&& j
<ArraySize(p
->colWidth
); j
++){
5002 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
5007 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
5008 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
5015 if( p
->outCount
==0 ) output_reset(p
);
5021 ** Return TRUE if a semicolon occurs anywhere in the first N characters
5024 static int line_contains_semicolon(const char *z
, int N
){
5026 for(i
=0; i
<N
; i
++){ if( z
[i
]==';' ) return 1; }
5031 ** Test to see if a line consists entirely of whitespace.
5033 static int _all_whitespace(const char *z
){
5035 if( IsSpace(z
[0]) ) continue;
5036 if( *z
=='/' && z
[1]=='*' ){
5038 while( *z
&& (*z
!='*' || z
[1]!='/') ){ z
++; }
5039 if( *z
==0 ) return 0;
5043 if( *z
=='-' && z
[1]=='-' ){
5045 while( *z
&& *z
!='\n' ){ z
++; }
5046 if( *z
==0 ) return 1;
5055 ** Return TRUE if the line typed in is an SQL command terminator other
5056 ** than a semi-colon. The SQL Server style "go" command is understood
5057 ** as is the Oracle "/".
5059 static int line_is_command_terminator(const char *zLine
){
5060 while( IsSpace(zLine
[0]) ){ zLine
++; };
5061 if( zLine
[0]=='/' && _all_whitespace(&zLine
[1]) ){
5062 return 1; /* Oracle */
5064 if( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o'
5065 && _all_whitespace(&zLine
[2]) ){
5066 return 1; /* SQL Server */
5072 ** Return true if zSql is a complete SQL statement. Return false if it
5073 ** ends in the middle of a string literal or C-style comment.
5075 static int line_is_complete(char *zSql
, int nSql
){
5077 if( zSql
==0 ) return 1;
5080 rc
= sqlite3_complete(zSql
);
5086 ** Read input from *in and process it. If *in==0 then input
5087 ** is interactive - the user is typing it it. Otherwise, input
5088 ** is coming from a file or device. A prompt is issued and history
5089 ** is saved only if input is interactive. An interrupt signal will
5090 ** cause this routine to exit immediately, unless input is interactive.
5092 ** Return the number of errors.
5094 static int process_input(ShellState
*p
, FILE *in
){
5095 char *zLine
= 0; /* A single input line */
5096 char *zSql
= 0; /* Accumulated SQL text */
5097 int nLine
; /* Length of current line */
5098 int nSql
= 0; /* Bytes of zSql[] used */
5099 int nAlloc
= 0; /* Allocated zSql[] space */
5100 int nSqlPrior
= 0; /* Bytes of zSql[] used by prior line */
5101 char *zErrMsg
; /* Error message returned */
5102 int rc
; /* Error code */
5103 int errCnt
= 0; /* Number of errors seen */
5104 int lineno
= 0; /* Current line number */
5105 int startline
= 0; /* Line number for start of current input */
5107 while( errCnt
==0 || !bail_on_error
|| (in
==0 && stdin_is_interactive
) ){
5109 zLine
= one_input_line(in
, zLine
, nSql
>0);
5112 if( in
==0 && stdin_is_interactive
) printf("\n");
5115 if( seenInterrupt
){
5120 if( nSql
==0 && _all_whitespace(zLine
) ){
5121 if( p
->echoOn
) printf("%s\n", zLine
);
5124 if( zLine
&& zLine
[0]=='.' && nSql
==0 ){
5125 if( p
->echoOn
) printf("%s\n", zLine
);
5126 rc
= do_meta_command(zLine
, p
);
5127 if( rc
==2 ){ /* exit requested */
5134 if( line_is_command_terminator(zLine
) && line_is_complete(zSql
, nSql
) ){
5135 memcpy(zLine
,";",2);
5137 nLine
= strlen30(zLine
);
5138 if( nSql
+nLine
+2>=nAlloc
){
5139 nAlloc
= nSql
+nLine
+100;
5140 zSql
= realloc(zSql
, nAlloc
);
5142 raw_printf(stderr
, "Error: out of memory\n");
5149 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
5150 assert( nAlloc
>0 && zSql
!=0 );
5151 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
5155 zSql
[nSql
++] = '\n';
5156 memcpy(zSql
+nSql
, zLine
, nLine
+1);
5159 if( nSql
&& line_contains_semicolon(&zSql
[nSqlPrior
], nSql
-nSqlPrior
)
5160 && sqlite3_complete(zSql
) ){
5163 if( p
->backslashOn
) resolve_backslashes(zSql
);
5165 rc
= shell_exec(p
->db
, zSql
, shell_callback
, p
, &zErrMsg
);
5167 if( rc
|| zErrMsg
){
5169 if( in
!=0 || !stdin_is_interactive
){
5170 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
5171 "Error: near line %d:", startline
);
5173 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "Error:");
5176 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrMsg
);
5177 sqlite3_free(zErrMsg
);
5180 utf8_printf(stderr
, "%s %s\n", zPrefix
, sqlite3_errmsg(p
->db
));
5183 }else if( p
->countChanges
){
5184 raw_printf(p
->out
, "changes: %3d total_changes: %d\n",
5185 sqlite3_changes(p
->db
), sqlite3_total_changes(p
->db
));
5192 }else if( nSql
&& _all_whitespace(zSql
) ){
5193 if( p
->echoOn
) printf("%s\n", zSql
);
5198 if( !_all_whitespace(zSql
) ){
5199 utf8_printf(stderr
, "Error: incomplete SQL: %s\n", zSql
);
5209 ** Return a pathname which is the user's home directory. A
5210 ** 0 return indicates an error of some kind.
5212 static char *find_home_dir(int clearFlag
){
5213 static char *home_dir
= NULL
;
5219 if( home_dir
) return home_dir
;
5221 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
5222 && !defined(__RTP__) && !defined(_WRS_KERNEL)
5224 struct passwd
*pwent
;
5225 uid_t uid
= getuid();
5226 if( (pwent
=getpwuid(uid
)) != NULL
) {
5227 home_dir
= pwent
->pw_dir
;
5232 #if defined(_WIN32_WCE)
5233 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
5238 #if defined(_WIN32) || defined(WIN32)
5240 home_dir
= getenv("USERPROFILE");
5245 home_dir
= getenv("HOME");
5248 #if defined(_WIN32) || defined(WIN32)
5250 char *zDrive
, *zPath
;
5252 zDrive
= getenv("HOMEDRIVE");
5253 zPath
= getenv("HOMEPATH");
5254 if( zDrive
&& zPath
){
5255 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
5256 home_dir
= malloc( n
);
5257 if( home_dir
==0 ) return 0;
5258 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
5265 #endif /* !_WIN32_WCE */
5268 int n
= strlen30(home_dir
) + 1;
5269 char *z
= malloc( n
);
5270 if( z
) memcpy(z
, home_dir
, n
);
5278 ** Read input from the file given by sqliterc_override. Or if that
5279 ** parameter is NULL, take input from ~/.sqliterc
5281 ** Returns the number of errors.
5283 static void process_sqliterc(
5284 ShellState
*p
, /* Configuration data */
5285 const char *sqliterc_override
/* Name of config file. NULL to use default */
5287 char *home_dir
= NULL
;
5288 const char *sqliterc
= sqliterc_override
;
5292 if (sqliterc
== NULL
) {
5293 home_dir
= find_home_dir(0);
5295 raw_printf(stderr
, "-- warning: cannot find home directory;"
5296 " cannot read ~/.sqliterc\n");
5299 sqlite3_initialize();
5300 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
5303 in
= fopen(sqliterc
,"rb");
5305 if( stdin_is_interactive
){
5306 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
5308 process_input(p
,in
);
5315 ** Show available command line options
5317 static const char zOptions
[] =
5318 " -ascii set output mode to 'ascii'\n"
5319 " -bail stop after hitting an error\n"
5320 " -batch force batch I/O\n"
5321 " -column set output mode to 'column'\n"
5322 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
5323 " -csv set output mode to 'csv'\n"
5324 " -echo print commands before execution\n"
5325 " -init FILENAME read/process named file\n"
5326 " -[no]header turn headers on or off\n"
5327 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
5328 " -heap SIZE Size of heap for memsys3 or memsys5\n"
5330 " -help show this message\n"
5331 " -html set output mode to HTML\n"
5332 " -interactive force interactive I/O\n"
5333 " -line set output mode to 'line'\n"
5334 " -list set output mode to 'list'\n"
5335 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
5336 " -mmap N default mmap size set to N\n"
5337 #ifdef SQLITE_ENABLE_MULTIPLEX
5338 " -multiplex enable the multiplexor VFS\n"
5340 " -newline SEP set output row separator. Default: '\\n'\n"
5341 " -nullvalue TEXT set text string for NULL values. Default ''\n"
5342 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
5343 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
5344 " -separator SEP set output column separator. Default: '|'\n"
5345 " -stats print memory stats before each finalize\n"
5346 " -version show SQLite version\n"
5347 " -vfs NAME use NAME as the default VFS\n"
5348 #ifdef SQLITE_ENABLE_VFSTRACE
5349 " -vfstrace enable tracing of all VFS calls\n"
5352 static void usage(int showDetail
){
5354 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
5355 "FILENAME is the name of an SQLite database. A new database is created\n"
5356 "if the file does not previously exist.\n", Argv0
);
5358 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
5360 raw_printf(stderr
, "Use the -help option for additional information\n");
5366 ** Initialize the state information in data
5368 static void main_init(ShellState
*data
) {
5369 memset(data
, 0, sizeof(*data
));
5370 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
5371 data
->autoExplain
= 1;
5372 memcpy(data
->colSeparator
,SEP_Column
, 2);
5373 memcpy(data
->rowSeparator
,SEP_Row
, 2);
5374 data
->showHeader
= 0;
5375 data
->shellFlgs
= SHFLG_Lookaside
;
5376 sqlite3_config(SQLITE_CONFIG_URI
, 1);
5377 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
5378 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
5379 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
5380 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
5384 ** Output text to the console in a font that attracts extra attention.
5387 static void printBold(const char *zText
){
5388 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
5389 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
5390 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
5391 SetConsoleTextAttribute(out
,
5392 FOREGROUND_RED
|FOREGROUND_INTENSITY
5394 printf("%s", zText
);
5395 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
5398 static void printBold(const char *zText
){
5399 printf("\033[1m%s\033[0m", zText
);
5404 ** Get the argument to an --option. Throw an error and die if no argument
5407 static char *cmdline_option_value(int argc
, char **argv
, int i
){
5409 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
5410 argv
[0], argv
[argc
-1]);
5416 #ifndef SQLITE_SHELL_IS_UTF8
5417 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
5418 # define SQLITE_SHELL_IS_UTF8 (0)
5420 # define SQLITE_SHELL_IS_UTF8 (1)
5424 #if SQLITE_SHELL_IS_UTF8
5425 int SQLITE_CDECL
main(int argc
, char **argv
){
5427 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
5432 const char *zInitFile
= 0;
5435 int warnInmemoryDb
= 0;
5440 setBinaryMode(stdin
, 0);
5441 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
5442 stdin_is_interactive
= isatty(0);
5443 stdout_is_console
= isatty(1);
5445 #if USE_SYSTEM_SQLITE+0!=1
5446 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
)!=0 ){
5447 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
5448 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
5453 #if !SQLITE_SHELL_IS_UTF8
5454 sqlite3_initialize();
5455 argv
= sqlite3_malloc64(sizeof(argv
[0])*argc
);
5457 raw_printf(stderr
, "out of memory\n");
5460 for(i
=0; i
<argc
; i
++){
5461 argv
[i
] = sqlite3_win32_unicode_to_utf8(wargv
[i
]);
5463 raw_printf(stderr
, "out of memory\n");
5468 assert( argc
>=1 && argv
&& argv
[0] );
5471 /* Make sure we have a valid signal handler early, before anything
5475 signal(SIGINT
, interrupt_handler
);
5478 #ifdef SQLITE_SHELL_DBNAME_PROC
5480 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
5481 ** of a C-function that will provide the name of the database file. Use
5482 ** this compile-time option to embed this shell program in larger
5484 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
5485 SQLITE_SHELL_DBNAME_PROC(&data
.zDbFilename
);
5490 /* Do an initial pass through the command-line argument to locate
5491 ** the name of the database file, the name of the initialization file,
5492 ** the size of the alternative malloc heap,
5493 ** and the first command to execute.
5495 for(i
=1; i
<argc
; i
++){
5499 if( data
.zDbFilename
==0 ){
5500 data
.zDbFilename
= z
;
5502 /* Excesss arguments are interpreted as SQL (or dot-commands) and
5503 ** mean that nothing is read from stdin */
5506 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
5508 raw_printf(stderr
, "out of memory\n");
5514 if( z
[1]=='-' ) z
++;
5515 if( strcmp(z
,"-separator")==0
5516 || strcmp(z
,"-nullvalue")==0
5517 || strcmp(z
,"-newline")==0
5518 || strcmp(z
,"-cmd")==0
5520 (void)cmdline_option_value(argc
, argv
, ++i
);
5521 }else if( strcmp(z
,"-init")==0 ){
5522 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
5523 }else if( strcmp(z
,"-batch")==0 ){
5524 /* Need to check for batch mode here to so we can avoid printing
5525 ** informational messages (like from process_sqliterc) before
5526 ** we do the actual processing of arguments later in a second pass.
5528 stdin_is_interactive
= 0;
5529 }else if( strcmp(z
,"-heap")==0 ){
5530 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
5532 sqlite3_int64 szHeap
;
5534 zSize
= cmdline_option_value(argc
, argv
, ++i
);
5535 szHeap
= integerValue(zSize
);
5536 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
5537 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
5539 (void)cmdline_option_value(argc
, argv
, ++i
);
5541 }else if( strcmp(z
,"-scratch")==0 ){
5543 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
5544 if( sz
>400000 ) sz
= 400000;
5545 if( sz
<2500 ) sz
= 2500;
5546 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
5549 sqlite3_config(SQLITE_CONFIG_SCRATCH
, malloc(n
*sz
+1), sz
, n
);
5550 data
.shellFlgs
|= SHFLG_Scratch
;
5551 }else if( strcmp(z
,"-pagecache")==0 ){
5553 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
5554 if( sz
>70000 ) sz
= 70000;
5556 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
5557 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
5558 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
5559 data
.shellFlgs
|= SHFLG_Pagecache
;
5560 }else if( strcmp(z
,"-lookaside")==0 ){
5562 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
5564 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
5566 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
5567 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
5568 #ifdef SQLITE_ENABLE_VFSTRACE
5569 }else if( strcmp(z
,"-vfstrace")==0 ){
5570 extern int vfstrace_register(
5571 const char *zTraceName
,
5572 const char *zOldVfsName
,
5573 int (*xOut
)(const char*,void*),
5577 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
5579 #ifdef SQLITE_ENABLE_MULTIPLEX
5580 }else if( strcmp(z
,"-multiplex")==0 ){
5581 extern int sqlite3_multiple_initialize(const char*,int);
5582 sqlite3_multiplex_initialize(0, 1);
5584 }else if( strcmp(z
,"-mmap")==0 ){
5585 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
5586 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
5587 }else if( strcmp(z
,"-vfs")==0 ){
5588 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(cmdline_option_value(argc
,argv
,++i
));
5590 sqlite3_vfs_register(pVfs
, 1);
5592 utf8_printf(stderr
, "no such VFS: \"%s\"\n", argv
[i
]);
5597 if( data
.zDbFilename
==0 ){
5598 #ifndef SQLITE_OMIT_MEMORYDB
5599 data
.zDbFilename
= ":memory:";
5600 warnInmemoryDb
= argc
==1;
5602 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
5608 /* Go ahead and open the database file if it already exists. If the
5609 ** file does not exist, delay opening it. This prevents empty database
5610 ** files from being created if a user mistypes the database name argument
5611 ** to the sqlite command-line tool.
5613 if( access(data
.zDbFilename
, 0)==0 ){
5617 /* Process the initialization file if there is one. If no -init option
5618 ** is given on the command line, look for a file named ~/.sqliterc and
5619 ** try to process it.
5621 process_sqliterc(&data
,zInitFile
);
5623 /* Make a second pass through the command-line argument and set
5624 ** options. This second pass is delayed until after the initialization
5625 ** file is processed so that the command-line arguments will override
5626 ** settings in the initialization file.
5628 for(i
=1; i
<argc
; i
++){
5630 if( z
[0]!='-' ) continue;
5631 if( z
[1]=='-' ){ z
++; }
5632 if( strcmp(z
,"-init")==0 ){
5634 }else if( strcmp(z
,"-html")==0 ){
5635 data
.mode
= MODE_Html
;
5636 }else if( strcmp(z
,"-list")==0 ){
5637 data
.mode
= MODE_List
;
5638 }else if( strcmp(z
,"-line")==0 ){
5639 data
.mode
= MODE_Line
;
5640 }else if( strcmp(z
,"-column")==0 ){
5641 data
.mode
= MODE_Column
;
5642 }else if( strcmp(z
,"-csv")==0 ){
5643 data
.mode
= MODE_Csv
;
5644 memcpy(data
.colSeparator
,",",2);
5645 }else if( strcmp(z
,"-ascii")==0 ){
5646 data
.mode
= MODE_Ascii
;
5647 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
5649 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
5651 }else if( strcmp(z
,"-separator")==0 ){
5652 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
5653 "%s",cmdline_option_value(argc
,argv
,++i
));
5654 }else if( strcmp(z
,"-newline")==0 ){
5655 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
5656 "%s",cmdline_option_value(argc
,argv
,++i
));
5657 }else if( strcmp(z
,"-nullvalue")==0 ){
5658 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
5659 "%s",cmdline_option_value(argc
,argv
,++i
));
5660 }else if( strcmp(z
,"-header")==0 ){
5661 data
.showHeader
= 1;
5662 }else if( strcmp(z
,"-noheader")==0 ){
5663 data
.showHeader
= 0;
5664 }else if( strcmp(z
,"-echo")==0 ){
5666 }else if( strcmp(z
,"-eqp")==0 ){
5668 }else if( strcmp(z
,"-eqpfull")==0 ){
5670 }else if( strcmp(z
,"-stats")==0 ){
5672 }else if( strcmp(z
,"-scanstats")==0 ){
5673 data
.scanstatsOn
= 1;
5674 }else if( strcmp(z
,"-backslash")==0 ){
5675 /* Undocumented command-line option: -backslash
5676 ** Causes C-style backslash escapes to be evaluated in SQL statements
5677 ** prior to sending the SQL into SQLite. Useful for injecting
5678 ** crazy bytes in the middle of SQL statements for testing and debugging.
5680 data
.backslashOn
= 1;
5681 }else if( strcmp(z
,"-bail")==0 ){
5683 }else if( strcmp(z
,"-version")==0 ){
5684 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
5686 }else if( strcmp(z
,"-interactive")==0 ){
5687 stdin_is_interactive
= 1;
5688 }else if( strcmp(z
,"-batch")==0 ){
5689 stdin_is_interactive
= 0;
5690 }else if( strcmp(z
,"-heap")==0 ){
5692 }else if( strcmp(z
,"-scratch")==0 ){
5694 }else if( strcmp(z
,"-pagecache")==0 ){
5696 }else if( strcmp(z
,"-lookaside")==0 ){
5698 }else if( strcmp(z
,"-mmap")==0 ){
5700 }else if( strcmp(z
,"-vfs")==0 ){
5702 #ifdef SQLITE_ENABLE_VFSTRACE
5703 }else if( strcmp(z
,"-vfstrace")==0 ){
5706 #ifdef SQLITE_ENABLE_MULTIPLEX
5707 }else if( strcmp(z
,"-multiplex")==0 ){
5710 }else if( strcmp(z
,"-help")==0 ){
5712 }else if( strcmp(z
,"-cmd")==0 ){
5713 /* Run commands that follow -cmd first and separately from commands
5714 ** that simply appear on the command-line. This seems goofy. It would
5715 ** be better if all commands ran in the order that they appear. But
5716 ** we retain the goofy behavior for historical compatibility. */
5717 if( i
==argc
-1 ) break;
5718 z
= cmdline_option_value(argc
,argv
,++i
);
5720 rc
= do_meta_command(z
, &data
);
5721 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
5724 rc
= shell_exec(data
.db
, z
, shell_callback
, &data
, &zErrMsg
);
5726 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
5727 if( bail_on_error
) return rc
!=0 ? rc
: 1;
5729 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
5730 if( bail_on_error
) return rc
;
5734 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
5735 raw_printf(stderr
,"Use -help for a list of options.\n");
5738 data
.cMode
= data
.mode
;
5742 /* Run all arguments that do not begin with '-' as if they were separate
5743 ** command-line inputs, except for the argToSkip argument which contains
5744 ** the database filename.
5746 for(i
=0; i
<nCmd
; i
++){
5747 if( azCmd
[i
][0]=='.' ){
5748 rc
= do_meta_command(azCmd
[i
], &data
);
5749 if( rc
) return rc
==2 ? 0 : rc
;
5752 rc
= shell_exec(data
.db
, azCmd
[i
], shell_callback
, &data
, &zErrMsg
);
5754 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
5755 return rc
!=0 ? rc
: 1;
5757 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
5764 /* Run commands received from standard input
5766 if( stdin_is_interactive
){
5771 "SQLite version %s %.19s\n" /*extra-version-info*/
5772 "Enter \".help\" for usage hints.\n",
5773 sqlite3_libversion(), sqlite3_sourceid()
5775 if( warnInmemoryDb
){
5776 printf("Connected to a ");
5777 printBold("transient in-memory database");
5778 printf(".\nUse \".open FILENAME\" to reopen on a "
5779 "persistent database.\n");
5781 zHome
= find_home_dir(0);
5783 nHistory
= strlen30(zHome
) + 20;
5784 if( (zHistory
= malloc(nHistory
))!=0 ){
5785 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
5788 if( zHistory
){ shell_read_history(zHistory
); }
5789 rc
= process_input(&data
, 0);
5791 shell_stifle_history(100);
5792 shell_write_history(zHistory
);
5796 rc
= process_input(&data
, stdin
);
5799 set_table_name(&data
, 0);
5801 session_close_all(&data
);
5802 sqlite3_close(data
.db
);
5804 sqlite3_free(data
.zFreeOnClose
);
5806 #if !SQLITE_SHELL_IS_UTF8
5807 for(i
=0; i
<argc
; i
++) sqlite3_free(argv
[i
]);