• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
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.
10 **
11 *************************************************************************
12 ** This file contains code to implement the "sqlite" command line
13 ** utility for accessing SQLite databases.
14 */
15 #if defined(_WIN32) || defined(WIN32)
16 /* This needs to come before any includes for MSVC compiler */
17 #define _CRT_SECURE_NO_WARNINGS
18 #endif
19 
20 #include <stdlib.h>
21 #include <string.h>
22 #include <stdio.h>
23 #include <assert.h>
24 #include "sqlite3.h"
25 #include <ctype.h>
26 #include <stdarg.h>
27 // Begin Android Add
28 #ifndef NO_ANDROID_FUNCS
29 #include <sqlite3_android.h>
30 #endif
31 // End Android Add
32 
33 #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__)
34 # include <signal.h>
35 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
36 #  include <pwd.h>
37 # endif
38 # include <unistd.h>
39 # include <sys/types.h>
40 #endif
41 
42 #ifdef __OS2__
43 # include <unistd.h>
44 #endif
45 
46 #if defined(HAVE_READLINE) && HAVE_READLINE==1
47 # include <readline/readline.h>
48 # include <readline/history.h>
49 #else
50 # define readline(p) local_getline(p,stdin)
51 # define add_history(X)
52 # define read_history(X)
53 # define write_history(X)
54 # define stifle_history(X)
55 #endif
56 
57 #if defined(_WIN32) || defined(WIN32)
58 # include <io.h>
59 #define isatty(h) _isatty(h)
60 #define access(f,m) _access((f),(m))
61 #else
62 /* Make sure isatty() has a prototype.
63 */
64 extern int isatty();
65 #endif
66 
67 #if defined(_WIN32_WCE)
68 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
69  * thus we always assume that we have a console. That can be
70  * overridden with the -batch command line option.
71  */
72 #define isatty(x) 1
73 #endif
74 
75 #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(__RTP__) && !defined(_WRS_KERNEL)
76 #include <sys/time.h>
77 #include <sys/resource.h>
78 
79 /* Saved resource information for the beginning of an operation */
80 static struct rusage sBegin;
81 
82 /* True if the timer is enabled */
83 static int enableTimer = 0;
84 
85 /*
86 ** Begin timing an operation
87 */
beginTimer(void)88 static void beginTimer(void){
89   if( enableTimer ){
90     getrusage(RUSAGE_SELF, &sBegin);
91   }
92 }
93 
94 /* Return the difference of two time_structs in seconds */
timeDiff(struct timeval * pStart,struct timeval * pEnd)95 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
96   return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
97          (double)(pEnd->tv_sec - pStart->tv_sec);
98 }
99 
100 /*
101 ** Print the timing results.
102 */
endTimer(void)103 static void endTimer(void){
104   if( enableTimer ){
105     struct rusage sEnd;
106     getrusage(RUSAGE_SELF, &sEnd);
107     printf("CPU Time: user %f sys %f\n",
108        timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
109        timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
110   }
111 }
112 
113 #define BEGIN_TIMER beginTimer()
114 #define END_TIMER endTimer()
115 #define HAS_TIMER 1
116 
117 #elif (defined(_WIN32) || defined(WIN32))
118 
119 #include <windows.h>
120 
121 /* Saved resource information for the beginning of an operation */
122 static HANDLE hProcess;
123 static FILETIME ftKernelBegin;
124 static FILETIME ftUserBegin;
125 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
126 static GETPROCTIMES getProcessTimesAddr = NULL;
127 
128 /* True if the timer is enabled */
129 static int enableTimer = 0;
130 
131 /*
132 ** Check to see if we have timer support.  Return 1 if necessary
133 ** support found (or found previously).
134 */
hasTimer(void)135 static int hasTimer(void){
136   if( getProcessTimesAddr ){
137     return 1;
138   } else {
139     /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions.
140     ** See if the version we are running on has it, and if it does, save off
141     ** a pointer to it and the current process handle.
142     */
143     hProcess = GetCurrentProcess();
144     if( hProcess ){
145       HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
146       if( NULL != hinstLib ){
147         getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
148         if( NULL != getProcessTimesAddr ){
149           return 1;
150         }
151         FreeLibrary(hinstLib);
152       }
153     }
154   }
155   return 0;
156 }
157 
158 /*
159 ** Begin timing an operation
160 */
beginTimer(void)161 static void beginTimer(void){
162   if( enableTimer && getProcessTimesAddr ){
163     FILETIME ftCreation, ftExit;
164     getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
165   }
166 }
167 
168 /* Return the difference of two FILETIME structs in seconds */
timeDiff(FILETIME * pStart,FILETIME * pEnd)169 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
170   sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
171   sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
172   return (double) ((i64End - i64Start) / 10000000.0);
173 }
174 
175 /*
176 ** Print the timing results.
177 */
endTimer(void)178 static void endTimer(void){
179   if( enableTimer && getProcessTimesAddr){
180     FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
181     getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
182     printf("CPU Time: user %f sys %f\n",
183        timeDiff(&ftUserBegin, &ftUserEnd),
184        timeDiff(&ftKernelBegin, &ftKernelEnd));
185   }
186 }
187 
188 #define BEGIN_TIMER beginTimer()
189 #define END_TIMER endTimer()
190 #define HAS_TIMER hasTimer()
191 
192 #else
193 #define BEGIN_TIMER
194 #define END_TIMER
195 #define HAS_TIMER 0
196 #endif
197 
198 /*
199 ** Used to prevent warnings about unused parameters
200 */
201 #define UNUSED_PARAMETER(x) (void)(x)
202 
203 /*
204 ** If the following flag is set, then command execution stops
205 ** at an error if we are not interactive.
206 */
207 static int bail_on_error = 0;
208 
209 /*
210 ** Threat stdin as an interactive input if the following variable
211 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
212 */
213 static int stdin_is_interactive = 1;
214 
215 /*
216 ** The following is the open SQLite database.  We make a pointer
217 ** to this database a static variable so that it can be accessed
218 ** by the SIGINT handler to interrupt database processing.
219 */
220 static sqlite3 *db = 0;
221 
222 /*
223 ** True if an interrupt (Control-C) has been received.
224 */
225 static volatile int seenInterrupt = 0;
226 
227 /*
228 ** This is the name of our program. It is set in main(), used
229 ** in a number of other places, mostly for error messages.
230 */
231 static char *Argv0;
232 
233 /*
234 ** Prompt strings. Initialized in main. Settable with
235 **   .prompt main continue
236 */
237 static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
238 static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
239 
240 /*
241 ** Write I/O traces to the following stream.
242 */
243 #ifdef SQLITE_ENABLE_IOTRACE
244 static FILE *iotrace = 0;
245 #endif
246 
247 /*
248 ** This routine works like printf in that its first argument is a
249 ** format string and subsequent arguments are values to be substituted
250 ** in place of % fields.  The result of formatting this string
251 ** is written to iotrace.
252 */
253 #ifdef SQLITE_ENABLE_IOTRACE
iotracePrintf(const char * zFormat,...)254 static void iotracePrintf(const char *zFormat, ...){
255   va_list ap;
256   char *z;
257   if( iotrace==0 ) return;
258   va_start(ap, zFormat);
259   z = sqlite3_vmprintf(zFormat, ap);
260   va_end(ap);
261   fprintf(iotrace, "%s", z);
262   sqlite3_free(z);
263 }
264 #endif
265 
266 
267 /*
268 ** Determines if a string is a number of not.
269 */
isNumber(const char * z,int * realnum)270 static int isNumber(const char *z, int *realnum){
271   if( *z=='-' || *z=='+' ) z++;
272   if( !isdigit(*z) ){
273     return 0;
274   }
275   z++;
276   if( realnum ) *realnum = 0;
277   while( isdigit(*z) ){ z++; }
278   if( *z=='.' ){
279     z++;
280     if( !isdigit(*z) ) return 0;
281     while( isdigit(*z) ){ z++; }
282     if( realnum ) *realnum = 1;
283   }
284   if( *z=='e' || *z=='E' ){
285     z++;
286     if( *z=='+' || *z=='-' ) z++;
287     if( !isdigit(*z) ) return 0;
288     while( isdigit(*z) ){ z++; }
289     if( realnum ) *realnum = 1;
290   }
291   return *z==0;
292 }
293 
294 /*
295 ** A global char* and an SQL function to access its current value
296 ** from within an SQL statement. This program used to use the
297 ** sqlite_exec_printf() API to substitue a string into an SQL statement.
298 ** The correct way to do this with sqlite3 is to use the bind API, but
299 ** since the shell is built around the callback paradigm it would be a lot
300 ** of work. Instead just use this hack, which is quite harmless.
301 */
302 static const char *zShellStatic = 0;
shellstaticFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)303 static void shellstaticFunc(
304   sqlite3_context *context,
305   int argc,
306   sqlite3_value **argv
307 ){
308   assert( 0==argc );
309   assert( zShellStatic );
310   UNUSED_PARAMETER(argc);
311   UNUSED_PARAMETER(argv);
312   sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
313 }
314 
315 
316 /*
317 ** This routine reads a line of text from FILE in, stores
318 ** the text in memory obtained from malloc() and returns a pointer
319 ** to the text.  NULL is returned at end of file, or if malloc()
320 ** fails.
321 **
322 ** The interface is like "readline" but no command-line editing
323 ** is done.
324 */
local_getline(char * zPrompt,FILE * in)325 static char *local_getline(char *zPrompt, FILE *in){
326   char *zLine;
327   int nLine;
328   int n;
329   int eol;
330 
331   if( zPrompt && *zPrompt ){
332     printf("%s",zPrompt);
333     fflush(stdout);
334   }
335   nLine = 100;
336   zLine = malloc( nLine );
337   if( zLine==0 ) return 0;
338   n = 0;
339   eol = 0;
340   while( !eol ){
341     if( n+100>nLine ){
342       nLine = nLine*2 + 100;
343       zLine = realloc(zLine, nLine);
344       if( zLine==0 ) return 0;
345     }
346     if( fgets(&zLine[n], nLine - n, in)==0 ){
347       if( n==0 ){
348         free(zLine);
349         return 0;
350       }
351       zLine[n] = 0;
352       eol = 1;
353       break;
354     }
355     while( zLine[n] ){ n++; }
356     if( n>0 && zLine[n-1]=='\n' ){
357       n--;
358       if( n>0 && zLine[n-1]=='\r' ) n--;
359       zLine[n] = 0;
360       eol = 1;
361     }
362   }
363   zLine = realloc( zLine, n+1 );
364   return zLine;
365 }
366 
367 /*
368 ** Retrieve a single line of input text.
369 **
370 ** zPrior is a string of prior text retrieved.  If not the empty
371 ** string, then issue a continuation prompt.
372 */
one_input_line(const char * zPrior,FILE * in)373 static char *one_input_line(const char *zPrior, FILE *in){
374   char *zPrompt;
375   char *zResult;
376   if( in!=0 ){
377     return local_getline(0, in);
378   }
379   if( zPrior && zPrior[0] ){
380     zPrompt = continuePrompt;
381   }else{
382     zPrompt = mainPrompt;
383   }
384   zResult = readline(zPrompt);
385 #if defined(HAVE_READLINE) && HAVE_READLINE==1
386   if( zResult && *zResult ) add_history(zResult);
387 #endif
388   return zResult;
389 }
390 
391 struct previous_mode_data {
392   int valid;        /* Is there legit data in here? */
393   int mode;
394   int showHeader;
395   int colWidth[100];
396 };
397 
398 /*
399 ** An pointer to an instance of this structure is passed from
400 ** the main program to the callback.  This is used to communicate
401 ** state and mode information.
402 */
403 struct callback_data {
404   sqlite3 *db;           /* The database */
405   int echoOn;            /* True to echo input commands */
406   int statsOn;           /* True to display memory stats before each finalize */
407   int cnt;               /* Number of records displayed so far */
408   FILE *out;             /* Write results here */
409   int mode;              /* An output mode setting */
410   int writableSchema;    /* True if PRAGMA writable_schema=ON */
411   int showHeader;        /* True to show column names in List or Column mode */
412   char *zDestTable;      /* Name of destination table when MODE_Insert */
413   char separator[20];    /* Separator character for MODE_List */
414   int colWidth[100];     /* Requested width of each column when in column mode*/
415   int actualWidth[100];  /* Actual width of each column */
416   char nullvalue[20];    /* The text to print when a NULL comes back from
417                          ** the database */
418   struct previous_mode_data explainPrev;
419                          /* Holds the mode information just before
420                          ** .explain ON */
421   char outfile[FILENAME_MAX]; /* Filename for *out */
422   const char *zDbFilename;    /* name of the database file */
423   sqlite3_stmt *pStmt;   /* Current statement if any. */
424   FILE *pLog;            /* Write log output here */
425 };
426 
427 /*
428 ** These are the allowed modes.
429 */
430 #define MODE_Line     0  /* One column per line.  Blank line between records */
431 #define MODE_Column   1  /* One record per line in neat columns */
432 #define MODE_List     2  /* One record per line with a separator */
433 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
434 #define MODE_Html     4  /* Generate an XHTML table */
435 #define MODE_Insert   5  /* Generate SQL "insert" statements */
436 #define MODE_Tcl      6  /* Generate ANSI-C or TCL quoted elements */
437 #define MODE_Csv      7  /* Quote strings, numbers are plain */
438 #define MODE_Explain  8  /* Like MODE_Column, but do not truncate data */
439 
440 static const char *modeDescr[] = {
441   "line",
442   "column",
443   "list",
444   "semi",
445   "html",
446   "insert",
447   "tcl",
448   "csv",
449   "explain",
450 };
451 
452 /*
453 ** Number of elements in an array
454 */
455 #define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
456 
457 /*
458 ** Compute a string length that is limited to what can be stored in
459 ** lower 30 bits of a 32-bit signed integer.
460 */
strlen30(const char * z)461 static int strlen30(const char *z){
462   const char *z2 = z;
463   while( *z2 ){ z2++; }
464   return 0x3fffffff & (int)(z2 - z);
465 }
466 
467 /*
468 ** A callback for the sqlite3_log() interface.
469 */
shellLog(void * pArg,int iErrCode,const char * zMsg)470 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
471   struct callback_data *p = (struct callback_data*)pArg;
472   if( p->pLog==0 ) return;
473   fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
474   fflush(p->pLog);
475 }
476 
477 /*
478 ** Output the given string as a hex-encoded blob (eg. X'1234' )
479 */
output_hex_blob(FILE * out,const void * pBlob,int nBlob)480 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
481   int i;
482   char *zBlob = (char *)pBlob;
483   fprintf(out,"X'");
484   for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]); }
485   fprintf(out,"'");
486 }
487 
488 /*
489 ** Output the given string as a quoted string using SQL quoting conventions.
490 */
output_quoted_string(FILE * out,const char * z)491 static void output_quoted_string(FILE *out, const char *z){
492   int i;
493   int nSingle = 0;
494   for(i=0; z[i]; i++){
495     if( z[i]=='\'' ) nSingle++;
496   }
497   if( nSingle==0 ){
498     fprintf(out,"'%s'",z);
499   }else{
500     fprintf(out,"'");
501     while( *z ){
502       for(i=0; z[i] && z[i]!='\''; i++){}
503       if( i==0 ){
504         fprintf(out,"''");
505         z++;
506       }else if( z[i]=='\'' ){
507         fprintf(out,"%.*s''",i,z);
508         z += i+1;
509       }else{
510         fprintf(out,"%s",z);
511         break;
512       }
513     }
514     fprintf(out,"'");
515   }
516 }
517 
518 /*
519 ** Output the given string as a quoted according to C or TCL quoting rules.
520 */
output_c_string(FILE * out,const char * z)521 static void output_c_string(FILE *out, const char *z){
522   unsigned int c;
523   fputc('"', out);
524   while( (c = *(z++))!=0 ){
525     if( c=='\\' ){
526       fputc(c, out);
527       fputc(c, out);
528     }else if( c=='\t' ){
529       fputc('\\', out);
530       fputc('t', out);
531     }else if( c=='\n' ){
532       fputc('\\', out);
533       fputc('n', out);
534     }else if( c=='\r' ){
535       fputc('\\', out);
536       fputc('r', out);
537     }else if( !isprint(c) ){
538       fprintf(out, "\\%03o", c&0xff);
539     }else{
540       fputc(c, out);
541     }
542   }
543   fputc('"', out);
544 }
545 
546 /*
547 ** Output the given string with characters that are special to
548 ** HTML escaped.
549 */
output_html_string(FILE * out,const char * z)550 static void output_html_string(FILE *out, const char *z){
551   int i;
552   while( *z ){
553     for(i=0;   z[i]
554             && z[i]!='<'
555             && z[i]!='&'
556             && z[i]!='>'
557             && z[i]!='\"'
558             && z[i]!='\'';
559         i++){}
560     if( i>0 ){
561       fprintf(out,"%.*s",i,z);
562     }
563     if( z[i]=='<' ){
564       fprintf(out,"&lt;");
565     }else if( z[i]=='&' ){
566       fprintf(out,"&amp;");
567     }else if( z[i]=='>' ){
568       fprintf(out,"&gt;");
569     }else if( z[i]=='\"' ){
570       fprintf(out,"&quot;");
571     }else if( z[i]=='\'' ){
572       fprintf(out,"&#39;");
573     }else{
574       break;
575     }
576     z += i + 1;
577   }
578 }
579 
580 /*
581 ** If a field contains any character identified by a 1 in the following
582 ** array, then the string must be quoted for CSV.
583 */
584 static const char needCsvQuote[] = {
585   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
586   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
587   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
588   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
589   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
590   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
591   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
592   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
593   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
594   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
595   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
596   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
597   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
598   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
599   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
600   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
601 };
602 
603 /*
604 ** Output a single term of CSV.  Actually, p->separator is used for
605 ** the separator, which may or may not be a comma.  p->nullvalue is
606 ** the null value.  Strings are quoted using ANSI-C rules.  Numbers
607 ** appear outside of quotes.
608 */
output_csv(struct callback_data * p,const char * z,int bSep)609 static void output_csv(struct callback_data *p, const char *z, int bSep){
610   FILE *out = p->out;
611   if( z==0 ){
612     fprintf(out,"%s",p->nullvalue);
613   }else{
614     int i;
615     int nSep = strlen30(p->separator);
616     for(i=0; z[i]; i++){
617       if( needCsvQuote[((unsigned char*)z)[i]]
618          || (z[i]==p->separator[0] &&
619              (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
620         i = 0;
621         break;
622       }
623     }
624     if( i==0 ){
625       putc('"', out);
626       for(i=0; z[i]; i++){
627         if( z[i]=='"' ) putc('"', out);
628         putc(z[i], out);
629       }
630       putc('"', out);
631     }else{
632       fprintf(out, "%s", z);
633     }
634   }
635   if( bSep ){
636     fprintf(p->out, "%s", p->separator);
637   }
638 }
639 
640 #ifdef SIGINT
641 /*
642 ** This routine runs when the user presses Ctrl-C
643 */
interrupt_handler(int NotUsed)644 static void interrupt_handler(int NotUsed){
645   UNUSED_PARAMETER(NotUsed);
646   seenInterrupt = 1;
647   if( db ) sqlite3_interrupt(db);
648 }
649 #endif
650 
651 /*
652 ** This is the callback routine that the shell
653 ** invokes for each row of a query result.
654 */
shell_callback(void * pArg,int nArg,char ** azArg,char ** azCol,int * aiType)655 static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){
656   int i;
657   struct callback_data *p = (struct callback_data*)pArg;
658 
659   switch( p->mode ){
660     case MODE_Line: {
661       int w = 5;
662       if( azArg==0 ) break;
663       for(i=0; i<nArg; i++){
664         int len = strlen30(azCol[i] ? azCol[i] : "");
665         if( len>w ) w = len;
666       }
667       if( p->cnt++>0 ) fprintf(p->out,"\n");
668       for(i=0; i<nArg; i++){
669         fprintf(p->out,"%*s = %s\n", w, azCol[i],
670                 azArg[i] ? azArg[i] : p->nullvalue);
671       }
672       break;
673     }
674     case MODE_Explain:
675     case MODE_Column: {
676       if( p->cnt++==0 ){
677         for(i=0; i<nArg; i++){
678           int w, n;
679           if( i<ArraySize(p->colWidth) ){
680             w = p->colWidth[i];
681           }else{
682             w = 0;
683           }
684           if( w<=0 ){
685             w = strlen30(azCol[i] ? azCol[i] : "");
686             if( w<10 ) w = 10;
687             n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue);
688             if( w<n ) w = n;
689           }
690           if( i<ArraySize(p->actualWidth) ){
691             p->actualWidth[i] = w;
692           }
693           if( p->showHeader ){
694             fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": "  ");
695           }
696         }
697         if( p->showHeader ){
698           for(i=0; i<nArg; i++){
699             int w;
700             if( i<ArraySize(p->actualWidth) ){
701                w = p->actualWidth[i];
702             }else{
703                w = 10;
704             }
705             fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
706                    "----------------------------------------------------------",
707                     i==nArg-1 ? "\n": "  ");
708           }
709         }
710       }
711       if( azArg==0 ) break;
712       for(i=0; i<nArg; i++){
713         int w;
714         if( i<ArraySize(p->actualWidth) ){
715            w = p->actualWidth[i];
716         }else{
717            w = 10;
718         }
719         if( p->mode==MODE_Explain && azArg[i] &&
720            strlen30(azArg[i])>w ){
721           w = strlen30(azArg[i]);
722         }
723         fprintf(p->out,"%-*.*s%s",w,w,
724             azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": "  ");
725       }
726       break;
727     }
728     case MODE_Semi:
729     case MODE_List: {
730       if( p->cnt++==0 && p->showHeader ){
731         for(i=0; i<nArg; i++){
732           fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
733         }
734       }
735       if( azArg==0 ) break;
736       for(i=0; i<nArg; i++){
737         char *z = azArg[i];
738         if( z==0 ) z = p->nullvalue;
739         fprintf(p->out, "%s", z);
740         if( i<nArg-1 ){
741           fprintf(p->out, "%s", p->separator);
742         }else if( p->mode==MODE_Semi ){
743           fprintf(p->out, ";\n");
744         }else{
745           fprintf(p->out, "\n");
746         }
747       }
748       break;
749     }
750     case MODE_Html: {
751       if( p->cnt++==0 && p->showHeader ){
752         fprintf(p->out,"<TR>");
753         for(i=0; i<nArg; i++){
754           fprintf(p->out,"<TH>");
755           output_html_string(p->out, azCol[i]);
756           fprintf(p->out,"</TH>\n");
757         }
758         fprintf(p->out,"</TR>\n");
759       }
760       if( azArg==0 ) break;
761       fprintf(p->out,"<TR>");
762       for(i=0; i<nArg; i++){
763         fprintf(p->out,"<TD>");
764         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
765         fprintf(p->out,"</TD>\n");
766       }
767       fprintf(p->out,"</TR>\n");
768       break;
769     }
770     case MODE_Tcl: {
771       if( p->cnt++==0 && p->showHeader ){
772         for(i=0; i<nArg; i++){
773           output_c_string(p->out,azCol[i] ? azCol[i] : "");
774           fprintf(p->out, "%s", p->separator);
775         }
776         fprintf(p->out,"\n");
777       }
778       if( azArg==0 ) break;
779       for(i=0; i<nArg; i++){
780         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
781         fprintf(p->out, "%s", p->separator);
782       }
783       fprintf(p->out,"\n");
784       break;
785     }
786     case MODE_Csv: {
787       if( p->cnt++==0 && p->showHeader ){
788         for(i=0; i<nArg; i++){
789           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
790         }
791         fprintf(p->out,"\n");
792       }
793       if( azArg==0 ) break;
794       for(i=0; i<nArg; i++){
795         output_csv(p, azArg[i], i<nArg-1);
796       }
797       fprintf(p->out,"\n");
798       break;
799     }
800     case MODE_Insert: {
801       p->cnt++;
802       if( azArg==0 ) break;
803       fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
804       for(i=0; i<nArg; i++){
805         char *zSep = i>0 ? ",": "";
806         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
807           fprintf(p->out,"%sNULL",zSep);
808         }else if( aiType && aiType[i]==SQLITE_TEXT ){
809           if( zSep[0] ) fprintf(p->out,"%s",zSep);
810           output_quoted_string(p->out, azArg[i]);
811         }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){
812           fprintf(p->out,"%s%s",zSep, azArg[i]);
813         }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
814           const void *pBlob = sqlite3_column_blob(p->pStmt, i);
815           int nBlob = sqlite3_column_bytes(p->pStmt, i);
816           if( zSep[0] ) fprintf(p->out,"%s",zSep);
817           output_hex_blob(p->out, pBlob, nBlob);
818         }else if( isNumber(azArg[i], 0) ){
819           fprintf(p->out,"%s%s",zSep, azArg[i]);
820         }else{
821           if( zSep[0] ) fprintf(p->out,"%s",zSep);
822           output_quoted_string(p->out, azArg[i]);
823         }
824       }
825       fprintf(p->out,");\n");
826       break;
827     }
828   }
829   return 0;
830 }
831 
832 /*
833 ** This is the callback routine that the SQLite library
834 ** invokes for each row of a query result.
835 */
callback(void * pArg,int nArg,char ** azArg,char ** azCol)836 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
837   /* since we don't have type info, call the shell_callback with a NULL value */
838   return shell_callback(pArg, nArg, azArg, azCol, NULL);
839 }
840 
841 /*
842 ** Set the destination table field of the callback_data structure to
843 ** the name of the table given.  Escape any quote characters in the
844 ** table name.
845 */
set_table_name(struct callback_data * p,const char * zName)846 static void set_table_name(struct callback_data *p, const char *zName){
847   int i, n;
848   int needQuote;
849   char *z;
850 
851   if( p->zDestTable ){
852     free(p->zDestTable);
853     p->zDestTable = 0;
854   }
855   if( zName==0 ) return;
856   needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
857   for(i=n=0; zName[i]; i++, n++){
858     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
859       needQuote = 1;
860       if( zName[i]=='\'' ) n++;
861     }
862   }
863   if( needQuote ) n += 2;
864   z = p->zDestTable = malloc( n+1 );
865   if( z==0 ){
866     fprintf(stderr,"Error: out of memory\n");
867     exit(1);
868   }
869   n = 0;
870   if( needQuote ) z[n++] = '\'';
871   for(i=0; zName[i]; i++){
872     z[n++] = zName[i];
873     if( zName[i]=='\'' ) z[n++] = '\'';
874   }
875   if( needQuote ) z[n++] = '\'';
876   z[n] = 0;
877 }
878 
879 /* zIn is either a pointer to a NULL-terminated string in memory obtained
880 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
881 ** added to zIn, and the result returned in memory obtained from malloc().
882 ** zIn, if it was not NULL, is freed.
883 **
884 ** If the third argument, quote, is not '\0', then it is used as a
885 ** quote character for zAppend.
886 */
appendText(char * zIn,char const * zAppend,char quote)887 static char *appendText(char *zIn, char const *zAppend, char quote){
888   int len;
889   int i;
890   int nAppend = strlen30(zAppend);
891   int nIn = (zIn?strlen30(zIn):0);
892 
893   len = nAppend+nIn+1;
894   if( quote ){
895     len += 2;
896     for(i=0; i<nAppend; i++){
897       if( zAppend[i]==quote ) len++;
898     }
899   }
900 
901   zIn = (char *)realloc(zIn, len);
902   if( !zIn ){
903     return 0;
904   }
905 
906   if( quote ){
907     char *zCsr = &zIn[nIn];
908     *zCsr++ = quote;
909     for(i=0; i<nAppend; i++){
910       *zCsr++ = zAppend[i];
911       if( zAppend[i]==quote ) *zCsr++ = quote;
912     }
913     *zCsr++ = quote;
914     *zCsr++ = '\0';
915     assert( (zCsr-zIn)==len );
916   }else{
917     memcpy(&zIn[nIn], zAppend, nAppend);
918     zIn[len-1] = '\0';
919   }
920 
921   return zIn;
922 }
923 
924 
925 /*
926 ** Execute a query statement that has a single result column.  Print
927 ** that result column on a line by itself with a semicolon terminator.
928 **
929 ** This is used, for example, to show the schema of the database by
930 ** querying the SQLITE_MASTER table.
931 */
run_table_dump_query(FILE * out,sqlite3 * db,const char * zSelect,const char * zFirstRow)932 static int run_table_dump_query(
933   FILE *out,              /* Send output here */
934   sqlite3 *db,            /* Database to query */
935   const char *zSelect,    /* SELECT statement to extract content */
936   const char *zFirstRow   /* Print before first row, if not NULL */
937 ){
938   sqlite3_stmt *pSelect;
939   int rc;
940   rc = sqlite3_prepare(db, zSelect, -1, &pSelect, 0);
941   if( rc!=SQLITE_OK || !pSelect ){
942     return rc;
943   }
944   rc = sqlite3_step(pSelect);
945   while( rc==SQLITE_ROW ){
946     if( zFirstRow ){
947       fprintf(out, "%s", zFirstRow);
948       zFirstRow = 0;
949     }
950     fprintf(out, "%s;\n", sqlite3_column_text(pSelect, 0));
951     rc = sqlite3_step(pSelect);
952   }
953   return sqlite3_finalize(pSelect);
954 }
955 
956 /*
957 ** Allocate space and save off current error string.
958 */
save_err_msg(sqlite3 * db)959 static char *save_err_msg(
960   sqlite3 *db            /* Database to query */
961 ){
962   int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
963   char *zErrMsg = sqlite3_malloc(nErrMsg);
964   if( zErrMsg ){
965     memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
966   }
967   return zErrMsg;
968 }
969 
970 /*
971 ** Display memory stats.
972 */
display_stats(sqlite3 * db,struct callback_data * pArg,int bReset)973 static int display_stats(
974   sqlite3 *db,                /* Database to query */
975   struct callback_data *pArg, /* Pointer to struct callback_data */
976   int bReset                  /* True to reset the stats */
977 ){
978   int iCur;
979   int iHiwtr;
980 
981   if( pArg && pArg->out ){
982 
983     iHiwtr = iCur = -1;
984     sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
985     fprintf(pArg->out, "Memory Used:                         %d (max %d) bytes\n", iCur, iHiwtr);
986     iHiwtr = iCur = -1;
987     sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
988     fprintf(pArg->out, "Number of Allocations:               %d (max %d)\n", iCur, iHiwtr);
989 /*
990 ** Not currently used by the CLI.
991 **    iHiwtr = iCur = -1;
992 **    sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
993 **    fprintf(pArg->out, "Number of Pcache Pages Used:         %d (max %d) pages\n", iCur, iHiwtr);
994 */
995     iHiwtr = iCur = -1;
996     sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
997     fprintf(pArg->out, "Number of Pcache Overflow Bytes:     %d (max %d) bytes\n", iCur, iHiwtr);
998 /*
999 ** Not currently used by the CLI.
1000 **    iHiwtr = iCur = -1;
1001 **    sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
1002 **    fprintf(pArg->out, "Number of Scratch Allocations Used:  %d (max %d)\n", iCur, iHiwtr);
1003 */
1004     iHiwtr = iCur = -1;
1005     sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
1006     fprintf(pArg->out, "Number of Scratch Overflow Bytes:    %d (max %d) bytes\n", iCur, iHiwtr);
1007     iHiwtr = iCur = -1;
1008     sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
1009     fprintf(pArg->out, "Largest Allocation:                  %d bytes\n", iHiwtr);
1010     iHiwtr = iCur = -1;
1011     sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
1012     fprintf(pArg->out, "Largest Pcache Allocation:           %d bytes\n", iHiwtr);
1013     iHiwtr = iCur = -1;
1014     sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
1015     fprintf(pArg->out, "Largest Scratch Allocation:          %d bytes\n", iHiwtr);
1016 #ifdef YYTRACKMAXSTACKDEPTH
1017     iHiwtr = iCur = -1;
1018     sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
1019     fprintf(pArg->out, "Deepest Parser Stack:                %d (max %d)\n", iCur, iHiwtr);
1020 #endif
1021   }
1022 
1023   if( pArg && pArg->out && db ){
1024     iHiwtr = iCur = -1;
1025     sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset);
1026     fprintf(pArg->out, "Lookaside Slots Used:                %d (max %d)\n", iCur, iHiwtr);
1027     iHiwtr = iCur = -1;
1028     sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
1029     fprintf(pArg->out, "Pager Heap Usage:                    %d bytes\n", iCur);
1030     iHiwtr = iCur = -1;
1031     sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
1032     fprintf(pArg->out, "Schema Heap Usage:                   %d bytes\n", iCur);
1033     iHiwtr = iCur = -1;
1034     sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
1035     fprintf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n", iCur);
1036   }
1037 
1038   if( pArg && pArg->out && db && pArg->pStmt ){
1039     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset);
1040     fprintf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
1041     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
1042     fprintf(pArg->out, "Sort Operations:                     %d\n", iCur);
1043     iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset);
1044     fprintf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
1045   }
1046 
1047   return 0;
1048 }
1049 
1050 /*
1051 ** Execute a statement or set of statements.  Print
1052 ** any result rows/columns depending on the current mode
1053 ** set via the supplied callback.
1054 **
1055 ** This is very similar to SQLite's built-in sqlite3_exec()
1056 ** function except it takes a slightly different callback
1057 ** and callback data argument.
1058 */
shell_exec(sqlite3 * db,const char * zSql,int (* xCallback)(void *,int,char **,char **,int *),struct callback_data * pArg,char ** pzErrMsg)1059 static int shell_exec(
1060   sqlite3 *db,                                /* An open database */
1061   const char *zSql,                           /* SQL to be evaluated */
1062   int (*xCallback)(void*,int,char**,char**,int*),   /* Callback function */
1063                                               /* (not the same as sqlite3_exec) */
1064   struct callback_data *pArg,                 /* Pointer to struct callback_data */
1065   char **pzErrMsg                             /* Error msg written here */
1066 ){
1067   sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
1068   int rc = SQLITE_OK;             /* Return Code */
1069   const char *zLeftover;          /* Tail of unprocessed SQL */
1070 
1071   if( pzErrMsg ){
1072     *pzErrMsg = NULL;
1073   }
1074 
1075   while( zSql[0] && (SQLITE_OK == rc) ){
1076     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
1077     if( SQLITE_OK != rc ){
1078       if( pzErrMsg ){
1079         *pzErrMsg = save_err_msg(db);
1080       }
1081     }else{
1082       if( !pStmt ){
1083         /* this happens for a comment or white-space */
1084         zSql = zLeftover;
1085         while( isspace(zSql[0]) ) zSql++;
1086         continue;
1087       }
1088 
1089       /* save off the prepared statment handle and reset row count */
1090       if( pArg ){
1091         pArg->pStmt = pStmt;
1092         pArg->cnt = 0;
1093       }
1094 
1095       /* echo the sql statement if echo on */
1096       if( pArg && pArg->echoOn ){
1097         const char *zStmtSql = sqlite3_sql(pStmt);
1098         fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
1099       }
1100 
1101       /* perform the first step.  this will tell us if we
1102       ** have a result set or not and how wide it is.
1103       */
1104       rc = sqlite3_step(pStmt);
1105       /* if we have a result set... */
1106       if( SQLITE_ROW == rc ){
1107         /* if we have a callback... */
1108         if( xCallback ){
1109           /* allocate space for col name ptr, value ptr, and type */
1110           int nCol = sqlite3_column_count(pStmt);
1111           void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
1112           if( !pData ){
1113             rc = SQLITE_NOMEM;
1114           }else{
1115             char **azCols = (char **)pData;      /* Names of result columns */
1116             char **azVals = &azCols[nCol];       /* Results */
1117             int *aiTypes = (int *)&azVals[nCol]; /* Result types */
1118             int i;
1119             assert(sizeof(int) <= sizeof(char *));
1120             /* save off ptrs to column names */
1121             for(i=0; i<nCol; i++){
1122               azCols[i] = (char *)sqlite3_column_name(pStmt, i);
1123             }
1124             do{
1125               /* extract the data and data types */
1126               for(i=0; i<nCol; i++){
1127                 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
1128                 aiTypes[i] = sqlite3_column_type(pStmt, i);
1129                 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
1130                   rc = SQLITE_NOMEM;
1131                   break; /* from for */
1132                 }
1133               } /* end for */
1134 
1135               /* if data and types extracted successfully... */
1136               if( SQLITE_ROW == rc ){
1137                 /* call the supplied callback with the result row data */
1138                 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
1139                   rc = SQLITE_ABORT;
1140                 }else{
1141                   rc = sqlite3_step(pStmt);
1142                 }
1143               }
1144             } while( SQLITE_ROW == rc );
1145             sqlite3_free(pData);
1146           }
1147         }else{
1148           do{
1149             rc = sqlite3_step(pStmt);
1150           } while( rc == SQLITE_ROW );
1151         }
1152       }
1153 
1154       /* print usage stats if stats on */
1155       if( pArg && pArg->statsOn ){
1156         display_stats(db, pArg, 0);
1157       }
1158 
1159       /* Finalize the statement just executed. If this fails, save a
1160       ** copy of the error message. Otherwise, set zSql to point to the
1161       ** next statement to execute. */
1162       rc = sqlite3_finalize(pStmt);
1163       if( rc==SQLITE_OK ){
1164         zSql = zLeftover;
1165         while( isspace(zSql[0]) ) zSql++;
1166       }else if( pzErrMsg ){
1167         *pzErrMsg = save_err_msg(db);
1168       }
1169 
1170       /* clear saved stmt handle */
1171       if( pArg ){
1172         pArg->pStmt = NULL;
1173       }
1174     }
1175   } /* end while */
1176 
1177   return rc;
1178 }
1179 
1180 
1181 /*
1182 ** This is a different callback routine used for dumping the database.
1183 ** Each row received by this callback consists of a table name,
1184 ** the table type ("index" or "table") and SQL to create the table.
1185 ** This routine should print text sufficient to recreate the table.
1186 */
dump_callback(void * pArg,int nArg,char ** azArg,char ** azCol)1187 static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
1188   int rc;
1189   const char *zTable;
1190   const char *zType;
1191   const char *zSql;
1192   const char *zPrepStmt = 0;
1193   struct callback_data *p = (struct callback_data *)pArg;
1194 
1195   UNUSED_PARAMETER(azCol);
1196   if( nArg!=3 ) return 1;
1197   zTable = azArg[0];
1198   zType = azArg[1];
1199   zSql = azArg[2];
1200 
1201   if( strcmp(zTable, "sqlite_sequence")==0 ){
1202     zPrepStmt = "DELETE FROM sqlite_sequence;\n";
1203   }else if( strcmp(zTable, "sqlite_stat1")==0 ){
1204     fprintf(p->out, "ANALYZE sqlite_master;\n");
1205   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
1206     return 0;
1207   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
1208     char *zIns;
1209     if( !p->writableSchema ){
1210       fprintf(p->out, "PRAGMA writable_schema=ON;\n");
1211       p->writableSchema = 1;
1212     }
1213     zIns = sqlite3_mprintf(
1214        "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
1215        "VALUES('table','%q','%q',0,'%q');",
1216        zTable, zTable, zSql);
1217     fprintf(p->out, "%s\n", zIns);
1218     sqlite3_free(zIns);
1219     return 0;
1220   }else{
1221     fprintf(p->out, "%s;\n", zSql);
1222   }
1223 
1224   if( strcmp(zType, "table")==0 ){
1225     sqlite3_stmt *pTableInfo = 0;
1226     char *zSelect = 0;
1227     char *zTableInfo = 0;
1228     char *zTmp = 0;
1229     int nRow = 0;
1230 
1231     zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
1232     zTableInfo = appendText(zTableInfo, zTable, '"');
1233     zTableInfo = appendText(zTableInfo, ");", 0);
1234 
1235     rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
1236     free(zTableInfo);
1237     if( rc!=SQLITE_OK || !pTableInfo ){
1238       return 1;
1239     }
1240 
1241     zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
1242     zTmp = appendText(zTmp, zTable, '"');
1243     if( zTmp ){
1244       zSelect = appendText(zSelect, zTmp, '\'');
1245     }
1246     zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
1247     rc = sqlite3_step(pTableInfo);
1248     while( rc==SQLITE_ROW ){
1249       const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
1250       zSelect = appendText(zSelect, "quote(", 0);
1251       zSelect = appendText(zSelect, zText, '"');
1252       rc = sqlite3_step(pTableInfo);
1253       if( rc==SQLITE_ROW ){
1254         zSelect = appendText(zSelect, ") || ',' || ", 0);
1255       }else{
1256         zSelect = appendText(zSelect, ") ", 0);
1257       }
1258       nRow++;
1259     }
1260     rc = sqlite3_finalize(pTableInfo);
1261     if( rc!=SQLITE_OK || nRow==0 ){
1262       free(zSelect);
1263       return 1;
1264     }
1265     zSelect = appendText(zSelect, "|| ')' FROM  ", 0);
1266     zSelect = appendText(zSelect, zTable, '"');
1267 
1268     rc = run_table_dump_query(p->out, p->db, zSelect, zPrepStmt);
1269     if( rc==SQLITE_CORRUPT ){
1270       zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
1271       rc = run_table_dump_query(p->out, p->db, zSelect, 0);
1272     }
1273     if( zSelect ) free(zSelect);
1274   }
1275   return 0;
1276 }
1277 
1278 /*
1279 ** Run zQuery.  Use dump_callback() as the callback routine so that
1280 ** the contents of the query are output as SQL statements.
1281 **
1282 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
1283 ** "ORDER BY rowid DESC" to the end.
1284 */
run_schema_dump_query(struct callback_data * p,const char * zQuery,char ** pzErrMsg)1285 static int run_schema_dump_query(
1286   struct callback_data *p,
1287   const char *zQuery,
1288   char **pzErrMsg
1289 ){
1290   int rc;
1291   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, pzErrMsg);
1292   if( rc==SQLITE_CORRUPT ){
1293     char *zQ2;
1294     int len = strlen30(zQuery);
1295     if( pzErrMsg ) sqlite3_free(*pzErrMsg);
1296     zQ2 = malloc( len+100 );
1297     if( zQ2==0 ) return rc;
1298     sqlite3_snprintf(sizeof(zQ2), zQ2, "%s ORDER BY rowid DESC", zQuery);
1299     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, pzErrMsg);
1300     free(zQ2);
1301   }
1302   return rc;
1303 }
1304 
1305 /*
1306 ** Text of a help message
1307 */
1308 static char zHelp[] =
1309   ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
1310   ".bail ON|OFF           Stop after hitting an error.  Default OFF\n"
1311   ".databases             List names and files of attached databases\n"
1312   ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
1313   "                         If TABLE specified, only dump tables matching\n"
1314   "                         LIKE pattern TABLE.\n"
1315   ".echo ON|OFF           Turn command echo on or off\n"
1316   ".exit                  Exit this program\n"
1317   ".explain ?ON|OFF?      Turn output mode suitable for EXPLAIN on or off.\n"
1318   "                         With no args, it turns EXPLAIN on.\n"
1319   ".header(s) ON|OFF      Turn display of headers on or off\n"
1320   ".help                  Show this message\n"
1321   ".import FILE TABLE     Import data from FILE into TABLE\n"
1322   ".indices ?TABLE?       Show names of all indices\n"
1323   "                         If TABLE specified, only show indices for tables\n"
1324   "                         matching LIKE pattern TABLE.\n"
1325 #ifdef SQLITE_ENABLE_IOTRACE
1326   ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
1327 #endif
1328 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1329   ".load FILE ?ENTRY?     Load an extension library\n"
1330 #endif
1331   ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
1332   ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
1333   "                         csv      Comma-separated values\n"
1334   "                         column   Left-aligned columns.  (See .width)\n"
1335   "                         html     HTML <table> code\n"
1336   "                         insert   SQL insert statements for TABLE\n"
1337   "                         line     One value per line\n"
1338   "                         list     Values delimited by .separator string\n"
1339   "                         tabs     Tab-separated values\n"
1340   "                         tcl      TCL list elements\n"
1341   ".nullvalue STRING      Print STRING in place of NULL values\n"
1342   ".output FILENAME       Send output to FILENAME\n"
1343   ".output stdout         Send output to the screen\n"
1344   ".prompt MAIN CONTINUE  Replace the standard prompts\n"
1345   ".quit                  Exit this program\n"
1346   ".read FILENAME         Execute SQL in FILENAME\n"
1347   ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
1348   ".schema ?TABLE?        Show the CREATE statements\n"
1349   "                         If TABLE specified, only show tables matching\n"
1350   "                         LIKE pattern TABLE.\n"
1351   ".separator STRING      Change separator used by output mode and .import\n"
1352   ".show                  Show the current values for various settings\n"
1353   ".stats ON|OFF          Turn stats on or off\n"
1354   ".tables ?TABLE?        List names of tables\n"
1355   "                         If TABLE specified, only list tables matching\n"
1356   "                         LIKE pattern TABLE.\n"
1357   ".timeout MS            Try opening locked tables for MS milliseconds\n"
1358   ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
1359 ;
1360 
1361 static char zTimerHelp[] =
1362   ".timer ON|OFF          Turn the CPU timer measurement on or off\n"
1363 ;
1364 
1365 /* Forward reference */
1366 static int process_input(struct callback_data *p, FILE *in);
1367 
1368 /*
1369 ** Make sure the database is open.  If it is not, then open it.  If
1370 ** the database fails to open, print an error message and exit.
1371 */
open_db(struct callback_data * p)1372 static void open_db(struct callback_data *p){
1373   if( p->db==0 ){
1374     sqlite3_open(p->zDbFilename, &p->db);
1375     db = p->db;
1376     if( db && sqlite3_errcode(db)==SQLITE_OK ){
1377       sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
1378           shellstaticFunc, 0, 0);
1379     }
1380     if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
1381       fprintf(stderr,"Error: unable to open database \"%s\": %s\n",
1382           p->zDbFilename, sqlite3_errmsg(db));
1383       exit(1);
1384     }
1385 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1386     sqlite3_enable_load_extension(p->db, 1);
1387 #endif
1388     // Begin Android Add
1389     #ifndef NO_ANDROID_FUNCS
1390         int err = register_localized_collators(db, "en_US", 0);
1391         if (err != SQLITE_OK) {
1392           fprintf(stderr, "register_localized_collators() failed\n");
1393           exit(1);
1394         }
1395         err = register_android_functions(db, 0);
1396         if (err != SQLITE_OK) {
1397           fprintf(stderr, "register_android_functions() failed\n");
1398           exit(1);
1399         }
1400     #endif
1401     // End Android Add
1402   }
1403 }
1404 
1405 /*
1406 ** Do C-language style dequoting.
1407 **
1408 **    \t    -> tab
1409 **    \n    -> newline
1410 **    \r    -> carriage return
1411 **    \NNN  -> ascii character NNN in octal
1412 **    \\    -> backslash
1413 */
resolve_backslashes(char * z)1414 static void resolve_backslashes(char *z){
1415   int i, j;
1416   char c;
1417   for(i=j=0; (c = z[i])!=0; i++, j++){
1418     if( c=='\\' ){
1419       c = z[++i];
1420       if( c=='n' ){
1421         c = '\n';
1422       }else if( c=='t' ){
1423         c = '\t';
1424       }else if( c=='r' ){
1425         c = '\r';
1426       }else if( c>='0' && c<='7' ){
1427         c -= '0';
1428         if( z[i+1]>='0' && z[i+1]<='7' ){
1429           i++;
1430           c = (c<<3) + z[i] - '0';
1431           if( z[i+1]>='0' && z[i+1]<='7' ){
1432             i++;
1433             c = (c<<3) + z[i] - '0';
1434           }
1435         }
1436       }
1437     }
1438     z[j] = c;
1439   }
1440   z[j] = 0;
1441 }
1442 
1443 /*
1444 ** Interpret zArg as a boolean value.  Return either 0 or 1.
1445 */
booleanValue(char * zArg)1446 static int booleanValue(char *zArg){
1447   int val = atoi(zArg);
1448   int j;
1449   for(j=0; zArg[j]; j++){
1450     zArg[j] = (char)tolower(zArg[j]);
1451   }
1452   if( strcmp(zArg,"on")==0 ){
1453     val = 1;
1454   }else if( strcmp(zArg,"yes")==0 ){
1455     val = 1;
1456   }
1457   return val;
1458 }
1459 
1460 /*
1461 ** If an input line begins with "." then invoke this routine to
1462 ** process that line.
1463 **
1464 ** Return 1 on error, 2 to exit, and 0 otherwise.
1465 */
do_meta_command(char * zLine,struct callback_data * p)1466 static int do_meta_command(char *zLine, struct callback_data *p){
1467   int i = 1;
1468   int nArg = 0;
1469   int n, c;
1470   int rc = 0;
1471   char *azArg[50];
1472 
1473   /* Parse the input line into tokens.
1474   */
1475   while( zLine[i] && nArg<ArraySize(azArg) ){
1476     while( isspace((unsigned char)zLine[i]) ){ i++; }
1477     if( zLine[i]==0 ) break;
1478     if( zLine[i]=='\'' || zLine[i]=='"' ){
1479       int delim = zLine[i++];
1480       azArg[nArg++] = &zLine[i];
1481       while( zLine[i] && zLine[i]!=delim ){ i++; }
1482       if( zLine[i]==delim ){
1483         zLine[i++] = 0;
1484       }
1485       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
1486     }else{
1487       azArg[nArg++] = &zLine[i];
1488       while( zLine[i] && !isspace((unsigned char)zLine[i]) ){ i++; }
1489       if( zLine[i] ) zLine[i++] = 0;
1490       resolve_backslashes(azArg[nArg-1]);
1491     }
1492   }
1493 
1494   /* Process the input line.
1495   */
1496   if( nArg==0 ) return 0; /* no tokens, no error */
1497   n = strlen30(azArg[0]);
1498   c = azArg[0][0];
1499   if( c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0 && nArg>1 && nArg<4){
1500     const char *zDestFile;
1501     const char *zDb;
1502     sqlite3 *pDest;
1503     sqlite3_backup *pBackup;
1504     if( nArg==2 ){
1505       zDestFile = azArg[1];
1506       zDb = "main";
1507     }else{
1508       zDestFile = azArg[2];
1509       zDb = azArg[1];
1510     }
1511     rc = sqlite3_open(zDestFile, &pDest);
1512     if( rc!=SQLITE_OK ){
1513       fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
1514       sqlite3_close(pDest);
1515       return 1;
1516     }
1517     open_db(p);
1518     pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
1519     if( pBackup==0 ){
1520       fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
1521       sqlite3_close(pDest);
1522       return 1;
1523     }
1524     while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1525     sqlite3_backup_finish(pBackup);
1526     if( rc==SQLITE_DONE ){
1527       rc = 0;
1528     }else{
1529       fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
1530       rc = 1;
1531     }
1532     sqlite3_close(pDest);
1533   }else
1534 
1535   if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){
1536     bail_on_error = booleanValue(azArg[1]);
1537   }else
1538 
1539   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){
1540     struct callback_data data;
1541     char *zErrMsg = 0;
1542     open_db(p);
1543     memcpy(&data, p, sizeof(data));
1544     data.showHeader = 1;
1545     data.mode = MODE_Column;
1546     data.colWidth[0] = 3;
1547     data.colWidth[1] = 15;
1548     data.colWidth[2] = 58;
1549     data.cnt = 0;
1550     sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
1551     if( zErrMsg ){
1552       fprintf(stderr,"Error: %s\n", zErrMsg);
1553       sqlite3_free(zErrMsg);
1554       rc = 1;
1555     }
1556   }else
1557 
1558   if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){
1559     char *zErrMsg = 0;
1560     open_db(p);
1561     /* When playing back a "dump", the content might appear in an order
1562     ** which causes immediate foreign key constraints to be violated.
1563     ** So disable foreign-key constraint enforcement to prevent problems. */
1564     fprintf(p->out, "PRAGMA foreign_keys=OFF;\n");
1565     fprintf(p->out, "BEGIN TRANSACTION;\n");
1566     p->writableSchema = 0;
1567     sqlite3_exec(p->db, "PRAGMA writable_schema=ON", 0, 0, 0);
1568     if( nArg==1 ){
1569       run_schema_dump_query(p,
1570         "SELECT name, type, sql FROM sqlite_master "
1571         "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'", 0
1572       );
1573       run_schema_dump_query(p,
1574         "SELECT name, type, sql FROM sqlite_master "
1575         "WHERE name=='sqlite_sequence'", 0
1576       );
1577       run_table_dump_query(p->out, p->db,
1578         "SELECT sql FROM sqlite_master "
1579         "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
1580       );
1581     }else{
1582       int i;
1583       for(i=1; i<nArg; i++){
1584         zShellStatic = azArg[i];
1585         run_schema_dump_query(p,
1586           "SELECT name, type, sql FROM sqlite_master "
1587           "WHERE tbl_name LIKE shellstatic() AND type=='table'"
1588           "  AND sql NOT NULL", 0);
1589         run_table_dump_query(p->out, p->db,
1590           "SELECT sql FROM sqlite_master "
1591           "WHERE sql NOT NULL"
1592           "  AND type IN ('index','trigger','view')"
1593           "  AND tbl_name LIKE shellstatic()", 0
1594         );
1595         zShellStatic = 0;
1596       }
1597     }
1598     if( p->writableSchema ){
1599       fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
1600       p->writableSchema = 0;
1601     }
1602     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF", 0, 0, 0);
1603     if( zErrMsg ){
1604       fprintf(stderr,"Error: %s\n", zErrMsg);
1605       sqlite3_free(zErrMsg);
1606     }else{
1607       fprintf(p->out, "COMMIT;\n");
1608     }
1609   }else
1610 
1611   if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){
1612     p->echoOn = booleanValue(azArg[1]);
1613   }else
1614 
1615   if( c=='e' && strncmp(azArg[0], "exit", n)==0  && nArg==1 ){
1616     rc = 2;
1617   }else
1618 
1619   if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){
1620     int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
1621     if(val == 1) {
1622       if(!p->explainPrev.valid) {
1623         p->explainPrev.valid = 1;
1624         p->explainPrev.mode = p->mode;
1625         p->explainPrev.showHeader = p->showHeader;
1626         memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
1627       }
1628       /* We could put this code under the !p->explainValid
1629       ** condition so that it does not execute if we are already in
1630       ** explain mode. However, always executing it allows us an easy
1631       ** was to reset to explain mode in case the user previously
1632       ** did an .explain followed by a .width, .mode or .header
1633       ** command.
1634       */
1635       p->mode = MODE_Explain;
1636       p->showHeader = 1;
1637       memset(p->colWidth,0,ArraySize(p->colWidth));
1638       p->colWidth[0] = 4;                  /* addr */
1639       p->colWidth[1] = 13;                 /* opcode */
1640       p->colWidth[2] = 4;                  /* P1 */
1641       p->colWidth[3] = 4;                  /* P2 */
1642       p->colWidth[4] = 4;                  /* P3 */
1643       p->colWidth[5] = 13;                 /* P4 */
1644       p->colWidth[6] = 2;                  /* P5 */
1645       p->colWidth[7] = 13;                  /* Comment */
1646     }else if (p->explainPrev.valid) {
1647       p->explainPrev.valid = 0;
1648       p->mode = p->explainPrev.mode;
1649       p->showHeader = p->explainPrev.showHeader;
1650       memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
1651     }
1652   }else
1653 
1654   if( c=='h' && (strncmp(azArg[0], "header", n)==0 ||
1655                  strncmp(azArg[0], "headers", n)==0) && nArg>1 && nArg<3 ){
1656     p->showHeader = booleanValue(azArg[1]);
1657   }else
1658 
1659   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
1660     fprintf(stderr,"%s",zHelp);
1661     if( HAS_TIMER ){
1662       fprintf(stderr,"%s",zTimerHelp);
1663     }
1664   }else
1665 
1666   if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){
1667     char *zTable = azArg[2];    /* Insert data into this table */
1668     char *zFile = azArg[1];     /* The file from which to extract data */
1669     sqlite3_stmt *pStmt = NULL; /* A statement */
1670     int nCol;                   /* Number of columns in the table */
1671     int nByte;                  /* Number of bytes in an SQL string */
1672     int i, j;                   /* Loop counters */
1673     int nSep;                   /* Number of bytes in p->separator[] */
1674     char *zSql;                 /* An SQL statement */
1675     char *zLine;                /* A single line of input from the file */
1676     char **azCol;               /* zLine[] broken up into columns */
1677     char *zCommit;              /* How to commit changes */
1678     FILE *in;                   /* The input file */
1679     int lineno = 0;             /* Line number of input file */
1680 
1681     open_db(p);
1682     nSep = strlen30(p->separator);
1683     if( nSep==0 ){
1684       fprintf(stderr, "Error: non-null separator required for import\n");
1685       return 1;
1686     }
1687     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1688     if( zSql==0 ){
1689       fprintf(stderr, "Error: out of memory\n");
1690       return 1;
1691     }
1692     nByte = strlen30(zSql);
1693     rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
1694     sqlite3_free(zSql);
1695     if( rc ){
1696       if (pStmt) sqlite3_finalize(pStmt);
1697       fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
1698       return 1;
1699     }
1700     nCol = sqlite3_column_count(pStmt);
1701     sqlite3_finalize(pStmt);
1702     pStmt = 0;
1703     if( nCol==0 ) return 0; /* no columns, no error */
1704     zSql = malloc( nByte + 20 + nCol*2 );
1705     if( zSql==0 ){
1706       fprintf(stderr, "Error: out of memory\n");
1707       return 1;
1708     }
1709     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO '%q' VALUES(?", zTable);
1710     j = strlen30(zSql);
1711     for(i=1; i<nCol; i++){
1712       zSql[j++] = ',';
1713       zSql[j++] = '?';
1714     }
1715     zSql[j++] = ')';
1716     zSql[j] = 0;
1717     rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
1718     free(zSql);
1719     if( rc ){
1720       fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
1721       if (pStmt) sqlite3_finalize(pStmt);
1722       return 1;
1723     }
1724     in = fopen(zFile, "rb");
1725     if( in==0 ){
1726       fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
1727       sqlite3_finalize(pStmt);
1728       return 1;
1729     }
1730     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1731     if( azCol==0 ){
1732       fprintf(stderr, "Error: out of memory\n");
1733       fclose(in);
1734       sqlite3_finalize(pStmt);
1735       return 1;
1736     }
1737     sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
1738     zCommit = "COMMIT";
1739     while( (zLine = local_getline(0, in))!=0 ){
1740       char *z;
1741       i = 0;
1742       lineno++;
1743       azCol[0] = zLine;
1744       for(i=0, z=zLine; *z && *z!='\n' && *z!='\r'; z++){
1745         if( *z==p->separator[0] && strncmp(z, p->separator, nSep)==0 ){
1746           *z = 0;
1747           i++;
1748           if( i<nCol ){
1749             azCol[i] = &z[nSep];
1750             z += nSep-1;
1751           }
1752         }
1753       } /* end for */
1754       *z = 0;
1755       if( i+1!=nCol ){
1756         fprintf(stderr,
1757                 "Error: %s line %d: expected %d columns of data but found %d\n",
1758                 zFile, lineno, nCol, i+1);
1759         zCommit = "ROLLBACK";
1760         free(zLine);
1761         rc = 1;
1762         break; /* from while */
1763       }
1764       for(i=0; i<nCol; i++){
1765         sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1766       }
1767       sqlite3_step(pStmt);
1768       rc = sqlite3_reset(pStmt);
1769       free(zLine);
1770       if( rc!=SQLITE_OK ){
1771         fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
1772         zCommit = "ROLLBACK";
1773         rc = 1;
1774         break; /* from while */
1775       }
1776     } /* end while */
1777     free(azCol);
1778     fclose(in);
1779     sqlite3_finalize(pStmt);
1780     sqlite3_exec(p->db, zCommit, 0, 0, 0);
1781   }else
1782 
1783   if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){
1784     struct callback_data data;
1785     char *zErrMsg = 0;
1786     open_db(p);
1787     memcpy(&data, p, sizeof(data));
1788     data.showHeader = 0;
1789     data.mode = MODE_List;
1790     if( nArg==1 ){
1791       rc = sqlite3_exec(p->db,
1792         "SELECT name FROM sqlite_master "
1793         "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
1794         "UNION ALL "
1795         "SELECT name FROM sqlite_temp_master "
1796         "WHERE type='index' "
1797         "ORDER BY 1",
1798         callback, &data, &zErrMsg
1799       );
1800     }else{
1801       zShellStatic = azArg[1];
1802       rc = sqlite3_exec(p->db,
1803         "SELECT name FROM sqlite_master "
1804         "WHERE type='index' AND tbl_name LIKE shellstatic() "
1805         "UNION ALL "
1806         "SELECT name FROM sqlite_temp_master "
1807         "WHERE type='index' AND tbl_name LIKE shellstatic() "
1808         "ORDER BY 1",
1809         callback, &data, &zErrMsg
1810       );
1811       zShellStatic = 0;
1812     }
1813     if( zErrMsg ){
1814       fprintf(stderr,"Error: %s\n", zErrMsg);
1815       sqlite3_free(zErrMsg);
1816       rc = 1;
1817     }else if( rc != SQLITE_OK ){
1818       fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
1819       rc = 1;
1820     }
1821   }else
1822 
1823 #ifdef SQLITE_ENABLE_IOTRACE
1824   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
1825     extern void (*sqlite3IoTrace)(const char*, ...);
1826     if( iotrace && iotrace!=stdout ) fclose(iotrace);
1827     iotrace = 0;
1828     if( nArg<2 ){
1829       sqlite3IoTrace = 0;
1830     }else if( strcmp(azArg[1], "-")==0 ){
1831       sqlite3IoTrace = iotracePrintf;
1832       iotrace = stdout;
1833     }else{
1834       iotrace = fopen(azArg[1], "w");
1835       if( iotrace==0 ){
1836         fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
1837         sqlite3IoTrace = 0;
1838         rc = 1;
1839       }else{
1840         sqlite3IoTrace = iotracePrintf;
1841       }
1842     }
1843   }else
1844 #endif
1845 
1846 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1847   if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){
1848     const char *zFile, *zProc;
1849     char *zErrMsg = 0;
1850     zFile = azArg[1];
1851     zProc = nArg>=3 ? azArg[2] : 0;
1852     open_db(p);
1853     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
1854     if( rc!=SQLITE_OK ){
1855       fprintf(stderr, "Error: %s\n", zErrMsg);
1856       sqlite3_free(zErrMsg);
1857       rc = 1;
1858     }
1859   }else
1860 #endif
1861 
1862   if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=1 ){
1863     const char *zFile = azArg[1];
1864     if( p->pLog && p->pLog!=stdout && p->pLog!=stderr ){
1865       fclose(p->pLog);
1866       p->pLog = 0;
1867     }
1868     if( strcmp(zFile,"stdout")==0 ){
1869       p->pLog = stdout;
1870     }else if( strcmp(zFile, "stderr")==0 ){
1871       p->pLog = stderr;
1872     }else if( strcmp(zFile, "off")==0 ){
1873       p->pLog = 0;
1874     }else{
1875       p->pLog = fopen(zFile, "w");
1876       if( p->pLog==0 ){
1877         fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
1878       }
1879     }
1880   }else
1881 
1882   if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==2 ){
1883     int n2 = strlen30(azArg[1]);
1884     if( (n2==4 && strncmp(azArg[1],"line",n2)==0)
1885         ||
1886         (n2==5 && strncmp(azArg[1],"lines",n2)==0) ){
1887       p->mode = MODE_Line;
1888     }else if( (n2==6 && strncmp(azArg[1],"column",n2)==0)
1889               ||
1890               (n2==7 && strncmp(azArg[1],"columns",n2)==0) ){
1891       p->mode = MODE_Column;
1892     }else if( n2==4 && strncmp(azArg[1],"list",n2)==0 ){
1893       p->mode = MODE_List;
1894     }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){
1895       p->mode = MODE_Html;
1896     }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){
1897       p->mode = MODE_Tcl;
1898     }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){
1899       p->mode = MODE_Csv;
1900       sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
1901     }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){
1902       p->mode = MODE_List;
1903       sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
1904     }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
1905       p->mode = MODE_Insert;
1906       set_table_name(p, "table");
1907     }else {
1908       fprintf(stderr,"Error: mode should be one of: "
1909          "column csv html insert line list tabs tcl\n");
1910       rc = 1;
1911     }
1912   }else
1913 
1914   if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==3 ){
1915     int n2 = strlen30(azArg[1]);
1916     if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
1917       p->mode = MODE_Insert;
1918       set_table_name(p, azArg[2]);
1919     }else {
1920       fprintf(stderr, "Error: invalid arguments: "
1921         " \"%s\". Enter \".help\" for help\n", azArg[2]);
1922       rc = 1;
1923     }
1924   }else
1925 
1926   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
1927     sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
1928                      "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
1929   }else
1930 
1931   if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
1932     if( p->out!=stdout ){
1933       fclose(p->out);
1934     }
1935     if( strcmp(azArg[1],"stdout")==0 ){
1936       p->out = stdout;
1937       sqlite3_snprintf(sizeof(p->outfile), p->outfile, "stdout");
1938     }else{
1939       p->out = fopen(azArg[1], "wb");
1940       if( p->out==0 ){
1941         fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]);
1942         p->out = stdout;
1943         rc = 1;
1944       } else {
1945          sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
1946       }
1947     }
1948   }else
1949 
1950   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
1951     if( nArg >= 2) {
1952       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
1953     }
1954     if( nArg >= 3) {
1955       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
1956     }
1957   }else
1958 
1959   if( c=='q' && strncmp(azArg[0], "quit", n)==0 && nArg==1 ){
1960     rc = 2;
1961   }else
1962 
1963   if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
1964     FILE *alt = fopen(azArg[1], "rb");
1965     if( alt==0 ){
1966       fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
1967       rc = 1;
1968     }else{
1969       rc = process_input(p, alt);
1970       fclose(alt);
1971     }
1972   }else
1973 
1974   if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 && nArg<4){
1975     const char *zSrcFile;
1976     const char *zDb;
1977     sqlite3 *pSrc;
1978     sqlite3_backup *pBackup;
1979     int nTimeout = 0;
1980 
1981     if( nArg==2 ){
1982       zSrcFile = azArg[1];
1983       zDb = "main";
1984     }else{
1985       zSrcFile = azArg[2];
1986       zDb = azArg[1];
1987     }
1988     rc = sqlite3_open(zSrcFile, &pSrc);
1989     if( rc!=SQLITE_OK ){
1990       fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
1991       sqlite3_close(pSrc);
1992       return 1;
1993     }
1994     open_db(p);
1995     pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
1996     if( pBackup==0 ){
1997       fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
1998       sqlite3_close(pSrc);
1999       return 1;
2000     }
2001     while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2002           || rc==SQLITE_BUSY  ){
2003       if( rc==SQLITE_BUSY ){
2004         if( nTimeout++ >= 3 ) break;
2005         sqlite3_sleep(100);
2006       }
2007     }
2008     sqlite3_backup_finish(pBackup);
2009     if( rc==SQLITE_DONE ){
2010       rc = 0;
2011     }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2012       fprintf(stderr, "Error: source database is busy\n");
2013       rc = 1;
2014     }else{
2015       fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
2016       rc = 1;
2017     }
2018     sqlite3_close(pSrc);
2019   }else
2020 
2021   if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){
2022     struct callback_data data;
2023     char *zErrMsg = 0;
2024     open_db(p);
2025     memcpy(&data, p, sizeof(data));
2026     data.showHeader = 0;
2027     data.mode = MODE_Semi;
2028     if( nArg>1 ){
2029       int i;
2030       for(i=0; azArg[1][i]; i++) azArg[1][i] = (char)tolower(azArg[1][i]);
2031       if( strcmp(azArg[1],"sqlite_master")==0 ){
2032         char *new_argv[2], *new_colv[2];
2033         new_argv[0] = "CREATE TABLE sqlite_master (\n"
2034                       "  type text,\n"
2035                       "  name text,\n"
2036                       "  tbl_name text,\n"
2037                       "  rootpage integer,\n"
2038                       "  sql text\n"
2039                       ")";
2040         new_argv[1] = 0;
2041         new_colv[0] = "sql";
2042         new_colv[1] = 0;
2043         callback(&data, 1, new_argv, new_colv);
2044         rc = SQLITE_OK;
2045       }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
2046         char *new_argv[2], *new_colv[2];
2047         new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
2048                       "  type text,\n"
2049                       "  name text,\n"
2050                       "  tbl_name text,\n"
2051                       "  rootpage integer,\n"
2052                       "  sql text\n"
2053                       ")";
2054         new_argv[1] = 0;
2055         new_colv[0] = "sql";
2056         new_colv[1] = 0;
2057         callback(&data, 1, new_argv, new_colv);
2058         rc = SQLITE_OK;
2059       }else{
2060         zShellStatic = azArg[1];
2061         rc = sqlite3_exec(p->db,
2062           "SELECT sql FROM "
2063           "  (SELECT sql sql, type type, tbl_name tbl_name, name name"
2064           "     FROM sqlite_master UNION ALL"
2065           "   SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
2066           "WHERE tbl_name LIKE shellstatic() AND type!='meta' AND sql NOTNULL "
2067           "ORDER BY substr(type,2,1), name",
2068           callback, &data, &zErrMsg);
2069         zShellStatic = 0;
2070       }
2071     }else{
2072       rc = sqlite3_exec(p->db,
2073          "SELECT sql FROM "
2074          "  (SELECT sql sql, type type, tbl_name tbl_name, name name"
2075          "     FROM sqlite_master UNION ALL"
2076          "   SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
2077          "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
2078          "ORDER BY substr(type,2,1), name",
2079          callback, &data, &zErrMsg
2080       );
2081     }
2082     if( zErrMsg ){
2083       fprintf(stderr,"Error: %s\n", zErrMsg);
2084       sqlite3_free(zErrMsg);
2085       rc = 1;
2086     }else if( rc != SQLITE_OK ){
2087       fprintf(stderr,"Error: querying schema information\n");
2088       rc = 1;
2089     }else{
2090       rc = 0;
2091     }
2092   }else
2093 
2094   if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
2095     sqlite3_snprintf(sizeof(p->separator), p->separator,
2096                      "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
2097   }else
2098 
2099   if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){
2100     int i;
2101     fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
2102     fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
2103     fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
2104     fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
2105     fprintf(p->out,"%9.9s: ", "nullvalue");
2106       output_c_string(p->out, p->nullvalue);
2107       fprintf(p->out, "\n");
2108     fprintf(p->out,"%9.9s: %s\n","output",
2109             strlen30(p->outfile) ? p->outfile : "stdout");
2110     fprintf(p->out,"%9.9s: ", "separator");
2111       output_c_string(p->out, p->separator);
2112       fprintf(p->out, "\n");
2113     fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off");
2114     fprintf(p->out,"%9.9s: ","width");
2115     for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
2116       fprintf(p->out,"%d ",p->colWidth[i]);
2117     }
2118     fprintf(p->out,"\n");
2119   }else
2120 
2121   if( c=='s' && strncmp(azArg[0], "stats", n)==0 && nArg>1 && nArg<3 ){
2122     p->statsOn = booleanValue(azArg[1]);
2123   }else
2124 
2125   if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){
2126     char **azResult;
2127     int nRow;
2128     char *zErrMsg;
2129     open_db(p);
2130     if( nArg==1 ){
2131       rc = sqlite3_get_table(p->db,
2132         "SELECT name FROM sqlite_master "
2133         "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' "
2134         "UNION ALL "
2135         "SELECT name FROM sqlite_temp_master "
2136         "WHERE type IN ('table','view') "
2137         "ORDER BY 1",
2138         &azResult, &nRow, 0, &zErrMsg
2139       );
2140     }else{
2141       zShellStatic = azArg[1];
2142       rc = sqlite3_get_table(p->db,
2143         "SELECT name FROM sqlite_master "
2144         "WHERE type IN ('table','view') AND name LIKE shellstatic() "
2145         "UNION ALL "
2146         "SELECT name FROM sqlite_temp_master "
2147         "WHERE type IN ('table','view') AND name LIKE shellstatic() "
2148         "ORDER BY 1",
2149         &azResult, &nRow, 0, &zErrMsg
2150       );
2151       zShellStatic = 0;
2152     }
2153     if( zErrMsg ){
2154       fprintf(stderr,"Error: %s\n", zErrMsg);
2155       sqlite3_free(zErrMsg);
2156       rc = 1;
2157     }else if( rc != SQLITE_OK ){
2158       fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
2159       rc = 1;
2160     }else{
2161       int len, maxlen = 0;
2162       int i, j;
2163       int nPrintCol, nPrintRow;
2164       for(i=1; i<=nRow; i++){
2165         if( azResult[i]==0 ) continue;
2166         len = strlen30(azResult[i]);
2167         if( len>maxlen ) maxlen = len;
2168       }
2169       nPrintCol = 80/(maxlen+2);
2170       if( nPrintCol<1 ) nPrintCol = 1;
2171       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
2172       for(i=0; i<nPrintRow; i++){
2173         for(j=i+1; j<=nRow; j+=nPrintRow){
2174           char *zSp = j<=nPrintRow ? "" : "  ";
2175           printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
2176         }
2177         printf("\n");
2178       }
2179     }
2180     sqlite3_free_table(azResult);
2181   }else
2182 
2183   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){
2184     open_db(p);
2185     sqlite3_busy_timeout(p->db, atoi(azArg[1]));
2186   }else
2187 
2188   if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 && nArg==2 ){
2189     enableTimer = booleanValue(azArg[1]);
2190   }else
2191 
2192   if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){
2193     int j;
2194     assert( nArg<=ArraySize(azArg) );
2195     for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
2196       p->colWidth[j-1] = atoi(azArg[j]);
2197     }
2198   }else
2199 
2200   {
2201     fprintf(stderr, "Error: unknown command or invalid arguments: "
2202       " \"%s\". Enter \".help\" for help\n", azArg[0]);
2203     rc = 1;
2204   }
2205 
2206   return rc;
2207 }
2208 
2209 /*
2210 ** Return TRUE if a semicolon occurs anywhere in the first N characters
2211 ** of string z[].
2212 */
_contains_semicolon(const char * z,int N)2213 static int _contains_semicolon(const char *z, int N){
2214   int i;
2215   for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
2216   return 0;
2217 }
2218 
2219 /*
2220 ** Test to see if a line consists entirely of whitespace.
2221 */
_all_whitespace(const char * z)2222 static int _all_whitespace(const char *z){
2223   for(; *z; z++){
2224     if( isspace(*(unsigned char*)z) ) continue;
2225     if( *z=='/' && z[1]=='*' ){
2226       z += 2;
2227       while( *z && (*z!='*' || z[1]!='/') ){ z++; }
2228       if( *z==0 ) return 0;
2229       z++;
2230       continue;
2231     }
2232     if( *z=='-' && z[1]=='-' ){
2233       z += 2;
2234       while( *z && *z!='\n' ){ z++; }
2235       if( *z==0 ) return 1;
2236       continue;
2237     }
2238     return 0;
2239   }
2240   return 1;
2241 }
2242 
2243 /*
2244 ** Return TRUE if the line typed in is an SQL command terminator other
2245 ** than a semi-colon.  The SQL Server style "go" command is understood
2246 ** as is the Oracle "/".
2247 */
_is_command_terminator(const char * zLine)2248 static int _is_command_terminator(const char *zLine){
2249   while( isspace(*(unsigned char*)zLine) ){ zLine++; };
2250   if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
2251     return 1;  /* Oracle */
2252   }
2253   if( tolower(zLine[0])=='g' && tolower(zLine[1])=='o'
2254          && _all_whitespace(&zLine[2]) ){
2255     return 1;  /* SQL Server */
2256   }
2257   return 0;
2258 }
2259 
2260 /*
2261 ** Return true if zSql is a complete SQL statement.  Return false if it
2262 ** ends in the middle of a string literal or C-style comment.
2263 */
_is_complete(char * zSql,int nSql)2264 static int _is_complete(char *zSql, int nSql){
2265   int rc;
2266   if( zSql==0 ) return 1;
2267   zSql[nSql] = ';';
2268   zSql[nSql+1] = 0;
2269   rc = sqlite3_complete(zSql);
2270   zSql[nSql] = 0;
2271   return rc;
2272 }
2273 
2274 /*
2275 ** Read input from *in and process it.  If *in==0 then input
2276 ** is interactive - the user is typing it it.  Otherwise, input
2277 ** is coming from a file or device.  A prompt is issued and history
2278 ** is saved only if input is interactive.  An interrupt signal will
2279 ** cause this routine to exit immediately, unless input is interactive.
2280 **
2281 ** Return the number of errors.
2282 */
process_input(struct callback_data * p,FILE * in)2283 static int process_input(struct callback_data *p, FILE *in){
2284   char *zLine = 0;
2285   char *zSql = 0;
2286   int nSql = 0;
2287   int nSqlPrior = 0;
2288   char *zErrMsg;
2289   int rc;
2290   int errCnt = 0;
2291   int lineno = 0;
2292   int startline = 0;
2293 
2294   while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
2295     fflush(p->out);
2296     free(zLine);
2297     zLine = one_input_line(zSql, in);
2298     if( zLine==0 ){
2299       break;  /* We have reached EOF */
2300     }
2301     if( seenInterrupt ){
2302       if( in!=0 ) break;
2303       seenInterrupt = 0;
2304     }
2305     lineno++;
2306     if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
2307     if( zLine && zLine[0]=='.' && nSql==0 ){
2308       if( p->echoOn ) printf("%s\n", zLine);
2309       rc = do_meta_command(zLine, p);
2310       if( rc==2 ){ /* exit requested */
2311         break;
2312       }else if( rc ){
2313         errCnt++;
2314       }
2315       continue;
2316     }
2317     if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){
2318       memcpy(zLine,";",2);
2319     }
2320     nSqlPrior = nSql;
2321     if( zSql==0 ){
2322       int i;
2323       for(i=0; zLine[i] && isspace((unsigned char)zLine[i]); i++){}
2324       if( zLine[i]!=0 ){
2325         nSql = strlen30(zLine);
2326         zSql = malloc( nSql+3 );
2327         if( zSql==0 ){
2328           fprintf(stderr, "Error: out of memory\n");
2329           exit(1);
2330         }
2331         memcpy(zSql, zLine, nSql+1);
2332         startline = lineno;
2333       }
2334     }else{
2335       int len = strlen30(zLine);
2336       zSql = realloc( zSql, nSql + len + 4 );
2337       if( zSql==0 ){
2338         fprintf(stderr,"Error: out of memory\n");
2339         exit(1);
2340       }
2341       zSql[nSql++] = '\n';
2342       memcpy(&zSql[nSql], zLine, len+1);
2343       nSql += len;
2344     }
2345     if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
2346                 && sqlite3_complete(zSql) ){
2347       p->cnt = 0;
2348       open_db(p);
2349       BEGIN_TIMER;
2350       rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
2351       END_TIMER;
2352       if( rc || zErrMsg ){
2353         char zPrefix[100];
2354         if( in!=0 || !stdin_is_interactive ){
2355           sqlite3_snprintf(sizeof(zPrefix), zPrefix,
2356                            "Error: near line %d:", startline);
2357         }else{
2358           sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
2359         }
2360         if( zErrMsg!=0 ){
2361           fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
2362           sqlite3_free(zErrMsg);
2363           zErrMsg = 0;
2364         }else{
2365           fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
2366         }
2367         errCnt++;
2368       }
2369       free(zSql);
2370       zSql = 0;
2371       nSql = 0;
2372     }
2373   }
2374   if( zSql ){
2375     if( !_all_whitespace(zSql) ) fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
2376     free(zSql);
2377   }
2378   free(zLine);
2379   return errCnt;
2380 }
2381 
2382 /*
2383 ** Return a pathname which is the user's home directory.  A
2384 ** 0 return indicates an error of some kind.  Space to hold the
2385 ** resulting string is obtained from malloc().  The calling
2386 ** function should free the result.
2387 */
find_home_dir(void)2388 static char *find_home_dir(void){
2389   char *home_dir = NULL;
2390 
2391 #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL)
2392   struct passwd *pwent;
2393   uid_t uid = getuid();
2394   if( (pwent=getpwuid(uid)) != NULL) {
2395     home_dir = pwent->pw_dir;
2396   }
2397 #endif
2398 
2399 #if defined(_WIN32_WCE)
2400   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
2401    */
2402   home_dir = strdup("/");
2403 #else
2404 
2405 #if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
2406   if (!home_dir) {
2407     home_dir = getenv("USERPROFILE");
2408   }
2409 #endif
2410 
2411   if (!home_dir) {
2412     home_dir = getenv("HOME");
2413   }
2414 
2415 #if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
2416   if (!home_dir) {
2417     char *zDrive, *zPath;
2418     int n;
2419     zDrive = getenv("HOMEDRIVE");
2420     zPath = getenv("HOMEPATH");
2421     if( zDrive && zPath ){
2422       n = strlen30(zDrive) + strlen30(zPath) + 1;
2423       home_dir = malloc( n );
2424       if( home_dir==0 ) return 0;
2425       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
2426       return home_dir;
2427     }
2428     home_dir = "c:\\";
2429   }
2430 #endif
2431 
2432 #endif /* !_WIN32_WCE */
2433 
2434   if( home_dir ){
2435     int n = strlen30(home_dir) + 1;
2436     char *z = malloc( n );
2437     if( z ) memcpy(z, home_dir, n);
2438     home_dir = z;
2439   }
2440 
2441   return home_dir;
2442 }
2443 
2444 /*
2445 ** Read input from the file given by sqliterc_override.  Or if that
2446 ** parameter is NULL, take input from ~/.sqliterc
2447 **
2448 ** Returns the number of errors.
2449 */
process_sqliterc(struct callback_data * p,const char * sqliterc_override)2450 static int process_sqliterc(
2451   struct callback_data *p,        /* Configuration data */
2452   const char *sqliterc_override   /* Name of config file. NULL to use default */
2453 ){
2454   char *home_dir = NULL;
2455   const char *sqliterc = sqliterc_override;
2456   char *zBuf = 0;
2457   FILE *in = NULL;
2458   int nBuf;
2459   int rc = 0;
2460 
2461   if (sqliterc == NULL) {
2462     home_dir = find_home_dir();
2463     if( home_dir==0 ){
2464 #if !defined(__RTP__) && !defined(_WRS_KERNEL)
2465       fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0);
2466 #endif
2467       return 1;
2468     }
2469     nBuf = strlen30(home_dir) + 16;
2470     zBuf = malloc( nBuf );
2471     if( zBuf==0 ){
2472       fprintf(stderr,"%s: Error: out of memory\n",Argv0);
2473       return 1;
2474     }
2475     sqlite3_snprintf(nBuf, zBuf,"%s/.sqliterc",home_dir);
2476     free(home_dir);
2477     sqliterc = (const char*)zBuf;
2478   }
2479   in = fopen(sqliterc,"rb");
2480   if( in ){
2481     if( stdin_is_interactive ){
2482       fprintf(stderr,"-- Loading resources from %s\n",sqliterc);
2483     }
2484     rc = process_input(p,in);
2485     fclose(in);
2486   }
2487   free(zBuf);
2488   return rc;
2489 }
2490 
2491 /*
2492 ** Show available command line options
2493 */
2494 static const char zOptions[] =
2495   "   -help                show this message\n"
2496   "   -init filename       read/process named file\n"
2497   "   -echo                print commands before execution\n"
2498   "   -[no]header          turn headers on or off\n"
2499   "   -bail                stop after hitting an error\n"
2500   "   -interactive         force interactive I/O\n"
2501   "   -batch               force batch I/O\n"
2502   "   -column              set output mode to 'column'\n"
2503   "   -csv                 set output mode to 'csv'\n"
2504   "   -html                set output mode to HTML\n"
2505   "   -line                set output mode to 'line'\n"
2506   "   -list                set output mode to 'list'\n"
2507   "   -separator 'x'       set output field separator (|)\n"
2508   "   -stats               print memory stats before each finalize\n"
2509   "   -nullvalue 'text'    set text string for NULL values\n"
2510   "   -version             show SQLite version\n"
2511 ;
usage(int showDetail)2512 static void usage(int showDetail){
2513   fprintf(stderr,
2514       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
2515       "FILENAME is the name of an SQLite database. A new database is created\n"
2516       "if the file does not previously exist.\n", Argv0);
2517   if( showDetail ){
2518     fprintf(stderr, "OPTIONS include:\n%s", zOptions);
2519   }else{
2520     fprintf(stderr, "Use the -help option for additional information\n");
2521   }
2522   exit(1);
2523 }
2524 
2525 /*
2526 ** Initialize the state information in data
2527 */
main_init(struct callback_data * data)2528 static void main_init(struct callback_data *data) {
2529   memset(data, 0, sizeof(*data));
2530   data->mode = MODE_List;
2531   memcpy(data->separator,"|", 2);
2532   data->showHeader = 0;
2533   sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
2534   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
2535   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
2536   sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
2537 }
2538 
main(int argc,char ** argv)2539 int main(int argc, char **argv){
2540   char *zErrMsg = 0;
2541   struct callback_data data;
2542   const char *zInitFile = 0;
2543   char *zFirstCmd = 0;
2544   int i;
2545   int rc = 0;
2546 
2547   Argv0 = argv[0];
2548   main_init(&data);
2549   stdin_is_interactive = isatty(0);
2550 
2551   /* Make sure we have a valid signal handler early, before anything
2552   ** else is done.
2553   */
2554 #ifdef SIGINT
2555   signal(SIGINT, interrupt_handler);
2556 #endif
2557 
2558   /* Do an initial pass through the command-line argument to locate
2559   ** the name of the database file, the name of the initialization file,
2560   ** and the first command to execute.
2561   */
2562   for(i=1; i<argc-1; i++){
2563     char *z;
2564     if( argv[i][0]!='-' ) break;
2565     z = argv[i];
2566     if( z[0]=='-' && z[1]=='-' ) z++;
2567     if( strcmp(argv[i],"-separator")==0 || strcmp(argv[i],"-nullvalue")==0 ){
2568       i++;
2569     }else if( strcmp(argv[i],"-init")==0 ){
2570       i++;
2571       zInitFile = argv[i];
2572     /* Need to check for batch mode here to so we can avoid printing
2573     ** informational messages (like from process_sqliterc) before
2574     ** we do the actual processing of arguments later in a second pass.
2575     */
2576     }else if( strcmp(argv[i],"-batch")==0 ){
2577       stdin_is_interactive = 0;
2578     }
2579   }
2580   if( i<argc ){
2581 #if defined(SQLITE_OS_OS2) && SQLITE_OS_OS2
2582     data.zDbFilename = (const char *)convertCpPathToUtf8( argv[i++] );
2583 #else
2584     data.zDbFilename = argv[i++];
2585 #endif
2586   }else{
2587 #ifndef SQLITE_OMIT_MEMORYDB
2588     data.zDbFilename = ":memory:";
2589 #else
2590     data.zDbFilename = 0;
2591 #endif
2592   }
2593   if( i<argc ){
2594     zFirstCmd = argv[i++];
2595   }
2596   if( i<argc ){
2597     fprintf(stderr,"%s: Error: too many options: \"%s\"\n", Argv0, argv[i]);
2598     fprintf(stderr,"Use -help for a list of options.\n");
2599     return 1;
2600   }
2601   data.out = stdout;
2602 
2603 #ifdef SQLITE_OMIT_MEMORYDB
2604   if( data.zDbFilename==0 ){
2605     fprintf(stderr,"%s: Error: no database filename specified\n", Argv0);
2606     return 1;
2607   }
2608 #endif
2609 
2610   /* Go ahead and open the database file if it already exists.  If the
2611   ** file does not exist, delay opening it.  This prevents empty database
2612   ** files from being created if a user mistypes the database name argument
2613   ** to the sqlite command-line tool.
2614   */
2615   if( access(data.zDbFilename, 0)==0 ){
2616     open_db(&data);
2617   }
2618 
2619   /* Process the initialization file if there is one.  If no -init option
2620   ** is given on the command line, look for a file named ~/.sqliterc and
2621   ** try to process it.
2622   */
2623   rc = process_sqliterc(&data,zInitFile);
2624   if( rc>0 ){
2625     return rc;
2626   }
2627 
2628   /* Make a second pass through the command-line argument and set
2629   ** options.  This second pass is delayed until after the initialization
2630   ** file is processed so that the command-line arguments will override
2631   ** settings in the initialization file.
2632   */
2633   for(i=1; i<argc && argv[i][0]=='-'; i++){
2634     char *z = argv[i];
2635     if( z[1]=='-' ){ z++; }
2636     if( strcmp(z,"-init")==0 ){
2637       i++;
2638     }else if( strcmp(z,"-html")==0 ){
2639       data.mode = MODE_Html;
2640     }else if( strcmp(z,"-list")==0 ){
2641       data.mode = MODE_List;
2642     }else if( strcmp(z,"-line")==0 ){
2643       data.mode = MODE_Line;
2644     }else if( strcmp(z,"-column")==0 ){
2645       data.mode = MODE_Column;
2646     }else if( strcmp(z,"-csv")==0 ){
2647       data.mode = MODE_Csv;
2648       memcpy(data.separator,",",2);
2649     }else if( strcmp(z,"-separator")==0 ){
2650       i++;
2651       if(i>=argc){
2652         fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z);
2653         fprintf(stderr,"Use -help for a list of options.\n");
2654         return 1;
2655       }
2656       sqlite3_snprintf(sizeof(data.separator), data.separator,
2657                        "%.*s",(int)sizeof(data.separator)-1,argv[i]);
2658     }else if( strcmp(z,"-nullvalue")==0 ){
2659       i++;
2660       if(i>=argc){
2661         fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z);
2662         fprintf(stderr,"Use -help for a list of options.\n");
2663         return 1;
2664       }
2665       sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
2666                        "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
2667     }else if( strcmp(z,"-header")==0 ){
2668       data.showHeader = 1;
2669     }else if( strcmp(z,"-noheader")==0 ){
2670       data.showHeader = 0;
2671     }else if( strcmp(z,"-echo")==0 ){
2672       data.echoOn = 1;
2673     }else if( strcmp(z,"-stats")==0 ){
2674       data.statsOn = 1;
2675     }else if( strcmp(z,"-bail")==0 ){
2676       bail_on_error = 1;
2677     }else if( strcmp(z,"-version")==0 ){
2678       printf("%s\n", sqlite3_libversion());
2679       return 0;
2680     }else if( strcmp(z,"-interactive")==0 ){
2681       stdin_is_interactive = 1;
2682     }else if( strcmp(z,"-batch")==0 ){
2683       stdin_is_interactive = 0;
2684     }else if( strcmp(z,"-help")==0 || strcmp(z, "--help")==0 ){
2685       usage(1);
2686     }else{
2687       fprintf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
2688       fprintf(stderr,"Use -help for a list of options.\n");
2689       return 1;
2690     }
2691   }
2692 
2693   if( zFirstCmd ){
2694     /* Run just the command that follows the database name
2695     */
2696     if( zFirstCmd[0]=='.' ){
2697       rc = do_meta_command(zFirstCmd, &data);
2698     }else{
2699       open_db(&data);
2700       rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg);
2701       if( zErrMsg!=0 ){
2702         fprintf(stderr,"Error: %s\n", zErrMsg);
2703         return rc!=0 ? rc : 1;
2704       }else if( rc!=0 ){
2705         fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd);
2706         return rc;
2707       }
2708     }
2709   }else{
2710     /* Run commands received from standard input
2711     */
2712     if( stdin_is_interactive ){
2713       char *zHome;
2714       char *zHistory = 0;
2715       int nHistory;
2716       printf(
2717         "SQLite version %s\n"
2718         "Enter \".help\" for instructions\n"
2719         "Enter SQL statements terminated with a \";\"\n",
2720         sqlite3_libversion()
2721       );
2722       zHome = find_home_dir();
2723       if( zHome ){
2724         nHistory = strlen30(zHome) + 20;
2725         if( (zHistory = malloc(nHistory))!=0 ){
2726           sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
2727         }
2728       }
2729 #if defined(HAVE_READLINE) && HAVE_READLINE==1
2730       if( zHistory ) read_history(zHistory);
2731 #endif
2732       rc = process_input(&data, 0);
2733       if( zHistory ){
2734         stifle_history(100);
2735         write_history(zHistory);
2736         free(zHistory);
2737       }
2738       free(zHome);
2739     }else{
2740       rc = process_input(&data, stdin);
2741     }
2742   }
2743   set_table_name(&data, 0);
2744   if( data.db ){
2745     if( sqlite3_close(data.db)!=SQLITE_OK ){
2746       fprintf(stderr,"Error: cannot close database \"%s\"\n",
2747               sqlite3_errmsg(db));
2748       rc++;
2749     }
2750   }
2751   return rc;
2752 }
2753