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 ** Enable large-file support for fopen() and friends on unix.
23 #ifndef SQLITE_DISABLE_LFS
24 # define _LARGE_FILE 1
25 # ifndef _FILE_OFFSET_BITS
26 # define _FILE_OFFSET_BITS 64
28 # define _LARGEFILE_SOURCE 1
39 #if !defined(_WIN32) && !defined(WIN32)
41 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
45 # include <sys/types.h>
49 # include <editline/editline.h>
51 #if defined(HAVE_READLINE) && HAVE_READLINE==1
52 # include <readline/readline.h>
53 # include <readline/history.h>
55 #if !defined(HAVE_EDITLINE) && (!defined(HAVE_READLINE) || HAVE_READLINE!=1)
56 # define readline(p) local_getline(p,stdin,0)
57 # define add_history(X)
58 # define read_history(X)
59 # define write_history(X)
60 # define stifle_history(X)
63 #if defined(_WIN32) || defined(WIN32)
65 #define isatty(h) _isatty(h)
66 #define access(f,m) _access((f),(m))
68 #define popen(a,b) _popen((a),(b))
70 #define pclose(x) _pclose(x)
72 /* Make sure isatty() has a prototype.
74 extern int isatty(int);
77 #if defined(_WIN32_WCE)
78 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
79 * thus we always assume that we have a console. That can be
80 * overridden with the -batch command line option.
85 /* True if the timer is enabled */
86 static int enableTimer = 0;
88 /* ctype macros that work with signed characters */
89 #define IsSpace(X) isspace((unsigned char)X)
90 #define IsDigit(X) isdigit((unsigned char)X)
91 #define ToLower(X) (char)tolower((unsigned char)X)
93 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WRS_KERNEL)
95 #include <sys/resource.h>
97 /* Saved resource information for the beginning of an operation */
98 static struct rusage sBegin;
101 ** Begin timing an operation
103 static void beginTimer(void){
105 getrusage(RUSAGE_SELF, &sBegin);
109 /* Return the difference of two time_structs in seconds */
110 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
111 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
112 (double)(pEnd->tv_sec - pStart->tv_sec);
116 ** Print the timing results.
118 static void endTimer(void){
121 getrusage(RUSAGE_SELF, &sEnd);
122 printf("CPU Time: user %f sys %f\n",
123 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
124 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
128 #define BEGIN_TIMER beginTimer()
129 #define END_TIMER endTimer()
132 #elif (defined(_WIN32) || defined(WIN32))
136 /* Saved resource information for the beginning of an operation */
137 static HANDLE hProcess;
138 static FILETIME ftKernelBegin;
139 static FILETIME ftUserBegin;
140 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
141 static GETPROCTIMES getProcessTimesAddr = NULL;
144 ** Check to see if we have timer support. Return 1 if necessary
145 ** support found (or found previously).
147 static int hasTimer(void){
148 if( getProcessTimesAddr ){
151 /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions.
152 ** See if the version we are running on has it, and if it does, save off
153 ** a pointer to it and the current process handle.
155 hProcess = GetCurrentProcess();
157 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
158 if( NULL != hinstLib ){
159 getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
160 if( NULL != getProcessTimesAddr ){
163 FreeLibrary(hinstLib);
171 ** Begin timing an operation
173 static void beginTimer(void){
174 if( enableTimer && getProcessTimesAddr ){
175 FILETIME ftCreation, ftExit;
176 getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
180 /* Return the difference of two FILETIME structs in seconds */
181 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
182 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
183 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
184 return (double) ((i64End - i64Start) / 10000000.0);
188 ** Print the timing results.
190 static void endTimer(void){
191 if( enableTimer && getProcessTimesAddr){
192 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
193 getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
194 printf("CPU Time: user %f sys %f\n",
195 timeDiff(&ftUserBegin, &ftUserEnd),
196 timeDiff(&ftKernelBegin, &ftKernelEnd));
200 #define BEGIN_TIMER beginTimer()
201 #define END_TIMER endTimer()
202 #define HAS_TIMER hasTimer()
211 ** Used to prevent warnings about unused parameters
213 #define UNUSED_PARAMETER(x) (void)(x)
216 ** If the following flag is set, then command execution stops
217 ** at an error if we are not interactive.
219 static int bail_on_error = 0;
222 ** Threat stdin as an interactive input if the following variable
223 ** is true. Otherwise, assume stdin is connected to a file or pipe.
225 static int stdin_is_interactive = 1;
228 ** The following is the open SQLite database. We make a pointer
229 ** to this database a static variable so that it can be accessed
230 ** by the SIGINT handler to interrupt database processing.
232 static sqlite3 *db = 0;
235 ** True if an interrupt (Control-C) has been received.
237 static volatile int seenInterrupt = 0;
240 ** This is the name of our program. It is set in main(), used
241 ** in a number of other places, mostly for error messages.
246 ** Prompt strings. Initialized in main. Settable with
247 ** .prompt main continue
249 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
250 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
253 ** Write I/O traces to the following stream.
255 #ifdef SQLITE_ENABLE_IOTRACE
256 static FILE *iotrace = 0;
260 ** This routine works like printf in that its first argument is a
261 ** format string and subsequent arguments are values to be substituted
262 ** in place of % fields. The result of formatting this string
263 ** is written to iotrace.
265 #ifdef SQLITE_ENABLE_IOTRACE
266 static void iotracePrintf(const char *zFormat, ...){
269 if( iotrace==0 ) return;
270 va_start(ap, zFormat);
271 z = sqlite3_vmprintf(zFormat, ap);
273 fprintf(iotrace, "%s", z);
280 ** Determines if a string is a number of not.
282 static int isNumber(const char *z, int *realnum){
283 if( *z=='-' || *z=='+' ) z++;
288 if( realnum ) *realnum = 0;
289 while( IsDigit(*z) ){ z++; }
292 if( !IsDigit(*z) ) return 0;
293 while( IsDigit(*z) ){ z++; }
294 if( realnum ) *realnum = 1;
296 if( *z=='e' || *z=='E' ){
298 if( *z=='+' || *z=='-' ) z++;
299 if( !IsDigit(*z) ) return 0;
300 while( IsDigit(*z) ){ z++; }
301 if( realnum ) *realnum = 1;
307 ** A global char* and an SQL function to access its current value
308 ** from within an SQL statement. This program used to use the
309 ** sqlite_exec_printf() API to substitue a string into an SQL statement.
310 ** The correct way to do this with sqlite3 is to use the bind API, but
311 ** since the shell is built around the callback paradigm it would be a lot
312 ** of work. Instead just use this hack, which is quite harmless.
314 static const char *zShellStatic = 0;
315 static void shellstaticFunc(
316 sqlite3_context *context,
321 assert( zShellStatic );
322 UNUSED_PARAMETER(argc);
323 UNUSED_PARAMETER(argv);
324 sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
329 ** This routine reads a line of text from FILE in, stores
330 ** the text in memory obtained from malloc() and returns a pointer
331 ** to the text. NULL is returned at end of file, or if malloc()
334 ** The interface is like "readline" but no command-line editing
337 static char *local_getline(char *zPrompt, FILE *in, int csvFlag){
343 if( zPrompt && *zPrompt ){
344 printf("%s",zPrompt);
348 zLine = malloc( nLine );
349 if( zLine==0 ) return 0;
353 nLine = nLine*2 + 100;
354 zLine = realloc(zLine, nLine);
355 if( zLine==0 ) return 0;
357 if( fgets(&zLine[n], nLine - n, in)==0 ){
366 if( zLine[n]=='"' ) inQuote = !inQuote;
369 if( n>0 && zLine[n-1]=='\n' && (!inQuote || !csvFlag) ){
371 if( n>0 && zLine[n-1]=='\r' ) n--;
376 zLine = realloc( zLine, n+1 );
381 ** Retrieve a single line of input text.
383 ** zPrior is a string of prior text retrieved. If not the empty
384 ** string, then issue a continuation prompt.
386 static char *one_input_line(const char *zPrior, FILE *in){
390 return local_getline(0, in, 0);
392 if( zPrior && zPrior[0] ){
393 zPrompt = continuePrompt;
395 zPrompt = mainPrompt;
397 zResult = readline(zPrompt);
398 #if defined(HAVE_READLINE) && HAVE_READLINE==1
399 if( zResult && *zResult ) add_history(zResult);
404 struct previous_mode_data {
405 int valid; /* Is there legit data in here? */
412 ** An pointer to an instance of this structure is passed from
413 ** the main program to the callback. This is used to communicate
414 ** state and mode information.
416 struct callback_data {
417 sqlite3 *db; /* The database */
418 int echoOn; /* True to echo input commands */
419 int statsOn; /* True to display memory stats before each finalize */
420 int cnt; /* Number of records displayed so far */
421 FILE *out; /* Write results here */
422 FILE *traceOut; /* Output for sqlite3_trace() */
423 int nErr; /* Number of errors seen */
424 int mode; /* An output mode setting */
425 int writableSchema; /* True if PRAGMA writable_schema=ON */
426 int showHeader; /* True to show column names in List or Column mode */
427 char *zDestTable; /* Name of destination table when MODE_Insert */
428 char separator[20]; /* Separator character for MODE_List */
429 int colWidth[100]; /* Requested width of each column when in column mode*/
430 int actualWidth[100]; /* Actual width of each column */
431 char nullvalue[20]; /* The text to print when a NULL comes back from
433 struct previous_mode_data explainPrev;
434 /* Holds the mode information just before
436 char outfile[FILENAME_MAX]; /* Filename for *out */
437 const char *zDbFilename; /* name of the database file */
438 const char *zVfs; /* Name of VFS to use */
439 sqlite3_stmt *pStmt; /* Current statement if any. */
440 FILE *pLog; /* Write log output here */
444 ** These are the allowed modes.
446 #define MODE_Line 0 /* One column per line. Blank line between records */
447 #define MODE_Column 1 /* One record per line in neat columns */
448 #define MODE_List 2 /* One record per line with a separator */
449 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
450 #define MODE_Html 4 /* Generate an XHTML table */
451 #define MODE_Insert 5 /* Generate SQL "insert" statements */
452 #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
453 #define MODE_Csv 7 /* Quote strings, numbers are plain */
454 #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
456 static const char *modeDescr[] = {
469 ** Number of elements in an array
471 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
474 ** Compute a string length that is limited to what can be stored in
475 ** lower 30 bits of a 32-bit signed integer.
477 static int strlen30(const char *z){
479 while( *z2 ){ z2++; }
480 return 0x3fffffff & (int)(z2 - z);
484 ** A callback for the sqlite3_log() interface.
486 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
487 struct callback_data *p = (struct callback_data*)pArg;
488 if( p->pLog==0 ) return;
489 fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
494 ** Output the given string as a hex-encoded blob (eg. X'1234' )
496 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
498 char *zBlob = (char *)pBlob;
500 for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]&0xff); }
505 ** Output the given string as a quoted string using SQL quoting conventions.
507 static void output_quoted_string(FILE *out, const char *z){
511 if( z[i]=='\'' ) nSingle++;
514 fprintf(out,"'%s'",z);
518 for(i=0; z[i] && z[i]!='\''; i++){}
522 }else if( z[i]=='\'' ){
523 fprintf(out,"%.*s''",i,z);
535 ** Output the given string as a quoted according to C or TCL quoting rules.
537 static void output_c_string(FILE *out, const char *z){
540 while( (c = *(z++))!=0 ){
553 }else if( !isprint(c) ){
554 fprintf(out, "\\%03o", c&0xff);
563 ** Output the given string with characters that are special to
566 static void output_html_string(FILE *out, const char *z){
577 fprintf(out,"%.*s",i,z);
581 }else if( z[i]=='&' ){
582 fprintf(out,"&");
583 }else if( z[i]=='>' ){
585 }else if( z[i]=='\"' ){
586 fprintf(out,""");
587 }else if( z[i]=='\'' ){
588 fprintf(out,"'");
597 ** If a field contains any character identified by a 1 in the following
598 ** array, then the string must be quoted for CSV.
600 static const char needCsvQuote[] = {
601 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
602 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
603 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
604 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
605 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
606 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
607 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
608 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
609 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
610 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
611 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
612 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
613 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
614 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
615 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
616 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
620 ** Output a single term of CSV. Actually, p->separator is used for
621 ** the separator, which may or may not be a comma. p->nullvalue is
622 ** the null value. Strings are quoted if necessary.
624 static void output_csv(struct callback_data *p, const char *z, int bSep){
627 fprintf(out,"%s",p->nullvalue);
630 int nSep = strlen30(p->separator);
632 if( needCsvQuote[((unsigned char*)z)[i]]
633 || (z[i]==p->separator[0] &&
634 (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
642 if( z[i]=='"' ) putc('"', out);
647 fprintf(out, "%s", z);
651 fprintf(p->out, "%s", p->separator);
657 ** This routine runs when the user presses Ctrl-C
659 static void interrupt_handler(int NotUsed){
660 UNUSED_PARAMETER(NotUsed);
662 if( db ) sqlite3_interrupt(db);
667 ** This is the callback routine that the shell
668 ** invokes for each row of a query result.
670 static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){
672 struct callback_data *p = (struct callback_data*)pArg;
677 if( azArg==0 ) break;
678 for(i=0; i<nArg; i++){
679 int len = strlen30(azCol[i] ? azCol[i] : "");
682 if( p->cnt++>0 ) fprintf(p->out,"\n");
683 for(i=0; i<nArg; i++){
684 fprintf(p->out,"%*s = %s\n", w, azCol[i],
685 azArg[i] ? azArg[i] : p->nullvalue);
692 for(i=0; i<nArg; i++){
694 if( i<ArraySize(p->colWidth) ){
700 w = strlen30(azCol[i] ? azCol[i] : "");
702 n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue);
705 if( i<ArraySize(p->actualWidth) ){
706 p->actualWidth[i] = w;
709 fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " ");
713 for(i=0; i<nArg; i++){
715 if( i<ArraySize(p->actualWidth) ){
716 w = p->actualWidth[i];
720 fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
721 "----------------------------------------------------------",
722 i==nArg-1 ? "\n": " ");
726 if( azArg==0 ) break;
727 for(i=0; i<nArg; i++){
729 if( i<ArraySize(p->actualWidth) ){
730 w = p->actualWidth[i];
734 if( p->mode==MODE_Explain && azArg[i] &&
735 strlen30(azArg[i])>w ){
736 w = strlen30(azArg[i]);
738 fprintf(p->out,"%-*.*s%s",w,w,
739 azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
745 if( p->cnt++==0 && p->showHeader ){
746 for(i=0; i<nArg; i++){
747 fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
750 if( azArg==0 ) break;
751 for(i=0; i<nArg; i++){
753 if( z==0 ) z = p->nullvalue;
754 fprintf(p->out, "%s", z);
756 fprintf(p->out, "%s", p->separator);
757 }else if( p->mode==MODE_Semi ){
758 fprintf(p->out, ";\n");
760 fprintf(p->out, "\n");
766 if( p->cnt++==0 && p->showHeader ){
767 fprintf(p->out,"<TR>");
768 for(i=0; i<nArg; i++){
769 fprintf(p->out,"<TH>");
770 output_html_string(p->out, azCol[i]);
771 fprintf(p->out,"</TH>\n");
773 fprintf(p->out,"</TR>\n");
775 if( azArg==0 ) break;
776 fprintf(p->out,"<TR>");
777 for(i=0; i<nArg; i++){
778 fprintf(p->out,"<TD>");
779 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
780 fprintf(p->out,"</TD>\n");
782 fprintf(p->out,"</TR>\n");
786 if( p->cnt++==0 && p->showHeader ){
787 for(i=0; i<nArg; i++){
788 output_c_string(p->out,azCol[i] ? azCol[i] : "");
789 fprintf(p->out, "%s", p->separator);
791 fprintf(p->out,"\n");
793 if( azArg==0 ) break;
794 for(i=0; i<nArg; i++){
795 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
796 fprintf(p->out, "%s", p->separator);
798 fprintf(p->out,"\n");
802 if( p->cnt++==0 && p->showHeader ){
803 for(i=0; i<nArg; i++){
804 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
806 fprintf(p->out,"\n");
808 if( azArg==0 ) break;
809 for(i=0; i<nArg; i++){
810 output_csv(p, azArg[i], i<nArg-1);
812 fprintf(p->out,"\n");
817 if( azArg==0 ) break;
818 fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
819 for(i=0; i<nArg; i++){
820 char *zSep = i>0 ? ",": "";
821 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
822 fprintf(p->out,"%sNULL",zSep);
823 }else if( aiType && aiType[i]==SQLITE_TEXT ){
824 if( zSep[0] ) fprintf(p->out,"%s",zSep);
825 output_quoted_string(p->out, azArg[i]);
826 }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){
827 fprintf(p->out,"%s%s",zSep, azArg[i]);
828 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
829 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
830 int nBlob = sqlite3_column_bytes(p->pStmt, i);
831 if( zSep[0] ) fprintf(p->out,"%s",zSep);
832 output_hex_blob(p->out, pBlob, nBlob);
833 }else if( isNumber(azArg[i], 0) ){
834 fprintf(p->out,"%s%s",zSep, azArg[i]);
836 if( zSep[0] ) fprintf(p->out,"%s",zSep);
837 output_quoted_string(p->out, azArg[i]);
840 fprintf(p->out,");\n");
848 ** This is the callback routine that the SQLite library
849 ** invokes for each row of a query result.
851 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
852 /* since we don't have type info, call the shell_callback with a NULL value */
853 return shell_callback(pArg, nArg, azArg, azCol, NULL);
857 ** Set the destination table field of the callback_data structure to
858 ** the name of the table given. Escape any quote characters in the
861 static void set_table_name(struct callback_data *p, const char *zName){
870 if( zName==0 ) return;
871 needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
872 for(i=n=0; zName[i]; i++, n++){
873 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
875 if( zName[i]=='\'' ) n++;
878 if( needQuote ) n += 2;
879 z = p->zDestTable = malloc( n+1 );
881 fprintf(stderr,"Error: out of memory\n");
885 if( needQuote ) z[n++] = '\'';
886 for(i=0; zName[i]; i++){
888 if( zName[i]=='\'' ) z[n++] = '\'';
890 if( needQuote ) z[n++] = '\'';
894 /* zIn is either a pointer to a NULL-terminated string in memory obtained
895 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
896 ** added to zIn, and the result returned in memory obtained from malloc().
897 ** zIn, if it was not NULL, is freed.
899 ** If the third argument, quote, is not '\0', then it is used as a
900 ** quote character for zAppend.
902 static char *appendText(char *zIn, char const *zAppend, char quote){
905 int nAppend = strlen30(zAppend);
906 int nIn = (zIn?strlen30(zIn):0);
911 for(i=0; i<nAppend; i++){
912 if( zAppend[i]==quote ) len++;
916 zIn = (char *)realloc(zIn, len);
922 char *zCsr = &zIn[nIn];
924 for(i=0; i<nAppend; i++){
925 *zCsr++ = zAppend[i];
926 if( zAppend[i]==quote ) *zCsr++ = quote;
930 assert( (zCsr-zIn)==len );
932 memcpy(&zIn[nIn], zAppend, nAppend);
941 ** Execute a query statement that will generate SQL output. Print
942 ** the result columns, comma-separated, on a line and then add a
943 ** semicolon terminator to the end of that line.
945 ** If the number of columns is 1 and that column contains text "--"
946 ** then write the semicolon on a separate line. That way, if a
947 ** "--" comment occurs at the end of the statement, the comment
948 ** won't consume the semicolon terminator.
950 static int run_table_dump_query(
951 struct callback_data *p, /* Query context */
952 const char *zSelect, /* SELECT statement to extract content */
953 const char *zFirstRow /* Print before first row, if not NULL */
955 sqlite3_stmt *pSelect;
960 rc = sqlite3_prepare(p->db, zSelect, -1, &pSelect, 0);
961 if( rc!=SQLITE_OK || !pSelect ){
962 fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
966 rc = sqlite3_step(pSelect);
967 nResult = sqlite3_column_count(pSelect);
968 while( rc==SQLITE_ROW ){
970 fprintf(p->out, "%s", zFirstRow);
973 z = (const char*)sqlite3_column_text(pSelect, 0);
974 fprintf(p->out, "%s", z);
975 for(i=1; i<nResult; i++){
976 fprintf(p->out, ",%s", sqlite3_column_text(pSelect, i));
979 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
981 fprintf(p->out, "\n;\n");
983 fprintf(p->out, ";\n");
985 rc = sqlite3_step(pSelect);
987 rc = sqlite3_finalize(pSelect);
989 fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
996 ** Allocate space and save off current error string.
998 static char *save_err_msg(
999 sqlite3 *db /* Database to query */
1001 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
1002 char *zErrMsg = sqlite3_malloc(nErrMsg);
1004 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
1010 ** Display memory stats.
1012 static int display_stats(
1013 sqlite3 *db, /* Database to query */
1014 struct callback_data *pArg, /* Pointer to struct callback_data */
1015 int bReset /* True to reset the stats */
1020 if( pArg && pArg->out ){
1023 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
1024 fprintf(pArg->out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr);
1026 sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
1027 fprintf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr);
1029 ** Not currently used by the CLI.
1030 ** iHiwtr = iCur = -1;
1031 ** sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
1032 ** fprintf(pArg->out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr);
1035 sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
1036 fprintf(pArg->out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr);
1038 ** Not currently used by the CLI.
1039 ** iHiwtr = iCur = -1;
1040 ** sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
1041 ** fprintf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr);
1044 sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
1045 fprintf(pArg->out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr);
1047 sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
1048 fprintf(pArg->out, "Largest Allocation: %d bytes\n", iHiwtr);
1050 sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
1051 fprintf(pArg->out, "Largest Pcache Allocation: %d bytes\n", iHiwtr);
1053 sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
1054 fprintf(pArg->out, "Largest Scratch Allocation: %d bytes\n", iHiwtr);
1055 #ifdef YYTRACKMAXSTACKDEPTH
1057 sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
1058 fprintf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr);
1062 if( pArg && pArg->out && db ){
1064 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset);
1065 fprintf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr);
1066 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset);
1067 fprintf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr);
1068 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset);
1069 fprintf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr);
1070 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset);
1071 fprintf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr);
1073 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
1074 fprintf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1;
1075 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
1076 fprintf(pArg->out, "Page cache hits: %d\n", iCur);
1078 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
1079 fprintf(pArg->out, "Page cache misses: %d\n", iCur);
1081 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
1082 fprintf(pArg->out, "Page cache writes: %d\n", iCur);
1084 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
1085 fprintf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur);
1087 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
1088 fprintf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur);
1091 if( pArg && pArg->out && db && pArg->pStmt ){
1092 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset);
1093 fprintf(pArg->out, "Fullscan Steps: %d\n", iCur);
1094 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
1095 fprintf(pArg->out, "Sort Operations: %d\n", iCur);
1096 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset);
1097 fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur);
1104 ** Execute a statement or set of statements. Print
1105 ** any result rows/columns depending on the current mode
1106 ** set via the supplied callback.
1108 ** This is very similar to SQLite's built-in sqlite3_exec()
1109 ** function except it takes a slightly different callback
1110 ** and callback data argument.
1112 static int shell_exec(
1113 sqlite3 *db, /* An open database */
1114 const char *zSql, /* SQL to be evaluated */
1115 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
1116 /* (not the same as sqlite3_exec) */
1117 struct callback_data *pArg, /* Pointer to struct callback_data */
1118 char **pzErrMsg /* Error msg written here */
1120 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
1121 int rc = SQLITE_OK; /* Return Code */
1123 const char *zLeftover; /* Tail of unprocessed SQL */
1129 while( zSql[0] && (SQLITE_OK == rc) ){
1130 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
1131 if( SQLITE_OK != rc ){
1133 *pzErrMsg = save_err_msg(db);
1137 /* this happens for a comment or white-space */
1139 while( IsSpace(zSql[0]) ) zSql++;
1143 /* save off the prepared statment handle and reset row count */
1145 pArg->pStmt = pStmt;
1149 /* echo the sql statement if echo on */
1150 if( pArg && pArg->echoOn ){
1151 const char *zStmtSql = sqlite3_sql(pStmt);
1152 fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
1155 /* Output TESTCTRL_EXPLAIN text of requested */
1156 if( pArg && pArg->mode==MODE_Explain ){
1157 const char *zExplain = 0;
1158 sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain);
1159 if( zExplain && zExplain[0] ){
1160 fprintf(pArg->out, "%s", zExplain);
1164 /* perform the first step. this will tell us if we
1165 ** have a result set or not and how wide it is.
1167 rc = sqlite3_step(pStmt);
1168 /* if we have a result set... */
1169 if( SQLITE_ROW == rc ){
1170 /* if we have a callback... */
1172 /* allocate space for col name ptr, value ptr, and type */
1173 int nCol = sqlite3_column_count(pStmt);
1174 void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
1178 char **azCols = (char **)pData; /* Names of result columns */
1179 char **azVals = &azCols[nCol]; /* Results */
1180 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
1182 assert(sizeof(int) <= sizeof(char *));
1183 /* save off ptrs to column names */
1184 for(i=0; i<nCol; i++){
1185 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
1188 /* extract the data and data types */
1189 for(i=0; i<nCol; i++){
1190 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
1191 aiTypes[i] = sqlite3_column_type(pStmt, i);
1192 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
1194 break; /* from for */
1198 /* if data and types extracted successfully... */
1199 if( SQLITE_ROW == rc ){
1200 /* call the supplied callback with the result row data */
1201 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
1204 rc = sqlite3_step(pStmt);
1207 } while( SQLITE_ROW == rc );
1208 sqlite3_free(pData);
1212 rc = sqlite3_step(pStmt);
1213 } while( rc == SQLITE_ROW );
1217 /* print usage stats if stats on */
1218 if( pArg && pArg->statsOn ){
1219 display_stats(db, pArg, 0);
1222 /* Finalize the statement just executed. If this fails, save a
1223 ** copy of the error message. Otherwise, set zSql to point to the
1224 ** next statement to execute. */
1225 rc2 = sqlite3_finalize(pStmt);
1226 if( rc!=SQLITE_NOMEM ) rc = rc2;
1227 if( rc==SQLITE_OK ){
1229 while( IsSpace(zSql[0]) ) zSql++;
1230 }else if( pzErrMsg ){
1231 *pzErrMsg = save_err_msg(db);
1234 /* clear saved stmt handle */
1246 ** This is a different callback routine used for dumping the database.
1247 ** Each row received by this callback consists of a table name,
1248 ** the table type ("index" or "table") and SQL to create the table.
1249 ** This routine should print text sufficient to recreate the table.
1251 static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
1256 const char *zPrepStmt = 0;
1257 struct callback_data *p = (struct callback_data *)pArg;
1259 UNUSED_PARAMETER(azCol);
1260 if( nArg!=3 ) return 1;
1265 if( strcmp(zTable, "sqlite_sequence")==0 ){
1266 zPrepStmt = "DELETE FROM sqlite_sequence;\n";
1267 }else if( strcmp(zTable, "sqlite_stat1")==0 ){
1268 fprintf(p->out, "ANALYZE sqlite_master;\n");
1269 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
1271 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
1273 if( !p->writableSchema ){
1274 fprintf(p->out, "PRAGMA writable_schema=ON;\n");
1275 p->writableSchema = 1;
1277 zIns = sqlite3_mprintf(
1278 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
1279 "VALUES('table','%q','%q',0,'%q');",
1280 zTable, zTable, zSql);
1281 fprintf(p->out, "%s\n", zIns);
1285 fprintf(p->out, "%s;\n", zSql);
1288 if( strcmp(zType, "table")==0 ){
1289 sqlite3_stmt *pTableInfo = 0;
1291 char *zTableInfo = 0;
1295 zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
1296 zTableInfo = appendText(zTableInfo, zTable, '"');
1297 zTableInfo = appendText(zTableInfo, ");", 0);
1299 rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
1301 if( rc!=SQLITE_OK || !pTableInfo ){
1305 zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
1306 /* Always quote the table name, even if it appears to be pure ascii,
1307 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
1308 zTmp = appendText(zTmp, zTable, '"');
1310 zSelect = appendText(zSelect, zTmp, '\'');
1313 zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
1314 rc = sqlite3_step(pTableInfo);
1315 while( rc==SQLITE_ROW ){
1316 const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
1317 zSelect = appendText(zSelect, "quote(", 0);
1318 zSelect = appendText(zSelect, zText, '"');
1319 rc = sqlite3_step(pTableInfo);
1320 if( rc==SQLITE_ROW ){
1321 zSelect = appendText(zSelect, "), ", 0);
1323 zSelect = appendText(zSelect, ") ", 0);
1327 rc = sqlite3_finalize(pTableInfo);
1328 if( rc!=SQLITE_OK || nRow==0 ){
1332 zSelect = appendText(zSelect, "|| ')' FROM ", 0);
1333 zSelect = appendText(zSelect, zTable, '"');
1335 rc = run_table_dump_query(p, zSelect, zPrepStmt);
1336 if( rc==SQLITE_CORRUPT ){
1337 zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
1338 run_table_dump_query(p, zSelect, 0);
1346 ** Run zQuery. Use dump_callback() as the callback routine so that
1347 ** the contents of the query are output as SQL statements.
1349 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
1350 ** "ORDER BY rowid DESC" to the end.
1352 static int run_schema_dump_query(
1353 struct callback_data *p,
1358 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
1359 if( rc==SQLITE_CORRUPT ){
1361 int len = strlen30(zQuery);
1362 fprintf(p->out, "/****** CORRUPTION ERROR *******/\n");
1364 fprintf(p->out, "/****** %s ******/\n", zErr);
1368 zQ2 = malloc( len+100 );
1369 if( zQ2==0 ) return rc;
1370 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
1371 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
1373 fprintf(p->out, "/****** ERROR: %s ******/\n", zErr);
1375 rc = SQLITE_CORRUPT;
1384 ** Text of a help message
1386 static char zHelp[] =
1387 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
1388 ".bail ON|OFF Stop after hitting an error. Default OFF\n"
1389 ".databases List names and files of attached databases\n"
1390 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
1391 " If TABLE specified, only dump tables matching\n"
1392 " LIKE pattern TABLE.\n"
1393 ".echo ON|OFF Turn command echo on or off\n"
1394 ".exit Exit this program\n"
1395 ".explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off.\n"
1396 " With no args, it turns EXPLAIN on.\n"
1397 ".header(s) ON|OFF Turn display of headers on or off\n"
1398 ".help Show this message\n"
1399 ".import FILE TABLE Import data from FILE into TABLE\n"
1400 ".indices ?TABLE? Show names of all indices\n"
1401 " If TABLE specified, only show indices for tables\n"
1402 " matching LIKE pattern TABLE.\n"
1403 #ifdef SQLITE_ENABLE_IOTRACE
1404 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
1406 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1407 ".load FILE ?ENTRY? Load an extension library\n"
1409 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
1410 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
1411 " csv Comma-separated values\n"
1412 " column Left-aligned columns. (See .width)\n"
1413 " html HTML <table> code\n"
1414 " insert SQL insert statements for TABLE\n"
1415 " line One value per line\n"
1416 " list Values delimited by .separator string\n"
1417 " tabs Tab-separated values\n"
1418 " tcl TCL list elements\n"
1419 ".nullvalue STRING Print STRING in place of NULL values\n"
1420 ".output FILENAME Send output to FILENAME\n"
1421 ".output stdout Send output to the screen\n"
1422 ".prompt MAIN CONTINUE Replace the standard prompts\n"
1423 ".quit Exit this program\n"
1424 ".read FILENAME Execute SQL in FILENAME\n"
1425 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
1426 ".schema ?TABLE? Show the CREATE statements\n"
1427 " If TABLE specified, only show tables matching\n"
1428 " LIKE pattern TABLE.\n"
1429 ".separator STRING Change separator used by output mode and .import\n"
1430 ".show Show the current values for various settings\n"
1431 ".stats ON|OFF Turn stats on or off\n"
1432 ".tables ?TABLE? List names of tables\n"
1433 " If TABLE specified, only list tables matching\n"
1434 " LIKE pattern TABLE.\n"
1435 ".timeout MS Try opening locked tables for MS milliseconds\n"
1436 ".trace FILE|off Output each SQL statement as it is run\n"
1437 ".vfsname ?AUX? Print the name of the VFS stack\n"
1438 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
1441 static char zTimerHelp[] =
1442 ".timer ON|OFF Turn the CPU timer measurement on or off\n"
1445 /* Forward reference */
1446 static int process_input(struct callback_data *p, FILE *in);
1449 ** Make sure the database is open. If it is not, then open it. If
1450 ** the database fails to open, print an error message and exit.
1452 static void open_db(struct callback_data *p){
1454 sqlite3_initialize();
1455 sqlite3_open(p->zDbFilename, &p->db);
1457 if( db && sqlite3_errcode(db)==SQLITE_OK ){
1458 sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
1459 shellstaticFunc, 0, 0);
1461 if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
1462 fprintf(stderr,"Error: unable to open database \"%s\": %s\n",
1463 p->zDbFilename, sqlite3_errmsg(db));
1466 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1467 sqlite3_enable_load_extension(p->db, 1);
1473 ** Do C-language style dequoting.
1477 ** \r -> carriage return
1478 ** \NNN -> ascii character NNN in octal
1481 static void resolve_backslashes(char *z){
1484 for(i=j=0; (c = z[i])!=0; i++, j++){
1493 }else if( c>='0' && c<='7' ){
1495 if( z[i+1]>='0' && z[i+1]<='7' ){
1497 c = (c<<3) + z[i] - '0';
1498 if( z[i+1]>='0' && z[i+1]<='7' ){
1500 c = (c<<3) + z[i] - '0';
1511 ** Interpret zArg as a boolean value. Return either 0 or 1.
1513 static int booleanValue(char *zArg){
1514 int val = atoi(zArg);
1516 for(j=0; zArg[j]; j++){
1517 zArg[j] = ToLower(zArg[j]);
1519 if( strcmp(zArg,"on")==0 ){
1521 }else if( strcmp(zArg,"yes")==0 ){
1528 ** Close an output file, assuming it is not stderr or stdout
1530 static void output_file_close(FILE *f){
1531 if( f && f!=stdout && f!=stderr ) fclose(f);
1535 ** Try to open an output file. The names "stdout" and "stderr" are
1536 ** recognized and do the right thing. NULL is returned if the output
1537 ** filename is "off".
1539 static FILE *output_file_open(const char *zFile){
1541 if( strcmp(zFile,"stdout")==0 ){
1543 }else if( strcmp(zFile, "stderr")==0 ){
1545 }else if( strcmp(zFile, "off")==0 ){
1548 f = fopen(zFile, "wb");
1550 fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
1557 ** A routine for handling output from sqlite3_trace().
1559 static void sql_trace_callback(void *pArg, const char *z){
1560 FILE *f = (FILE*)pArg;
1561 if( f ) fprintf(f, "%s\n", z);
1565 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
1566 ** a useful spot to set a debugger breakpoint.
1568 static void test_breakpoint(void){
1569 static int nCall = 0;
1574 ** If an input line begins with "." then invoke this routine to
1575 ** process that line.
1577 ** Return 1 on error, 2 to exit, and 0 otherwise.
1579 static int do_meta_command(char *zLine, struct callback_data *p){
1586 /* Parse the input line into tokens.
1588 while( zLine[i] && nArg<ArraySize(azArg) ){
1589 while( IsSpace(zLine[i]) ){ i++; }
1590 if( zLine[i]==0 ) break;
1591 if( zLine[i]=='\'' || zLine[i]=='"' ){
1592 int delim = zLine[i++];
1593 azArg[nArg++] = &zLine[i];
1594 while( zLine[i] && zLine[i]!=delim ){ i++; }
1595 if( zLine[i]==delim ){
1598 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
1600 azArg[nArg++] = &zLine[i];
1601 while( zLine[i] && !IsSpace(zLine[i]) ){ i++; }
1602 if( zLine[i] ) zLine[i++] = 0;
1603 resolve_backslashes(azArg[nArg-1]);
1607 /* Process the input line.
1609 if( nArg==0 ) return 0; /* no tokens, no error */
1610 n = strlen30(azArg[0]);
1612 if( c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0 && nArg>1 && nArg<4){
1613 const char *zDestFile;
1616 sqlite3_backup *pBackup;
1618 zDestFile = azArg[1];
1621 zDestFile = azArg[2];
1624 rc = sqlite3_open(zDestFile, &pDest);
1625 if( rc!=SQLITE_OK ){
1626 fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
1627 sqlite3_close(pDest);
1631 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
1633 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
1634 sqlite3_close(pDest);
1637 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1638 sqlite3_backup_finish(pBackup);
1639 if( rc==SQLITE_DONE ){
1642 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
1645 sqlite3_close(pDest);
1648 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){
1649 bail_on_error = booleanValue(azArg[1]);
1652 /* The undocumented ".breakpoint" command causes a call to the no-op
1653 ** routine named test_breakpoint().
1655 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
1659 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){
1660 struct callback_data data;
1663 memcpy(&data, p, sizeof(data));
1664 data.showHeader = 1;
1665 data.mode = MODE_Column;
1666 data.colWidth[0] = 3;
1667 data.colWidth[1] = 15;
1668 data.colWidth[2] = 58;
1670 sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
1672 fprintf(stderr,"Error: %s\n", zErrMsg);
1673 sqlite3_free(zErrMsg);
1678 if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){
1680 /* When playing back a "dump", the content might appear in an order
1681 ** which causes immediate foreign key constraints to be violated.
1682 ** So disable foreign-key constraint enforcement to prevent problems. */
1683 fprintf(p->out, "PRAGMA foreign_keys=OFF;\n");
1684 fprintf(p->out, "BEGIN TRANSACTION;\n");
1685 p->writableSchema = 0;
1686 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
1689 run_schema_dump_query(p,
1690 "SELECT name, type, sql FROM sqlite_master "
1691 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
1693 run_schema_dump_query(p,
1694 "SELECT name, type, sql FROM sqlite_master "
1695 "WHERE name=='sqlite_sequence'"
1697 run_table_dump_query(p,
1698 "SELECT sql FROM sqlite_master "
1699 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
1703 for(i=1; i<nArg; i++){
1704 zShellStatic = azArg[i];
1705 run_schema_dump_query(p,
1706 "SELECT name, type, sql FROM sqlite_master "
1707 "WHERE tbl_name LIKE shellstatic() AND type=='table'"
1708 " AND sql NOT NULL");
1709 run_table_dump_query(p,
1710 "SELECT sql FROM sqlite_master "
1711 "WHERE sql NOT NULL"
1712 " AND type IN ('index','trigger','view')"
1713 " AND tbl_name LIKE shellstatic()", 0
1718 if( p->writableSchema ){
1719 fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
1720 p->writableSchema = 0;
1722 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
1723 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
1724 fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
1727 if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){
1728 p->echoOn = booleanValue(azArg[1]);
1731 if( c=='e' && strncmp(azArg[0], "exit", n)==0 && nArg==1 ){
1735 if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){
1736 int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
1738 if(!p->explainPrev.valid) {
1739 p->explainPrev.valid = 1;
1740 p->explainPrev.mode = p->mode;
1741 p->explainPrev.showHeader = p->showHeader;
1742 memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
1744 /* We could put this code under the !p->explainValid
1745 ** condition so that it does not execute if we are already in
1746 ** explain mode. However, always executing it allows us an easy
1747 ** was to reset to explain mode in case the user previously
1748 ** did an .explain followed by a .width, .mode or .header
1751 p->mode = MODE_Explain;
1753 memset(p->colWidth,0,ArraySize(p->colWidth));
1754 p->colWidth[0] = 4; /* addr */
1755 p->colWidth[1] = 13; /* opcode */
1756 p->colWidth[2] = 4; /* P1 */
1757 p->colWidth[3] = 4; /* P2 */
1758 p->colWidth[4] = 4; /* P3 */
1759 p->colWidth[5] = 13; /* P4 */
1760 p->colWidth[6] = 2; /* P5 */
1761 p->colWidth[7] = 13; /* Comment */
1762 }else if (p->explainPrev.valid) {
1763 p->explainPrev.valid = 0;
1764 p->mode = p->explainPrev.mode;
1765 p->showHeader = p->explainPrev.showHeader;
1766 memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
1770 if( c=='h' && (strncmp(azArg[0], "header", n)==0 ||
1771 strncmp(azArg[0], "headers", n)==0) && nArg>1 && nArg<3 ){
1772 p->showHeader = booleanValue(azArg[1]);
1775 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
1776 fprintf(stderr,"%s",zHelp);
1778 fprintf(stderr,"%s",zTimerHelp);
1782 if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){
1783 char *zTable = azArg[2]; /* Insert data into this table */
1784 char *zFile = azArg[1]; /* The file from which to extract data */
1785 sqlite3_stmt *pStmt = NULL; /* A statement */
1786 int nCol; /* Number of columns in the table */
1787 int nByte; /* Number of bytes in an SQL string */
1788 int i, j; /* Loop counters */
1789 int nSep; /* Number of bytes in p->separator[] */
1790 char *zSql; /* An SQL statement */
1791 char *zLine; /* A single line of input from the file */
1792 char **azCol; /* zLine[] broken up into columns */
1793 char *zCommit; /* How to commit changes */
1794 FILE *in; /* The input file */
1795 int lineno = 0; /* Line number of input file */
1798 nSep = strlen30(p->separator);
1800 fprintf(stderr, "Error: non-null separator required for import\n");
1803 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
1805 fprintf(stderr, "Error: out of memory\n");
1808 nByte = strlen30(zSql);
1809 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
1812 if (pStmt) sqlite3_finalize(pStmt);
1813 fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
1816 nCol = sqlite3_column_count(pStmt);
1817 sqlite3_finalize(pStmt);
1819 if( nCol==0 ) return 0; /* no columns, no error */
1820 zSql = malloc( nByte + 20 + nCol*2 );
1822 fprintf(stderr, "Error: out of memory\n");
1825 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zTable);
1827 for(i=1; i<nCol; i++){
1833 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
1836 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
1837 if (pStmt) sqlite3_finalize(pStmt);
1840 in = fopen(zFile, "rb");
1842 fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
1843 sqlite3_finalize(pStmt);
1846 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1848 fprintf(stderr, "Error: out of memory\n");
1850 sqlite3_finalize(pStmt);
1853 sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
1855 while( (zLine = local_getline(0, in, 1))!=0 ){
1860 for(i=0, z=zLine; (c = *z)!=0; z++){
1861 if( c=='"' ) inQuote = !inQuote;
1862 if( c=='\n' ) lineno++;
1863 if( !inQuote && c==p->separator[0] && strncmp(z,p->separator,nSep)==0 ){
1867 azCol[i] = &z[nSep];
1875 "Error: %s line %d: expected %d columns of data but found %d\n",
1876 zFile, lineno, nCol, i+1);
1877 zCommit = "ROLLBACK";
1880 break; /* from while */
1882 for(i=0; i<nCol; i++){
1883 if( azCol[i][0]=='"' ){
1885 for(z=azCol[i], j=1, k=0; z[j]; j++){
1886 if( z[j]=='"' ){ j++; if( z[j]==0 ) break; }
1891 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1893 sqlite3_step(pStmt);
1894 rc = sqlite3_reset(pStmt);
1896 if( rc!=SQLITE_OK ){
1897 fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
1898 zCommit = "ROLLBACK";
1900 break; /* from while */
1905 sqlite3_finalize(pStmt);
1906 sqlite3_exec(p->db, zCommit, 0, 0, 0);
1909 if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){
1910 struct callback_data data;
1913 memcpy(&data, p, sizeof(data));
1914 data.showHeader = 0;
1915 data.mode = MODE_List;
1917 rc = sqlite3_exec(p->db,
1918 "SELECT name FROM sqlite_master "
1919 "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
1921 "SELECT name FROM sqlite_temp_master "
1922 "WHERE type='index' "
1924 callback, &data, &zErrMsg
1927 zShellStatic = azArg[1];
1928 rc = sqlite3_exec(p->db,
1929 "SELECT name FROM sqlite_master "
1930 "WHERE type='index' AND tbl_name LIKE shellstatic() "
1932 "SELECT name FROM sqlite_temp_master "
1933 "WHERE type='index' AND tbl_name LIKE shellstatic() "
1935 callback, &data, &zErrMsg
1940 fprintf(stderr,"Error: %s\n", zErrMsg);
1941 sqlite3_free(zErrMsg);
1943 }else if( rc != SQLITE_OK ){
1944 fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
1949 #ifdef SQLITE_ENABLE_IOTRACE
1950 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
1951 extern void (*sqlite3IoTrace)(const char*, ...);
1952 if( iotrace && iotrace!=stdout ) fclose(iotrace);
1956 }else if( strcmp(azArg[1], "-")==0 ){
1957 sqlite3IoTrace = iotracePrintf;
1960 iotrace = fopen(azArg[1], "w");
1962 fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
1966 sqlite3IoTrace = iotracePrintf;
1972 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1973 if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){
1974 const char *zFile, *zProc;
1977 zProc = nArg>=3 ? azArg[2] : 0;
1979 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
1980 if( rc!=SQLITE_OK ){
1981 fprintf(stderr, "Error: %s\n", zErrMsg);
1982 sqlite3_free(zErrMsg);
1988 if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=2 ){
1989 const char *zFile = azArg[1];
1990 output_file_close(p->pLog);
1991 p->pLog = output_file_open(zFile);
1994 if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==2 ){
1995 int n2 = strlen30(azArg[1]);
1996 if( (n2==4 && strncmp(azArg[1],"line",n2)==0)
1998 (n2==5 && strncmp(azArg[1],"lines",n2)==0) ){
1999 p->mode = MODE_Line;
2000 }else if( (n2==6 && strncmp(azArg[1],"column",n2)==0)
2002 (n2==7 && strncmp(azArg[1],"columns",n2)==0) ){
2003 p->mode = MODE_Column;
2004 }else if( n2==4 && strncmp(azArg[1],"list",n2)==0 ){
2005 p->mode = MODE_List;
2006 }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){
2007 p->mode = MODE_Html;
2008 }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){
2010 }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){
2012 sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
2013 }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){
2014 p->mode = MODE_List;
2015 sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
2016 }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
2017 p->mode = MODE_Insert;
2018 set_table_name(p, "table");
2020 fprintf(stderr,"Error: mode should be one of: "
2021 "column csv html insert line list tabs tcl\n");
2026 if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==3 ){
2027 int n2 = strlen30(azArg[1]);
2028 if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
2029 p->mode = MODE_Insert;
2030 set_table_name(p, azArg[2]);
2032 fprintf(stderr, "Error: invalid arguments: "
2033 " \"%s\". Enter \".help\" for help\n", azArg[2]);
2038 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
2039 sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
2040 "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
2043 if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
2044 if( p->outfile[0]=='|' ){
2047 output_file_close(p->out);
2050 if( azArg[1][0]=='|' ){
2051 p->out = popen(&azArg[1][1], "w");
2053 fprintf(stderr,"Error: cannot open pipe \"%s\"\n", &azArg[1][1]);
2057 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
2060 p->out = output_file_open(azArg[1]);
2062 if( strcmp(azArg[1],"off")!=0 ){
2063 fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]);
2068 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
2073 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
2075 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
2078 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
2082 if( c=='q' && strncmp(azArg[0], "quit", n)==0 && nArg==1 ){
2086 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
2087 FILE *alt = fopen(azArg[1], "rb");
2089 fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
2092 rc = process_input(p, alt);
2097 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 && nArg<4){
2098 const char *zSrcFile;
2101 sqlite3_backup *pBackup;
2105 zSrcFile = azArg[1];
2108 zSrcFile = azArg[2];
2111 rc = sqlite3_open(zSrcFile, &pSrc);
2112 if( rc!=SQLITE_OK ){
2113 fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
2114 sqlite3_close(pSrc);
2118 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
2120 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
2121 sqlite3_close(pSrc);
2124 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2125 || rc==SQLITE_BUSY ){
2126 if( rc==SQLITE_BUSY ){
2127 if( nTimeout++ >= 3 ) break;
2131 sqlite3_backup_finish(pBackup);
2132 if( rc==SQLITE_DONE ){
2134 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2135 fprintf(stderr, "Error: source database is busy\n");
2138 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
2141 sqlite3_close(pSrc);
2144 if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){
2145 struct callback_data data;
2148 memcpy(&data, p, sizeof(data));
2149 data.showHeader = 0;
2150 data.mode = MODE_Semi;
2153 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
2154 if( strcmp(azArg[1],"sqlite_master")==0 ){
2155 char *new_argv[2], *new_colv[2];
2156 new_argv[0] = "CREATE TABLE sqlite_master (\n"
2160 " rootpage integer,\n"
2164 new_colv[0] = "sql";
2166 callback(&data, 1, new_argv, new_colv);
2168 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
2169 char *new_argv[2], *new_colv[2];
2170 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
2174 " rootpage integer,\n"
2178 new_colv[0] = "sql";
2180 callback(&data, 1, new_argv, new_colv);
2183 zShellStatic = azArg[1];
2184 rc = sqlite3_exec(p->db,
2186 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
2187 " FROM sqlite_master UNION ALL"
2188 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
2189 "WHERE lower(tbl_name) LIKE shellstatic()"
2190 " AND type!='meta' AND sql NOTNULL "
2191 "ORDER BY substr(type,2,1), "
2192 " CASE type WHEN 'view' THEN rowid ELSE name END",
2193 callback, &data, &zErrMsg);
2197 rc = sqlite3_exec(p->db,
2199 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
2200 " FROM sqlite_master UNION ALL"
2201 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
2202 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
2203 "ORDER BY substr(type,2,1),"
2204 " CASE type WHEN 'view' THEN rowid ELSE name END",
2205 callback, &data, &zErrMsg
2209 fprintf(stderr,"Error: %s\n", zErrMsg);
2210 sqlite3_free(zErrMsg);
2212 }else if( rc != SQLITE_OK ){
2213 fprintf(stderr,"Error: querying schema information\n");
2220 if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
2221 sqlite3_snprintf(sizeof(p->separator), p->separator,
2222 "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
2225 if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){
2227 fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
2228 fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
2229 fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
2230 fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
2231 fprintf(p->out,"%9.9s: ", "nullvalue");
2232 output_c_string(p->out, p->nullvalue);
2233 fprintf(p->out, "\n");
2234 fprintf(p->out,"%9.9s: %s\n","output",
2235 strlen30(p->outfile) ? p->outfile : "stdout");
2236 fprintf(p->out,"%9.9s: ", "separator");
2237 output_c_string(p->out, p->separator);
2238 fprintf(p->out, "\n");
2239 fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off");
2240 fprintf(p->out,"%9.9s: ","width");
2241 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
2242 fprintf(p->out,"%d ",p->colWidth[i]);
2244 fprintf(p->out,"\n");
2247 if( c=='s' && strncmp(azArg[0], "stats", n)==0 && nArg>1 && nArg<3 ){
2248 p->statsOn = booleanValue(azArg[1]);
2251 if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){
2252 sqlite3_stmt *pStmt;
2258 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
2260 zSql = sqlite3_mprintf(
2261 "SELECT name FROM sqlite_master"
2262 " WHERE type IN ('table','view')"
2263 " AND name NOT LIKE 'sqlite_%%'"
2264 " AND name LIKE ?1");
2265 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2266 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
2267 if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue;
2268 if( strcmp(zDbName,"temp")==0 ){
2269 zSql = sqlite3_mprintf(
2271 "SELECT 'temp.' || name FROM sqlite_temp_master"
2272 " WHERE type IN ('table','view')"
2273 " AND name NOT LIKE 'sqlite_%%'"
2274 " AND name LIKE ?1", zSql);
2276 zSql = sqlite3_mprintf(
2278 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
2279 " WHERE type IN ('table','view')"
2280 " AND name NOT LIKE 'sqlite_%%'"
2281 " AND name LIKE ?1", zSql, zDbName, zDbName);
2284 sqlite3_finalize(pStmt);
2285 zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
2286 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2292 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
2294 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
2296 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2299 int n = nAlloc*2 + 10;
2300 azNew = sqlite3_realloc(azResult, sizeof(azResult[0])*n);
2302 fprintf(stderr, "Error: out of memory\n");
2308 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
2309 if( azResult[nRow] ) nRow++;
2311 sqlite3_finalize(pStmt);
2313 int len, maxlen = 0;
2315 int nPrintCol, nPrintRow;
2316 for(i=0; i<nRow; i++){
2317 len = strlen30(azResult[i]);
2318 if( len>maxlen ) maxlen = len;
2320 nPrintCol = 80/(maxlen+2);
2321 if( nPrintCol<1 ) nPrintCol = 1;
2322 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
2323 for(i=0; i<nPrintRow; i++){
2324 for(j=i; j<nRow; j+=nPrintRow){
2325 char *zSp = j<nPrintRow ? "" : " ";
2326 printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
2331 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
2332 sqlite3_free(azResult);
2335 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
2336 static const struct {
2337 const char *zCtrlName; /* Name of a test-control option */
2338 int ctrlCode; /* Integer code for that option */
2340 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
2341 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
2342 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
2343 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
2344 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
2345 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
2346 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
2347 { "assert", SQLITE_TESTCTRL_ASSERT },
2348 { "always", SQLITE_TESTCTRL_ALWAYS },
2349 { "reserve", SQLITE_TESTCTRL_RESERVE },
2350 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
2351 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
2352 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
2359 /* convert testctrl text option to value. allow any unique prefix
2360 ** of the option name, or a numerical value. */
2361 n = strlen30(azArg[1]);
2362 for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){
2363 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){
2365 testctrl = aCtrl[i].ctrlCode;
2367 fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
2373 if( testctrl<0 ) testctrl = atoi(azArg[1]);
2374 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
2375 fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
2379 /* sqlite3_test_control(int, db, int) */
2380 case SQLITE_TESTCTRL_OPTIMIZATIONS:
2381 case SQLITE_TESTCTRL_RESERVE:
2383 int opt = (int)strtol(azArg[2], 0, 0);
2384 rc = sqlite3_test_control(testctrl, p->db, opt);
2385 printf("%d (0x%08x)\n", rc, rc);
2387 fprintf(stderr,"Error: testctrl %s takes a single int option\n",
2392 /* sqlite3_test_control(int) */
2393 case SQLITE_TESTCTRL_PRNG_SAVE:
2394 case SQLITE_TESTCTRL_PRNG_RESTORE:
2395 case SQLITE_TESTCTRL_PRNG_RESET:
2397 rc = sqlite3_test_control(testctrl);
2398 printf("%d (0x%08x)\n", rc, rc);
2400 fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]);
2404 /* sqlite3_test_control(int, uint) */
2405 case SQLITE_TESTCTRL_PENDING_BYTE:
2407 unsigned int opt = (unsigned int)atoi(azArg[2]);
2408 rc = sqlite3_test_control(testctrl, opt);
2409 printf("%d (0x%08x)\n", rc, rc);
2411 fprintf(stderr,"Error: testctrl %s takes a single unsigned"
2412 " int option\n", azArg[1]);
2416 /* sqlite3_test_control(int, int) */
2417 case SQLITE_TESTCTRL_ASSERT:
2418 case SQLITE_TESTCTRL_ALWAYS:
2420 int opt = atoi(azArg[2]);
2421 rc = sqlite3_test_control(testctrl, opt);
2422 printf("%d (0x%08x)\n", rc, rc);
2424 fprintf(stderr,"Error: testctrl %s takes a single int option\n",
2429 /* sqlite3_test_control(int, char *) */
2430 #ifdef SQLITE_N_KEYWORD
2431 case SQLITE_TESTCTRL_ISKEYWORD:
2433 const char *opt = azArg[2];
2434 rc = sqlite3_test_control(testctrl, opt);
2435 printf("%d (0x%08x)\n", rc, rc);
2437 fprintf(stderr,"Error: testctrl %s takes a single char * option\n",
2443 case SQLITE_TESTCTRL_BITVEC_TEST:
2444 case SQLITE_TESTCTRL_FAULT_INSTALL:
2445 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
2446 case SQLITE_TESTCTRL_SCRATCHMALLOC:
2448 fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n",
2455 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){
2457 sqlite3_busy_timeout(p->db, atoi(azArg[1]));
2460 if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0
2463 enableTimer = booleanValue(azArg[1]);
2466 if( c=='t' && strncmp(azArg[0], "trace", n)==0 && nArg>1 ){
2468 output_file_close(p->traceOut);
2469 p->traceOut = output_file_open(azArg[1]);
2470 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2471 if( p->traceOut==0 ){
2472 sqlite3_trace(p->db, 0, 0);
2474 sqlite3_trace(p->db, sql_trace_callback, p->traceOut);
2479 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
2480 printf("SQLite %s %s\n" /*extra-version-info*/,
2481 sqlite3_libversion(), sqlite3_sourceid());
2484 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
2485 const char *zDbName = nArg==2 ? azArg[1] : "main";
2488 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
2490 printf("%s\n", zVfsName);
2491 sqlite3_free(zVfsName);
2496 if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){
2498 assert( nArg<=ArraySize(azArg) );
2499 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
2500 p->colWidth[j-1] = atoi(azArg[j]);
2505 fprintf(stderr, "Error: unknown command or invalid arguments: "
2506 " \"%s\". Enter \".help\" for help\n", azArg[0]);
2514 ** Return TRUE if a semicolon occurs anywhere in the first N characters
2517 static int _contains_semicolon(const char *z, int N){
2519 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
2524 ** Test to see if a line consists entirely of whitespace.
2526 static int _all_whitespace(const char *z){
2528 if( IsSpace(z[0]) ) continue;
2529 if( *z=='/' && z[1]=='*' ){
2531 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
2532 if( *z==0 ) return 0;
2536 if( *z=='-' && z[1]=='-' ){
2538 while( *z && *z!='\n' ){ z++; }
2539 if( *z==0 ) return 1;
2548 ** Return TRUE if the line typed in is an SQL command terminator other
2549 ** than a semi-colon. The SQL Server style "go" command is understood
2550 ** as is the Oracle "/".
2552 static int _is_command_terminator(const char *zLine){
2553 while( IsSpace(zLine[0]) ){ zLine++; };
2554 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
2555 return 1; /* Oracle */
2557 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
2558 && _all_whitespace(&zLine[2]) ){
2559 return 1; /* SQL Server */
2565 ** Return true if zSql is a complete SQL statement. Return false if it
2566 ** ends in the middle of a string literal or C-style comment.
2568 static int _is_complete(char *zSql, int nSql){
2570 if( zSql==0 ) return 1;
2573 rc = sqlite3_complete(zSql);
2579 ** Read input from *in and process it. If *in==0 then input
2580 ** is interactive - the user is typing it it. Otherwise, input
2581 ** is coming from a file or device. A prompt is issued and history
2582 ** is saved only if input is interactive. An interrupt signal will
2583 ** cause this routine to exit immediately, unless input is interactive.
2585 ** Return the number of errors.
2587 static int process_input(struct callback_data *p, FILE *in){
2598 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
2601 zLine = one_input_line(zSql, in);
2604 if( stdin_is_interactive ) printf("\n");
2607 if( seenInterrupt ){
2612 if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
2613 if( zLine && zLine[0]=='.' && nSql==0 ){
2614 if( p->echoOn ) printf("%s\n", zLine);
2615 rc = do_meta_command(zLine, p);
2616 if( rc==2 ){ /* exit requested */
2623 if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){
2624 memcpy(zLine,";",2);
2629 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
2631 nSql = strlen30(zLine);
2632 zSql = malloc( nSql+3 );
2634 fprintf(stderr, "Error: out of memory\n");
2637 memcpy(zSql, zLine, nSql+1);
2641 int len = strlen30(zLine);
2642 zSql = realloc( zSql, nSql + len + 4 );
2644 fprintf(stderr,"Error: out of memory\n");
2647 zSql[nSql++] = '\n';
2648 memcpy(&zSql[nSql], zLine, len+1);
2651 if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
2652 && sqlite3_complete(zSql) ){
2656 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
2658 if( rc || zErrMsg ){
2660 if( in!=0 || !stdin_is_interactive ){
2661 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
2662 "Error: near line %d:", startline);
2664 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
2667 fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
2668 sqlite3_free(zErrMsg);
2671 fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
2681 if( !_all_whitespace(zSql) ){
2682 fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
2691 ** Return a pathname which is the user's home directory. A
2692 ** 0 return indicates an error of some kind.
2694 static char *find_home_dir(void){
2695 static char *home_dir = NULL;
2696 if( home_dir ) return home_dir;
2698 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL)
2700 struct passwd *pwent;
2701 uid_t uid = getuid();
2702 if( (pwent=getpwuid(uid)) != NULL) {
2703 home_dir = pwent->pw_dir;
2708 #if defined(_WIN32_WCE)
2709 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
2714 #if defined(_WIN32) || defined(WIN32)
2716 home_dir = getenv("USERPROFILE");
2721 home_dir = getenv("HOME");
2724 #if defined(_WIN32) || defined(WIN32)
2726 char *zDrive, *zPath;
2728 zDrive = getenv("HOMEDRIVE");
2729 zPath = getenv("HOMEPATH");
2730 if( zDrive && zPath ){
2731 n = strlen30(zDrive) + strlen30(zPath) + 1;
2732 home_dir = malloc( n );
2733 if( home_dir==0 ) return 0;
2734 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
2741 #endif /* !_WIN32_WCE */
2744 int n = strlen30(home_dir) + 1;
2745 char *z = malloc( n );
2746 if( z ) memcpy(z, home_dir, n);
2754 ** Read input from the file given by sqliterc_override. Or if that
2755 ** parameter is NULL, take input from ~/.sqliterc
2757 ** Returns the number of errors.
2759 static int process_sqliterc(
2760 struct callback_data *p, /* Configuration data */
2761 const char *sqliterc_override /* Name of config file. NULL to use default */
2763 char *home_dir = NULL;
2764 const char *sqliterc = sqliterc_override;
2769 if (sqliterc == NULL) {
2770 home_dir = find_home_dir();
2772 #if !defined(__RTP__) && !defined(_WRS_KERNEL)
2773 fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0);
2777 sqlite3_initialize();
2778 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
2781 in = fopen(sqliterc,"rb");
2783 if( stdin_is_interactive ){
2784 fprintf(stderr,"-- Loading resources from %s\n",sqliterc);
2786 rc = process_input(p,in);
2794 ** Show available command line options
2796 static const char zOptions[] =
2797 " -bail stop after hitting an error\n"
2798 " -batch force batch I/O\n"
2799 " -column set output mode to 'column'\n"
2800 " -cmd command run \"command\" before reading stdin\n"
2801 " -csv set output mode to 'csv'\n"
2802 " -echo print commands before execution\n"
2803 " -init filename read/process named file\n"
2804 " -[no]header turn headers on or off\n"
2805 " -help show this message\n"
2806 " -html set output mode to HTML\n"
2807 " -interactive force interactive I/O\n"
2808 " -line set output mode to 'line'\n"
2809 " -list set output mode to 'list'\n"
2810 #ifdef SQLITE_ENABLE_MULTIPLEX
2811 " -multiplex enable the multiplexor VFS\n"
2813 " -nullvalue 'text' set text string for NULL values\n"
2814 " -separator 'x' set output field separator (|)\n"
2815 " -stats print memory stats before each finalize\n"
2816 " -version show SQLite version\n"
2817 " -vfs NAME use NAME as the default VFS\n"
2818 #ifdef SQLITE_ENABLE_VFSTRACE
2819 " -vfstrace enable tracing of all VFS calls\n"
2822 static void usage(int showDetail){
2824 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
2825 "FILENAME is the name of an SQLite database. A new database is created\n"
2826 "if the file does not previously exist.\n", Argv0);
2828 fprintf(stderr, "OPTIONS include:\n%s", zOptions);
2830 fprintf(stderr, "Use the -help option for additional information\n");
2836 ** Initialize the state information in data
2838 static void main_init(struct callback_data *data) {
2839 memset(data, 0, sizeof(*data));
2840 data->mode = MODE_List;
2841 memcpy(data->separator,"|", 2);
2842 data->showHeader = 0;
2843 sqlite3_config(SQLITE_CONFIG_URI, 1);
2844 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
2845 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
2846 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
2847 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
2850 int main(int argc, char **argv){
2852 struct callback_data data;
2853 const char *zInitFile = 0;
2854 char *zFirstCmd = 0;
2858 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
2859 fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
2860 sqlite3_sourceid(), SQLITE_SOURCE_ID);
2865 stdin_is_interactive = isatty(0);
2867 /* Make sure we have a valid signal handler early, before anything
2871 signal(SIGINT, interrupt_handler);
2874 /* Do an initial pass through the command-line argument to locate
2875 ** the name of the database file, the name of the initialization file,
2876 ** the size of the alternative malloc heap,
2877 ** and the first command to execute.
2879 for(i=1; i<argc-1; i++){
2881 if( argv[i][0]!='-' ) break;
2883 if( z[1]=='-' ) z++;
2884 if( strcmp(z,"-separator")==0
2885 || strcmp(z,"-nullvalue")==0
2886 || strcmp(z,"-cmd")==0
2889 }else if( strcmp(z,"-init")==0 ){
2891 zInitFile = argv[i];
2892 /* Need to check for batch mode here to so we can avoid printing
2893 ** informational messages (like from process_sqliterc) before
2894 ** we do the actual processing of arguments later in a second pass.
2896 }else if( strcmp(z,"-batch")==0 ){
2897 stdin_is_interactive = 0;
2898 }else if( strcmp(z,"-heap")==0 ){
2899 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
2902 sqlite3_int64 szHeap;
2905 szHeap = atoi(zSize);
2906 for(j=0; (c = zSize[j])!=0; j++){
2907 if( c=='M' ){ szHeap *= 1000000; break; }
2908 if( c=='K' ){ szHeap *= 1000; break; }
2909 if( c=='G' ){ szHeap *= 1000000000; break; }
2911 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
2912 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
2914 #ifdef SQLITE_ENABLE_VFSTRACE
2915 }else if( strcmp(z,"-vfstrace")==0 ){
2916 extern int vfstrace_register(
2917 const char *zTraceName,
2918 const char *zOldVfsName,
2919 int (*xOut)(const char*,void*),
2923 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
2925 #ifdef SQLITE_ENABLE_MULTIPLEX
2926 }else if( strcmp(z,"-multiplex")==0 ){
2927 extern int sqlite3_multiple_initialize(const char*,int);
2928 sqlite3_multiplex_initialize(0, 1);
2930 }else if( strcmp(z,"-vfs")==0 ){
2931 sqlite3_vfs *pVfs = sqlite3_vfs_find(argv[++i]);
2933 sqlite3_vfs_register(pVfs, 1);
2935 fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]);
2941 data.zDbFilename = argv[i++];
2943 #ifndef SQLITE_OMIT_MEMORYDB
2944 data.zDbFilename = ":memory:";
2946 data.zDbFilename = 0;
2950 zFirstCmd = argv[i++];
2953 fprintf(stderr,"%s: Error: too many options: \"%s\"\n", Argv0, argv[i]);
2954 fprintf(stderr,"Use -help for a list of options.\n");
2959 #ifdef SQLITE_OMIT_MEMORYDB
2960 if( data.zDbFilename==0 ){
2961 fprintf(stderr,"%s: Error: no database filename specified\n", Argv0);
2966 /* Go ahead and open the database file if it already exists. If the
2967 ** file does not exist, delay opening it. This prevents empty database
2968 ** files from being created if a user mistypes the database name argument
2969 ** to the sqlite command-line tool.
2971 if( access(data.zDbFilename, 0)==0 ){
2975 /* Process the initialization file if there is one. If no -init option
2976 ** is given on the command line, look for a file named ~/.sqliterc and
2977 ** try to process it.
2979 rc = process_sqliterc(&data,zInitFile);
2984 /* Make a second pass through the command-line argument and set
2985 ** options. This second pass is delayed until after the initialization
2986 ** file is processed so that the command-line arguments will override
2987 ** settings in the initialization file.
2989 for(i=1; i<argc && argv[i][0]=='-'; i++){
2991 if( z[1]=='-' ){ z++; }
2992 if( strcmp(z,"-init")==0 ){
2994 }else if( strcmp(z,"-html")==0 ){
2995 data.mode = MODE_Html;
2996 }else if( strcmp(z,"-list")==0 ){
2997 data.mode = MODE_List;
2998 }else if( strcmp(z,"-line")==0 ){
2999 data.mode = MODE_Line;
3000 }else if( strcmp(z,"-column")==0 ){
3001 data.mode = MODE_Column;
3002 }else if( strcmp(z,"-csv")==0 ){
3003 data.mode = MODE_Csv;
3004 memcpy(data.separator,",",2);
3005 }else if( strcmp(z,"-separator")==0 ){
3008 fprintf(stderr,"%s: Error: missing argument for option: %s\n",
3010 fprintf(stderr,"Use -help for a list of options.\n");
3013 sqlite3_snprintf(sizeof(data.separator), data.separator,
3014 "%.*s",(int)sizeof(data.separator)-1,argv[i]);
3015 }else if( strcmp(z,"-nullvalue")==0 ){
3018 fprintf(stderr,"%s: Error: missing argument for option: %s\n",
3020 fprintf(stderr,"Use -help for a list of options.\n");
3023 sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
3024 "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
3025 }else if( strcmp(z,"-header")==0 ){
3026 data.showHeader = 1;
3027 }else if( strcmp(z,"-noheader")==0 ){
3028 data.showHeader = 0;
3029 }else if( strcmp(z,"-echo")==0 ){
3031 }else if( strcmp(z,"-stats")==0 ){
3033 }else if( strcmp(z,"-bail")==0 ){
3035 }else if( strcmp(z,"-version")==0 ){
3036 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
3038 }else if( strcmp(z,"-interactive")==0 ){
3039 stdin_is_interactive = 1;
3040 }else if( strcmp(z,"-batch")==0 ){
3041 stdin_is_interactive = 0;
3042 }else if( strcmp(z,"-heap")==0 ){
3044 }else if( strcmp(z,"-vfs")==0 ){
3046 #ifdef SQLITE_ENABLE_VFSTRACE
3047 }else if( strcmp(z,"-vfstrace")==0 ){
3050 #ifdef SQLITE_ENABLE_MULTIPLEX
3051 }else if( strcmp(z,"-multiplex")==0 ){
3054 }else if( strcmp(z,"-help")==0 ){
3056 }else if( strcmp(z,"-cmd")==0 ){
3057 if( i==argc-1 ) break;
3061 rc = do_meta_command(z, &data);
3062 if( rc && bail_on_error ) return rc;
3065 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
3067 fprintf(stderr,"Error: %s\n", zErrMsg);
3068 if( bail_on_error ) return rc!=0 ? rc : 1;
3070 fprintf(stderr,"Error: unable to process SQL \"%s\"\n", z);
3071 if( bail_on_error ) return rc;
3075 fprintf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
3076 fprintf(stderr,"Use -help for a list of options.\n");
3082 /* Run just the command that follows the database name
3084 if( zFirstCmd[0]=='.' ){
3085 rc = do_meta_command(zFirstCmd, &data);
3088 rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg);
3090 fprintf(stderr,"Error: %s\n", zErrMsg);
3091 return rc!=0 ? rc : 1;
3093 fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd);
3098 /* Run commands received from standard input
3100 if( stdin_is_interactive ){
3105 "SQLite version %s %.19s\n" /*extra-version-info*/
3106 "Enter \".help\" for instructions\n"
3107 "Enter SQL statements terminated with a \";\"\n",
3108 sqlite3_libversion(), sqlite3_sourceid()
3110 zHome = find_home_dir();
3112 nHistory = strlen30(zHome) + 20;
3113 if( (zHistory = malloc(nHistory))!=0 ){
3114 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
3117 #if defined(HAVE_READLINE) && HAVE_READLINE==1
3118 if( zHistory ) read_history(zHistory);
3120 rc = process_input(&data, 0);
3122 stifle_history(100);
3123 write_history(zHistory);
3127 rc = process_input(&data, stdin);
3130 set_table_name(&data, 0);
3132 sqlite3_close(data.db);