• 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 ** $Id: shell.c,v 1.178 2008/05/05 16:27:24 drh Exp $
16 */
17 
18 #ifndef NO_ANDROID_FUNCS
19 #include <sqlite3_android.h>
20 #endif
21 
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <assert.h>
26 #include "sqlite3.h"
27 #include <ctype.h>
28 #include <stdarg.h>
29 
30 #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__)
31 # include <signal.h>
32 # include <pwd.h>
33 # include <unistd.h>
34 # include <sys/types.h>
35 #endif
36 
37 #ifdef __OS2__
38 # include <unistd.h>
39 #endif
40 
41 #if defined(HAVE_READLINE) && HAVE_READLINE==1
42 # include <readline/readline.h>
43 # include <readline/history.h>
44 #else
45 # define readline(p) local_getline(p,stdin)
46 # define add_history(X)
47 # define read_history(X)
48 # define write_history(X)
49 # define stifle_history(X)
50 #endif
51 
52 #if defined(_WIN32) || defined(WIN32)
53 # include <io.h>
54 #else
55 /* Make sure isatty() has a prototype.
56 */
57 extern int isatty();
58 #endif
59 
60 #if defined(_WIN32_WCE)
61 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
62  * thus we always assume that we have a console. That can be
63  * overridden with the -batch command line option.
64  */
65 #define isatty(x) 1
66 #endif
67 
68 #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__)
69 #include <sys/time.h>
70 #include <sys/resource.h>
71 
72 /* Saved resource information for the beginning of an operation */
73 static struct rusage sBegin;
74 
75 /* True if the timer is enabled */
76 static int enableTimer = 0;
77 
78 /*
79 ** Begin timing an operation
80 */
beginTimer(void)81 static void beginTimer(void){
82   if( enableTimer ){
83     getrusage(RUSAGE_SELF, &sBegin);
84   }
85 }
86 
87 /* Return the difference of two time_structs in microseconds */
timeDiff(struct timeval * pStart,struct timeval * pEnd)88 static int timeDiff(struct timeval *pStart, struct timeval *pEnd){
89   return (pEnd->tv_usec - pStart->tv_usec) +
90          1000000*(pEnd->tv_sec - pStart->tv_sec);
91 }
92 
93 /*
94 ** Print the timing results.
95 */
endTimer(void)96 static void endTimer(void){
97   if( enableTimer ){
98     struct rusage sEnd;
99     getrusage(RUSAGE_SELF, &sEnd);
100     printf("CPU Time: user %f sys %f\n",
101        0.000001*timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
102        0.000001*timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
103   }
104 }
105 #define BEGIN_TIMER beginTimer()
106 #define END_TIMER endTimer()
107 #define HAS_TIMER 1
108 #else
109 #define BEGIN_TIMER
110 #define END_TIMER
111 #define HAS_TIMER 0
112 #endif
113 
114 
115 /*
116 ** If the following flag is set, then command execution stops
117 ** at an error if we are not interactive.
118 */
119 static int bail_on_error = 0;
120 
121 /*
122 ** Threat stdin as an interactive input if the following variable
123 ** is true.  Otherwise, assume stdin is connected to a file or pipe.
124 */
125 static int stdin_is_interactive = 1;
126 
127 /*
128 ** The following is the open SQLite database.  We make a pointer
129 ** to this database a static variable so that it can be accessed
130 ** by the SIGINT handler to interrupt database processing.
131 */
132 static sqlite3 *db = 0;
133 
134 /*
135 ** True if an interrupt (Control-C) has been received.
136 */
137 static volatile int seenInterrupt = 0;
138 
139 /*
140 ** This is the name of our program. It is set in main(), used
141 ** in a number of other places, mostly for error messages.
142 */
143 static char *Argv0;
144 
145 /*
146 ** Prompt strings. Initialized in main. Settable with
147 **   .prompt main continue
148 */
149 static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
150 static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
151 
152 /*
153 ** Write I/O traces to the following stream.
154 */
155 #ifdef SQLITE_ENABLE_IOTRACE
156 static FILE *iotrace = 0;
157 #endif
158 
159 /*
160 ** This routine works like printf in that its first argument is a
161 ** format string and subsequent arguments are values to be substituted
162 ** in place of % fields.  The result of formatting this string
163 ** is written to iotrace.
164 */
165 #ifdef SQLITE_ENABLE_IOTRACE
iotracePrintf(const char * zFormat,...)166 static void iotracePrintf(const char *zFormat, ...){
167   va_list ap;
168   char *z;
169   if( iotrace==0 ) return;
170   va_start(ap, zFormat);
171   z = sqlite3_vmprintf(zFormat, ap);
172   va_end(ap);
173   fprintf(iotrace, "%s", z);
174   sqlite3_free(z);
175 }
176 #endif
177 
178 
179 /*
180 ** Determines if a string is a number of not.
181 */
isNumber(const char * z,int * realnum)182 static int isNumber(const char *z, int *realnum){
183   if( *z=='-' || *z=='+' ) z++;
184   if( !isdigit(*z) ){
185     return 0;
186   }
187   z++;
188   if( realnum ) *realnum = 0;
189   while( isdigit(*z) ){ z++; }
190   if( *z=='.' ){
191     z++;
192     if( !isdigit(*z) ) return 0;
193     while( isdigit(*z) ){ z++; }
194     if( realnum ) *realnum = 1;
195   }
196   if( *z=='e' || *z=='E' ){
197     z++;
198     if( *z=='+' || *z=='-' ) z++;
199     if( !isdigit(*z) ) return 0;
200     while( isdigit(*z) ){ z++; }
201     if( realnum ) *realnum = 1;
202   }
203   return *z==0;
204 }
205 
206 /*
207 ** A global char* and an SQL function to access its current value
208 ** from within an SQL statement. This program used to use the
209 ** sqlite_exec_printf() API to substitue a string into an SQL statement.
210 ** The correct way to do this with sqlite3 is to use the bind API, but
211 ** since the shell is built around the callback paradigm it would be a lot
212 ** of work. Instead just use this hack, which is quite harmless.
213 */
214 static const char *zShellStatic = 0;
shellstaticFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)215 static void shellstaticFunc(
216   sqlite3_context *context,
217   int argc,
218   sqlite3_value **argv
219 ){
220   assert( 0==argc );
221   assert( zShellStatic );
222   sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
223 }
224 
225 
226 /*
227 ** This routine reads a line of text from FILE in, stores
228 ** the text in memory obtained from malloc() and returns a pointer
229 ** to the text.  NULL is returned at end of file, or if malloc()
230 ** fails.
231 **
232 ** The interface is like "readline" but no command-line editing
233 ** is done.
234 */
local_getline(char * zPrompt,FILE * in)235 static char *local_getline(char *zPrompt, FILE *in){
236   char *zLine;
237   int nLine;
238   int n;
239   int eol;
240 
241   if( zPrompt && *zPrompt ){
242     printf("%s",zPrompt);
243     fflush(stdout);
244   }
245   nLine = 100;
246   zLine = malloc( nLine );
247   if( zLine==0 ) return 0;
248   n = 0;
249   eol = 0;
250   while( !eol ){
251     if( n+100>nLine ){
252       nLine = nLine*2 + 100;
253       zLine = realloc(zLine, nLine);
254       if( zLine==0 ) return 0;
255     }
256     if( fgets(&zLine[n], nLine - n, in)==0 ){
257       if( n==0 ){
258         free(zLine);
259         return 0;
260       }
261       zLine[n] = 0;
262       eol = 1;
263       break;
264     }
265     while( zLine[n] ){ n++; }
266     if( n>0 && zLine[n-1]=='\n' ){
267       n--;
268       zLine[n] = 0;
269       eol = 1;
270     }
271   }
272   zLine = realloc( zLine, n+1 );
273   return zLine;
274 }
275 
276 /*
277 ** Retrieve a single line of input text.
278 **
279 ** zPrior is a string of prior text retrieved.  If not the empty
280 ** string, then issue a continuation prompt.
281 */
one_input_line(const char * zPrior,FILE * in)282 static char *one_input_line(const char *zPrior, FILE *in){
283   char *zPrompt;
284   char *zResult;
285   if( in!=0 ){
286     return local_getline(0, in);
287   }
288   if( zPrior && zPrior[0] ){
289     zPrompt = continuePrompt;
290   }else{
291     zPrompt = mainPrompt;
292   }
293   zResult = readline(zPrompt);
294 #if defined(HAVE_READLINE) && HAVE_READLINE==1
295   if( zResult && *zResult ) add_history(zResult);
296 #endif
297   return zResult;
298 }
299 
300 struct previous_mode_data {
301   int valid;        /* Is there legit data in here? */
302   int mode;
303   int showHeader;
304   int colWidth[100];
305 };
306 
307 /*
308 ** An pointer to an instance of this structure is passed from
309 ** the main program to the callback.  This is used to communicate
310 ** state and mode information.
311 */
312 struct callback_data {
313   sqlite3 *db;            /* The database */
314   int echoOn;            /* True to echo input commands */
315   int cnt;               /* Number of records displayed so far */
316   FILE *out;             /* Write results here */
317   int mode;              /* An output mode setting */
318   int writableSchema;    /* True if PRAGMA writable_schema=ON */
319   int showHeader;        /* True to show column names in List or Column mode */
320   char *zDestTable;      /* Name of destination table when MODE_Insert */
321   char separator[20];    /* Separator character for MODE_List */
322   int colWidth[100];     /* Requested width of each column when in column mode*/
323   int actualWidth[100];  /* Actual width of each column */
324   char nullvalue[20];    /* The text to print when a NULL comes back from
325                          ** the database */
326   struct previous_mode_data explainPrev;
327                          /* Holds the mode information just before
328                          ** .explain ON */
329   char outfile[FILENAME_MAX]; /* Filename for *out */
330   const char *zDbFilename;    /* name of the database file */
331 };
332 
333 /*
334 ** These are the allowed modes.
335 */
336 #define MODE_Line     0  /* One column per line.  Blank line between records */
337 #define MODE_Column   1  /* One record per line in neat columns */
338 #define MODE_List     2  /* One record per line with a separator */
339 #define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
340 #define MODE_Html     4  /* Generate an XHTML table */
341 #define MODE_Insert   5  /* Generate SQL "insert" statements */
342 #define MODE_Tcl      6  /* Generate ANSI-C or TCL quoted elements */
343 #define MODE_Csv      7  /* Quote strings, numbers are plain */
344 #define MODE_Explain  8  /* Like MODE_Column, but do not truncate data */
345 
346 static const char *modeDescr[] = {
347   "line",
348   "column",
349   "list",
350   "semi",
351   "html",
352   "insert",
353   "tcl",
354   "csv",
355   "explain",
356 };
357 
358 /*
359 ** Number of elements in an array
360 */
361 #define ArraySize(X)  (sizeof(X)/sizeof(X[0]))
362 
363 /*
364 ** Output the given string as a quoted string using SQL quoting conventions.
365 */
output_quoted_string(FILE * out,const char * z)366 static void output_quoted_string(FILE *out, const char *z){
367   int i;
368   int nSingle = 0;
369   for(i=0; z[i]; i++){
370     if( z[i]=='\'' ) nSingle++;
371   }
372   if( nSingle==0 ){
373     fprintf(out,"'%s'",z);
374   }else{
375     fprintf(out,"'");
376     while( *z ){
377       for(i=0; z[i] && z[i]!='\''; i++){}
378       if( i==0 ){
379         fprintf(out,"''");
380         z++;
381       }else if( z[i]=='\'' ){
382         fprintf(out,"%.*s''",i,z);
383         z += i+1;
384       }else{
385         fprintf(out,"%s",z);
386         break;
387       }
388     }
389     fprintf(out,"'");
390   }
391 }
392 
393 /*
394 ** Output the given string as a quoted according to C or TCL quoting rules.
395 */
output_c_string(FILE * out,const char * z)396 static void output_c_string(FILE *out, const char *z){
397   unsigned int c;
398   fputc('"', out);
399   while( (c = *(z++))!=0 ){
400     if( c=='\\' ){
401       fputc(c, out);
402       fputc(c, out);
403     }else if( c=='\t' ){
404       fputc('\\', out);
405       fputc('t', out);
406     }else if( c=='\n' ){
407       fputc('\\', out);
408       fputc('n', out);
409     }else if( c=='\r' ){
410       fputc('\\', out);
411       fputc('r', out);
412     }else if( !isprint(c) ){
413       fprintf(out, "\\%03o", c&0xff);
414     }else{
415       fputc(c, out);
416     }
417   }
418   fputc('"', out);
419 }
420 
421 /*
422 ** Output the given string with characters that are special to
423 ** HTML escaped.
424 */
output_html_string(FILE * out,const char * z)425 static void output_html_string(FILE *out, const char *z){
426   int i;
427   while( *z ){
428     for(i=0; z[i] && z[i]!='<' && z[i]!='&'; i++){}
429     if( i>0 ){
430       fprintf(out,"%.*s",i,z);
431     }
432     if( z[i]=='<' ){
433       fprintf(out,"&lt;");
434     }else if( z[i]=='&' ){
435       fprintf(out,"&amp;");
436     }else{
437       break;
438     }
439     z += i + 1;
440   }
441 }
442 
443 /*
444 ** If a field contains any character identified by a 1 in the following
445 ** array, then the string must be quoted for CSV.
446 */
447 static const char needCsvQuote[] = {
448   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
449   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
450   1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
451   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
452   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
453   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
454   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
455   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
456   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
457   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
458   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
459   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
460   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
461   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
462   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
463   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
464 };
465 
466 /*
467 ** Output a single term of CSV.  Actually, p->separator is used for
468 ** the separator, which may or may not be a comma.  p->nullvalue is
469 ** the null value.  Strings are quoted using ANSI-C rules.  Numbers
470 ** appear outside of quotes.
471 */
output_csv(struct callback_data * p,const char * z,int bSep)472 static void output_csv(struct callback_data *p, const char *z, int bSep){
473   FILE *out = p->out;
474   if( z==0 ){
475     fprintf(out,"%s",p->nullvalue);
476   }else{
477     int i;
478     int nSep = strlen(p->separator);
479     for(i=0; z[i]; i++){
480       if( needCsvQuote[((unsigned char*)z)[i]]
481          || (z[i]==p->separator[0] &&
482              (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
483         i = 0;
484         break;
485       }
486     }
487     if( i==0 ){
488       putc('"', out);
489       for(i=0; z[i]; i++){
490         if( z[i]=='"' ) putc('"', out);
491         putc(z[i], out);
492       }
493       putc('"', out);
494     }else{
495       fprintf(out, "%s", z);
496     }
497   }
498   if( bSep ){
499     fprintf(p->out, "%s", p->separator);
500   }
501 }
502 
503 #ifdef SIGINT
504 /*
505 ** This routine runs when the user presses Ctrl-C
506 */
interrupt_handler(int NotUsed)507 static void interrupt_handler(int NotUsed){
508   seenInterrupt = 1;
509   if( db ) sqlite3_interrupt(db);
510 }
511 #endif
512 
513 /*
514 ** This is the callback routine that the SQLite library
515 ** invokes for each row of a query result.
516 */
callback(void * pArg,int nArg,char ** azArg,char ** azCol)517 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
518   int i;
519   struct callback_data *p = (struct callback_data*)pArg;
520   switch( p->mode ){
521     case MODE_Line: {
522       int w = 5;
523       if( azArg==0 ) break;
524       for(i=0; i<nArg; i++){
525         int len = strlen(azCol[i] ? azCol[i] : "");
526         if( len>w ) w = len;
527       }
528       if( p->cnt++>0 ) fprintf(p->out,"\n");
529       for(i=0; i<nArg; i++){
530         fprintf(p->out,"%*s = %s\n", w, azCol[i],
531                 azArg[i] ? azArg[i] : p->nullvalue);
532       }
533       break;
534     }
535     case MODE_Explain:
536     case MODE_Column: {
537       if( p->cnt++==0 ){
538         for(i=0; i<nArg; i++){
539           int w, n;
540           if( i<ArraySize(p->colWidth) ){
541             w = p->colWidth[i];
542           }else{
543             w = 0;
544           }
545           if( w<=0 ){
546             w = strlen(azCol[i] ? azCol[i] : "");
547             if( w<10 ) w = 10;
548             n = strlen(azArg && azArg[i] ? azArg[i] : p->nullvalue);
549             if( w<n ) w = n;
550           }
551           if( i<ArraySize(p->actualWidth) ){
552             p->actualWidth[i] = w;
553           }
554           if( p->showHeader ){
555             fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": "  ");
556           }
557         }
558         if( p->showHeader ){
559           for(i=0; i<nArg; i++){
560             int w;
561             if( i<ArraySize(p->actualWidth) ){
562                w = p->actualWidth[i];
563             }else{
564                w = 10;
565             }
566             fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
567                    "----------------------------------------------------------",
568                     i==nArg-1 ? "\n": "  ");
569           }
570         }
571       }
572       if( azArg==0 ) break;
573       for(i=0; i<nArg; i++){
574         int w;
575         if( i<ArraySize(p->actualWidth) ){
576            w = p->actualWidth[i];
577         }else{
578            w = 10;
579         }
580         if( p->mode==MODE_Explain && azArg[i] && strlen(azArg[i])>w ){
581           w = strlen(azArg[i]);
582         }
583         fprintf(p->out,"%-*.*s%s",w,w,
584             azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": "  ");
585       }
586       break;
587     }
588     case MODE_Semi:
589     case MODE_List: {
590       if( p->cnt++==0 && p->showHeader ){
591         for(i=0; i<nArg; i++){
592           fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
593         }
594       }
595       if( azArg==0 ) break;
596       for(i=0; i<nArg; i++){
597         char *z = azArg[i];
598         if( z==0 ) z = p->nullvalue;
599         fprintf(p->out, "%s", z);
600         if( i<nArg-1 ){
601           fprintf(p->out, "%s", p->separator);
602         }else if( p->mode==MODE_Semi ){
603           fprintf(p->out, ";\n");
604         }else{
605           fprintf(p->out, "\n");
606         }
607       }
608       break;
609     }
610     case MODE_Html: {
611       if( p->cnt++==0 && p->showHeader ){
612         fprintf(p->out,"<TR>");
613         for(i=0; i<nArg; i++){
614           fprintf(p->out,"<TH>%s</TH>",azCol[i]);
615         }
616         fprintf(p->out,"</TR>\n");
617       }
618       if( azArg==0 ) break;
619       fprintf(p->out,"<TR>");
620       for(i=0; i<nArg; i++){
621         fprintf(p->out,"<TD>");
622         output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
623         fprintf(p->out,"</TD>\n");
624       }
625       fprintf(p->out,"</TR>\n");
626       break;
627     }
628     case MODE_Tcl: {
629       if( p->cnt++==0 && p->showHeader ){
630         for(i=0; i<nArg; i++){
631           output_c_string(p->out,azCol[i] ? azCol[i] : "");
632           fprintf(p->out, "%s", p->separator);
633         }
634         fprintf(p->out,"\n");
635       }
636       if( azArg==0 ) break;
637       for(i=0; i<nArg; i++){
638         output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
639         fprintf(p->out, "%s", p->separator);
640       }
641       fprintf(p->out,"\n");
642       break;
643     }
644     case MODE_Csv: {
645       if( p->cnt++==0 && p->showHeader ){
646         for(i=0; i<nArg; i++){
647           output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
648         }
649         fprintf(p->out,"\n");
650       }
651       if( azArg==0 ) break;
652       for(i=0; i<nArg; i++){
653         output_csv(p, azArg[i], i<nArg-1);
654       }
655       fprintf(p->out,"\n");
656       break;
657     }
658     case MODE_Insert: {
659       if( azArg==0 ) break;
660       fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
661       for(i=0; i<nArg; i++){
662         char *zSep = i>0 ? ",": "";
663         if( azArg[i]==0 ){
664           fprintf(p->out,"%sNULL",zSep);
665         }else if( isNumber(azArg[i], 0) ){
666           fprintf(p->out,"%s%s",zSep, azArg[i]);
667         }else{
668           if( zSep[0] ) fprintf(p->out,"%s",zSep);
669           output_quoted_string(p->out, azArg[i]);
670         }
671       }
672       fprintf(p->out,");\n");
673       break;
674     }
675   }
676   return 0;
677 }
678 
679 /*
680 ** Set the destination table field of the callback_data structure to
681 ** the name of the table given.  Escape any quote characters in the
682 ** table name.
683 */
set_table_name(struct callback_data * p,const char * zName)684 static void set_table_name(struct callback_data *p, const char *zName){
685   int i, n;
686   int needQuote;
687   char *z;
688 
689   if( p->zDestTable ){
690     free(p->zDestTable);
691     p->zDestTable = 0;
692   }
693   if( zName==0 ) return;
694   needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
695   for(i=n=0; zName[i]; i++, n++){
696     if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
697       needQuote = 1;
698       if( zName[i]=='\'' ) n++;
699     }
700   }
701   if( needQuote ) n += 2;
702   z = p->zDestTable = malloc( n+1 );
703   if( z==0 ){
704     fprintf(stderr,"Out of memory!\n");
705     exit(1);
706   }
707   n = 0;
708   if( needQuote ) z[n++] = '\'';
709   for(i=0; zName[i]; i++){
710     z[n++] = zName[i];
711     if( zName[i]=='\'' ) z[n++] = '\'';
712   }
713   if( needQuote ) z[n++] = '\'';
714   z[n] = 0;
715 }
716 
717 /* zIn is either a pointer to a NULL-terminated string in memory obtained
718 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
719 ** added to zIn, and the result returned in memory obtained from malloc().
720 ** zIn, if it was not NULL, is freed.
721 **
722 ** If the third argument, quote, is not '\0', then it is used as a
723 ** quote character for zAppend.
724 */
appendText(char * zIn,char const * zAppend,char quote)725 static char *appendText(char *zIn, char const *zAppend, char quote){
726   int len;
727   int i;
728   int nAppend = strlen(zAppend);
729   int nIn = (zIn?strlen(zIn):0);
730 
731   len = nAppend+nIn+1;
732   if( quote ){
733     len += 2;
734     for(i=0; i<nAppend; i++){
735       if( zAppend[i]==quote ) len++;
736     }
737   }
738 
739   zIn = (char *)realloc(zIn, len);
740   if( !zIn ){
741     return 0;
742   }
743 
744   if( quote ){
745     char *zCsr = &zIn[nIn];
746     *zCsr++ = quote;
747     for(i=0; i<nAppend; i++){
748       *zCsr++ = zAppend[i];
749       if( zAppend[i]==quote ) *zCsr++ = quote;
750     }
751     *zCsr++ = quote;
752     *zCsr++ = '\0';
753     assert( (zCsr-zIn)==len );
754   }else{
755     memcpy(&zIn[nIn], zAppend, nAppend);
756     zIn[len-1] = '\0';
757   }
758 
759   return zIn;
760 }
761 
762 
763 /*
764 ** Execute a query statement that has a single result column.  Print
765 ** that result column on a line by itself with a semicolon terminator.
766 **
767 ** This is used, for example, to show the schema of the database by
768 ** querying the SQLITE_MASTER table.
769 */
run_table_dump_query(FILE * out,sqlite3 * db,const char * zSelect)770 static int run_table_dump_query(FILE *out, sqlite3 *db, const char *zSelect){
771   sqlite3_stmt *pSelect;
772   int rc;
773   rc = sqlite3_prepare(db, zSelect, -1, &pSelect, 0);
774   if( rc!=SQLITE_OK || !pSelect ){
775     return rc;
776   }
777   rc = sqlite3_step(pSelect);
778   while( rc==SQLITE_ROW ){
779     fprintf(out, "%s;\n", sqlite3_column_text(pSelect, 0));
780     rc = sqlite3_step(pSelect);
781   }
782   return sqlite3_finalize(pSelect);
783 }
784 
785 
786 /*
787 ** This is a different callback routine used for dumping the database.
788 ** Each row received by this callback consists of a table name,
789 ** the table type ("index" or "table") and SQL to create the table.
790 ** This routine should print text sufficient to recreate the table.
791 */
dump_callback(void * pArg,int nArg,char ** azArg,char ** azCol)792 static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
793   int rc;
794   const char *zTable;
795   const char *zType;
796   const char *zSql;
797   struct callback_data *p = (struct callback_data *)pArg;
798 
799   if( nArg!=3 ) return 1;
800   zTable = azArg[0];
801   zType = azArg[1];
802   zSql = azArg[2];
803 
804   if( strcmp(zTable, "sqlite_sequence")==0 ){
805     fprintf(p->out, "DELETE FROM sqlite_sequence;\n");
806   }else if( strcmp(zTable, "sqlite_stat1")==0 ){
807     fprintf(p->out, "ANALYZE sqlite_master;\n");
808   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
809     return 0;
810   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
811     char *zIns;
812     if( !p->writableSchema ){
813       fprintf(p->out, "PRAGMA writable_schema=ON;\n");
814       p->writableSchema = 1;
815     }
816     zIns = sqlite3_mprintf(
817        "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
818        "VALUES('table','%q','%q',0,'%q');",
819        zTable, zTable, zSql);
820     fprintf(p->out, "%s\n", zIns);
821     sqlite3_free(zIns);
822     return 0;
823   }else{
824     fprintf(p->out, "%s;\n", zSql);
825   }
826 
827   if( strcmp(zType, "table")==0 ){
828     sqlite3_stmt *pTableInfo = 0;
829     char *zSelect = 0;
830     char *zTableInfo = 0;
831     char *zTmp = 0;
832 
833     zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
834     zTableInfo = appendText(zTableInfo, zTable, '"');
835     zTableInfo = appendText(zTableInfo, ");", 0);
836 
837     rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
838     if( zTableInfo ) free(zTableInfo);
839     if( rc!=SQLITE_OK || !pTableInfo ){
840       return 1;
841     }
842 
843     zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
844     zTmp = appendText(zTmp, zTable, '"');
845     if( zTmp ){
846       zSelect = appendText(zSelect, zTmp, '\'');
847     }
848     zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
849     rc = sqlite3_step(pTableInfo);
850     while( rc==SQLITE_ROW ){
851       const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
852       zSelect = appendText(zSelect, "quote(", 0);
853       zSelect = appendText(zSelect, zText, '"');
854       rc = sqlite3_step(pTableInfo);
855       if( rc==SQLITE_ROW ){
856         zSelect = appendText(zSelect, ") || ',' || ", 0);
857       }else{
858         zSelect = appendText(zSelect, ") ", 0);
859       }
860     }
861     rc = sqlite3_finalize(pTableInfo);
862     if( rc!=SQLITE_OK ){
863       if( zSelect ) free(zSelect);
864       return 1;
865     }
866     zSelect = appendText(zSelect, "|| ')' FROM  ", 0);
867     zSelect = appendText(zSelect, zTable, '"');
868 
869     rc = run_table_dump_query(p->out, p->db, zSelect);
870     if( rc==SQLITE_CORRUPT ){
871       zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
872       rc = run_table_dump_query(p->out, p->db, zSelect);
873     }
874     if( zSelect ) free(zSelect);
875   }
876   return 0;
877 }
878 
879 /*
880 ** Run zQuery.  Use dump_callback() as the callback routine so that
881 ** the contents of the query are output as SQL statements.
882 **
883 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
884 ** "ORDER BY rowid DESC" to the end.
885 */
run_schema_dump_query(struct callback_data * p,const char * zQuery,char ** pzErrMsg)886 static int run_schema_dump_query(
887   struct callback_data *p,
888   const char *zQuery,
889   char **pzErrMsg
890 ){
891   int rc;
892   rc = sqlite3_exec(p->db, zQuery, dump_callback, p, pzErrMsg);
893   if( rc==SQLITE_CORRUPT ){
894     char *zQ2;
895     int len = strlen(zQuery);
896     if( pzErrMsg ) sqlite3_free(*pzErrMsg);
897     zQ2 = malloc( len+100 );
898     if( zQ2==0 ) return rc;
899     sqlite3_snprintf(sizeof(zQ2), zQ2, "%s ORDER BY rowid DESC", zQuery);
900     rc = sqlite3_exec(p->db, zQ2, dump_callback, p, pzErrMsg);
901     free(zQ2);
902   }
903   return rc;
904 }
905 
906 /*
907 ** Text of a help message
908 */
909 static char zHelp[] =
910   ".bail ON|OFF           Stop after hitting an error.  Default OFF\n"
911   ".databases             List names and files of attached databases\n"
912   ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
913   ".echo ON|OFF           Turn command echo on or off\n"
914   ".exit                  Exit this program\n"
915   ".explain ON|OFF        Turn output mode suitable for EXPLAIN on or off.\n"
916   ".header(s) ON|OFF      Turn display of headers on or off\n"
917   ".help                  Show this message\n"
918   ".import FILE TABLE     Import data from FILE into TABLE\n"
919   ".indices TABLE         Show names of all indices on TABLE\n"
920 #ifdef SQLITE_ENABLE_IOTRACE
921   ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
922 #endif
923 #ifndef SQLITE_OMIT_LOAD_EXTENSION
924   ".load FILE ?ENTRY?     Load an extension library\n"
925 #endif
926   ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
927   "                         csv      Comma-separated values\n"
928   "                         column   Left-aligned columns.  (See .width)\n"
929   "                         html     HTML <table> code\n"
930   "                         insert   SQL insert statements for TABLE\n"
931   "                         line     One value per line\n"
932   "                         list     Values delimited by .separator string\n"
933   "                         tabs     Tab-separated values\n"
934   "                         tcl      TCL list elements\n"
935   ".nullvalue STRING      Print STRING in place of NULL values\n"
936   ".output FILENAME       Send output to FILENAME\n"
937   ".output stdout         Send output to the screen\n"
938   ".prompt MAIN CONTINUE  Replace the standard prompts\n"
939   ".quit                  Exit this program\n"
940   ".read FILENAME         Execute SQL in FILENAME\n"
941   ".schema ?TABLE?        Show the CREATE statements\n"
942   ".separator STRING      Change separator used by output mode and .import\n"
943   ".show                  Show the current values for various settings\n"
944   ".tables ?PATTERN?      List names of tables matching a LIKE pattern\n"
945   ".timeout MS            Try opening locked tables for MS milliseconds\n"
946 #if HAS_TIMER
947   ".timer ON|OFF          Turn the CPU timer measurement on or off\n"
948 #endif
949   ".width NUM NUM ...     Set column widths for \"column\" mode\n"
950 ;
951 
952 /* Forward reference */
953 static int process_input(struct callback_data *p, FILE *in);
954 
955 /*
956 ** Make sure the database is open.  If it is not, then open it.  If
957 ** the database fails to open, print an error message and exit.
958 */
open_db(struct callback_data * p)959 static void open_db(struct callback_data *p){
960   if( p->db==0 ){
961     sqlite3_open(p->zDbFilename, &p->db);
962     db = p->db;
963     if( db && sqlite3_errcode(db)==SQLITE_OK ){
964       sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
965           shellstaticFunc, 0, 0);
966     }
967 #ifndef NO_ANDROID_FUNCS
968     register_android_functions(db, 0);
969     register_localized_collators(db, "", 0);
970 #endif
971     if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
972       fprintf(stderr,"Unable to open database \"%s\": %s\n",
973           p->zDbFilename, sqlite3_errmsg(db));
974       exit(1);
975     }
976 #ifndef SQLITE_OMIT_LOAD_EXTENSION
977     sqlite3_enable_load_extension(p->db, 1);
978 #endif
979   }
980 }
981 
982 /*
983 ** Do C-language style dequoting.
984 **
985 **    \t    -> tab
986 **    \n    -> newline
987 **    \r    -> carriage return
988 **    \NNN  -> ascii character NNN in octal
989 **    \\    -> backslash
990 */
resolve_backslashes(char * z)991 static void resolve_backslashes(char *z){
992   int i, j, c;
993   for(i=j=0; (c = z[i])!=0; i++, j++){
994     if( c=='\\' ){
995       c = z[++i];
996       if( c=='n' ){
997         c = '\n';
998       }else if( c=='t' ){
999         c = '\t';
1000       }else if( c=='r' ){
1001         c = '\r';
1002       }else if( c>='0' && c<='7' ){
1003         c -= '0';
1004         if( z[i+1]>='0' && z[i+1]<='7' ){
1005           i++;
1006           c = (c<<3) + z[i] - '0';
1007           if( z[i+1]>='0' && z[i+1]<='7' ){
1008             i++;
1009             c = (c<<3) + z[i] - '0';
1010           }
1011         }
1012       }
1013     }
1014     z[j] = c;
1015   }
1016   z[j] = 0;
1017 }
1018 
1019 /*
1020 ** Interpret zArg as a boolean value.  Return either 0 or 1.
1021 */
booleanValue(char * zArg)1022 static int booleanValue(char *zArg){
1023   int val = atoi(zArg);
1024   int j;
1025   for(j=0; zArg[j]; j++){
1026     zArg[j] = tolower(zArg[j]);
1027   }
1028   if( strcmp(zArg,"on")==0 ){
1029     val = 1;
1030   }else if( strcmp(zArg,"yes")==0 ){
1031     val = 1;
1032   }
1033   return val;
1034 }
1035 
1036 /*
1037 ** If an input line begins with "." then invoke this routine to
1038 ** process that line.
1039 **
1040 ** Return 1 on error, 2 to exit, and 0 otherwise.
1041 */
do_meta_command(char * zLine,struct callback_data * p)1042 static int do_meta_command(char *zLine, struct callback_data *p){
1043   int i = 1;
1044   int nArg = 0;
1045   int n, c;
1046   int rc = 0;
1047   char *azArg[50];
1048 
1049   /* Parse the input line into tokens.
1050   */
1051   while( zLine[i] && nArg<ArraySize(azArg) ){
1052     while( isspace((unsigned char)zLine[i]) ){ i++; }
1053     if( zLine[i]==0 ) break;
1054     if( zLine[i]=='\'' || zLine[i]=='"' ){
1055       int delim = zLine[i++];
1056       azArg[nArg++] = &zLine[i];
1057       while( zLine[i] && zLine[i]!=delim ){ i++; }
1058       if( zLine[i]==delim ){
1059         zLine[i++] = 0;
1060       }
1061       if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
1062     }else{
1063       azArg[nArg++] = &zLine[i];
1064       while( zLine[i] && !isspace((unsigned char)zLine[i]) ){ i++; }
1065       if( zLine[i] ) zLine[i++] = 0;
1066       resolve_backslashes(azArg[nArg-1]);
1067     }
1068   }
1069 
1070   /* Process the input line.
1071   */
1072   if( nArg==0 ) return rc;
1073   n = strlen(azArg[0]);
1074   c = azArg[0][0];
1075   if( c=='b' && n>1 && strncmp(azArg[0], "bail", n)==0 && nArg>1 ){
1076     bail_on_error = booleanValue(azArg[1]);
1077   }else
1078 
1079   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
1080     struct callback_data data;
1081     char *zErrMsg = 0;
1082     open_db(p);
1083     memcpy(&data, p, sizeof(data));
1084     data.showHeader = 1;
1085     data.mode = MODE_Column;
1086     data.colWidth[0] = 3;
1087     data.colWidth[1] = 15;
1088     data.colWidth[2] = 58;
1089     data.cnt = 0;
1090     sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
1091     if( zErrMsg ){
1092       fprintf(stderr,"Error: %s\n", zErrMsg);
1093       sqlite3_free(zErrMsg);
1094     }
1095   }else
1096 
1097   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
1098     char *zErrMsg = 0;
1099     open_db(p);
1100     fprintf(p->out, "BEGIN TRANSACTION;\n");
1101     p->writableSchema = 0;
1102     if( nArg==1 ){
1103       run_schema_dump_query(p,
1104         "SELECT name, type, sql FROM sqlite_master "
1105         "WHERE sql NOT NULL AND type=='table'", 0
1106       );
1107       run_table_dump_query(p->out, p->db,
1108         "SELECT sql FROM sqlite_master "
1109         "WHERE sql NOT NULL AND type IN ('index','trigger','view')"
1110       );
1111     }else{
1112       int i;
1113       for(i=1; i<nArg; i++){
1114         zShellStatic = azArg[i];
1115         run_schema_dump_query(p,
1116           "SELECT name, type, sql FROM sqlite_master "
1117           "WHERE tbl_name LIKE shellstatic() AND type=='table'"
1118           "  AND sql NOT NULL", 0);
1119         run_table_dump_query(p->out, p->db,
1120           "SELECT sql FROM sqlite_master "
1121           "WHERE sql NOT NULL"
1122           "  AND type IN ('index','trigger','view')"
1123           "  AND tbl_name LIKE shellstatic()"
1124         );
1125         zShellStatic = 0;
1126       }
1127     }
1128     if( p->writableSchema ){
1129       fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
1130       p->writableSchema = 0;
1131     }
1132     if( zErrMsg ){
1133       fprintf(stderr,"Error: %s\n", zErrMsg);
1134       sqlite3_free(zErrMsg);
1135     }else{
1136       fprintf(p->out, "COMMIT;\n");
1137     }
1138   }else
1139 
1140   if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 ){
1141     p->echoOn = booleanValue(azArg[1]);
1142   }else
1143 
1144   if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
1145     rc = 2;
1146   }else
1147 
1148   if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
1149     int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
1150     if(val == 1) {
1151       if(!p->explainPrev.valid) {
1152         p->explainPrev.valid = 1;
1153         p->explainPrev.mode = p->mode;
1154         p->explainPrev.showHeader = p->showHeader;
1155         memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
1156       }
1157       /* We could put this code under the !p->explainValid
1158       ** condition so that it does not execute if we are already in
1159       ** explain mode. However, always executing it allows us an easy
1160       ** was to reset to explain mode in case the user previously
1161       ** did an .explain followed by a .width, .mode or .header
1162       ** command.
1163       */
1164       p->mode = MODE_Explain;
1165       p->showHeader = 1;
1166       memset(p->colWidth,0,ArraySize(p->colWidth));
1167       p->colWidth[0] = 4;                  /* addr */
1168       p->colWidth[1] = 13;                 /* opcode */
1169       p->colWidth[2] = 4;                  /* P1 */
1170       p->colWidth[3] = 4;                  /* P2 */
1171       p->colWidth[4] = 4;                  /* P3 */
1172       p->colWidth[5] = 13;                 /* P4 */
1173       p->colWidth[6] = 2;                  /* P5 */
1174       p->colWidth[7] = 13;                  /* Comment */
1175     }else if (p->explainPrev.valid) {
1176       p->explainPrev.valid = 0;
1177       p->mode = p->explainPrev.mode;
1178       p->showHeader = p->explainPrev.showHeader;
1179       memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
1180     }
1181   }else
1182 
1183   if( c=='h' && (strncmp(azArg[0], "header", n)==0 ||
1184                  strncmp(azArg[0], "headers", n)==0 )&& nArg>1 ){
1185     p->showHeader = booleanValue(azArg[1]);
1186   }else
1187 
1188   if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
1189     fprintf(stderr,zHelp);
1190   }else
1191 
1192   if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg>=3 ){
1193     char *zTable = azArg[2];    /* Insert data into this table */
1194     char *zFile = azArg[1];     /* The file from which to extract data */
1195     sqlite3_stmt *pStmt;        /* A statement */
1196     int rc;                     /* Result code */
1197     int nCol;                   /* Number of columns in the table */
1198     int nByte;                  /* Number of bytes in an SQL string */
1199     int i, j;                   /* Loop counters */
1200     int nSep;                   /* Number of bytes in p->separator[] */
1201     char *zSql;                 /* An SQL statement */
1202     char *zLine;                /* A single line of input from the file */
1203     char **azCol;               /* zLine[] broken up into columns */
1204     char *zCommit;              /* How to commit changes */
1205     FILE *in;                   /* The input file */
1206     int lineno = 0;             /* Line number of input file */
1207 
1208     open_db(p);
1209     nSep = strlen(p->separator);
1210     if( nSep==0 ){
1211       fprintf(stderr, "non-null separator required for import\n");
1212       return 0;
1213     }
1214     zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
1215     if( zSql==0 ) return 0;
1216     nByte = strlen(zSql);
1217     rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
1218     sqlite3_free(zSql);
1219     if( rc ){
1220       fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
1221       nCol = 0;
1222       rc = 1;
1223     }else{
1224       nCol = sqlite3_column_count(pStmt);
1225     }
1226     sqlite3_finalize(pStmt);
1227     if( nCol==0 ) return 0;
1228     zSql = malloc( nByte + 20 + nCol*2 );
1229     if( zSql==0 ) return 0;
1230     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO '%q' VALUES(?", zTable);
1231     j = strlen(zSql);
1232     for(i=1; i<nCol; i++){
1233       zSql[j++] = ',';
1234       zSql[j++] = '?';
1235     }
1236     zSql[j++] = ')';
1237     zSql[j] = 0;
1238     rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
1239     free(zSql);
1240     if( rc ){
1241       fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
1242       sqlite3_finalize(pStmt);
1243       return 1;
1244     }
1245     in = fopen(zFile, "rb");
1246     if( in==0 ){
1247       fprintf(stderr, "cannot open file: %s\n", zFile);
1248       sqlite3_finalize(pStmt);
1249       return 0;
1250     }
1251     azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1252     if( azCol==0 ){
1253       fclose(in);
1254       return 0;
1255     }
1256     sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
1257     zCommit = "COMMIT";
1258     while( (zLine = local_getline(0, in))!=0 ){
1259       char *z;
1260       i = 0;
1261       lineno++;
1262       azCol[0] = zLine;
1263       for(i=0, z=zLine; *z && *z!='\n' && *z!='\r'; z++){
1264         if( *z==p->separator[0] && strncmp(z, p->separator, nSep)==0 ){
1265           *z = 0;
1266           i++;
1267           if( i<nCol ){
1268             azCol[i] = &z[nSep];
1269             z += nSep-1;
1270           }
1271         }
1272       }
1273       *z = 0;
1274       if( i+1!=nCol ){
1275         fprintf(stderr,"%s line %d: expected %d columns of data but found %d\n",
1276            zFile, lineno, nCol, i+1);
1277         zCommit = "ROLLBACK";
1278         break;
1279       }
1280       for(i=0; i<nCol; i++){
1281         sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1282       }
1283       sqlite3_step(pStmt);
1284       rc = sqlite3_reset(pStmt);
1285       free(zLine);
1286       if( rc!=SQLITE_OK ){
1287         fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
1288         zCommit = "ROLLBACK";
1289         rc = 1;
1290         break;
1291       }
1292     }
1293     free(azCol);
1294     fclose(in);
1295     sqlite3_finalize(pStmt);
1296     sqlite3_exec(p->db, zCommit, 0, 0, 0);
1297   }else
1298 
1299   if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg>1 ){
1300     struct callback_data data;
1301     char *zErrMsg = 0;
1302     open_db(p);
1303     memcpy(&data, p, sizeof(data));
1304     data.showHeader = 0;
1305     data.mode = MODE_List;
1306     zShellStatic = azArg[1];
1307     sqlite3_exec(p->db,
1308       "SELECT name FROM sqlite_master "
1309       "WHERE type='index' AND tbl_name LIKE shellstatic() "
1310       "UNION ALL "
1311       "SELECT name FROM sqlite_temp_master "
1312       "WHERE type='index' AND tbl_name LIKE shellstatic() "
1313       "ORDER BY 1",
1314       callback, &data, &zErrMsg
1315     );
1316     zShellStatic = 0;
1317     if( zErrMsg ){
1318       fprintf(stderr,"Error: %s\n", zErrMsg);
1319       sqlite3_free(zErrMsg);
1320     }
1321   }else
1322 
1323 #ifdef SQLITE_ENABLE_IOTRACE
1324   if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
1325     extern void (*sqlite3IoTrace)(const char*, ...);
1326     if( iotrace && iotrace!=stdout ) fclose(iotrace);
1327     iotrace = 0;
1328     if( nArg<2 ){
1329       sqlite3IoTrace = 0;
1330     }else if( strcmp(azArg[1], "-")==0 ){
1331       sqlite3IoTrace = iotracePrintf;
1332       iotrace = stdout;
1333     }else{
1334       iotrace = fopen(azArg[1], "w");
1335       if( iotrace==0 ){
1336         fprintf(stderr, "cannot open \"%s\"\n", azArg[1]);
1337         sqlite3IoTrace = 0;
1338       }else{
1339         sqlite3IoTrace = iotracePrintf;
1340       }
1341     }
1342   }else
1343 #endif
1344 
1345 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1346   if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){
1347     const char *zFile, *zProc;
1348     char *zErrMsg = 0;
1349     int rc;
1350     zFile = azArg[1];
1351     zProc = nArg>=3 ? azArg[2] : 0;
1352     open_db(p);
1353     rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
1354     if( rc!=SQLITE_OK ){
1355       fprintf(stderr, "%s\n", zErrMsg);
1356       sqlite3_free(zErrMsg);
1357       rc = 1;
1358     }
1359   }else
1360 #endif
1361 
1362   if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg>=2 ){
1363     int n2 = strlen(azArg[1]);
1364     if( strncmp(azArg[1],"line",n2)==0
1365         ||
1366         strncmp(azArg[1],"lines",n2)==0 ){
1367       p->mode = MODE_Line;
1368     }else if( strncmp(azArg[1],"column",n2)==0
1369               ||
1370               strncmp(azArg[1],"columns",n2)==0 ){
1371       p->mode = MODE_Column;
1372     }else if( strncmp(azArg[1],"list",n2)==0 ){
1373       p->mode = MODE_List;
1374     }else if( strncmp(azArg[1],"html",n2)==0 ){
1375       p->mode = MODE_Html;
1376     }else if( strncmp(azArg[1],"tcl",n2)==0 ){
1377       p->mode = MODE_Tcl;
1378     }else if( strncmp(azArg[1],"csv",n2)==0 ){
1379       p->mode = MODE_Csv;
1380       sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
1381     }else if( strncmp(azArg[1],"tabs",n2)==0 ){
1382       p->mode = MODE_List;
1383       sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
1384     }else if( strncmp(azArg[1],"insert",n2)==0 ){
1385       p->mode = MODE_Insert;
1386       if( nArg>=3 ){
1387         set_table_name(p, azArg[2]);
1388       }else{
1389         set_table_name(p, "table");
1390       }
1391     }else {
1392       fprintf(stderr,"mode should be one of: "
1393          "column csv html insert line list tabs tcl\n");
1394     }
1395   }else
1396 
1397   if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
1398     sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
1399                      "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
1400   }else
1401 
1402   if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
1403     if( p->out!=stdout ){
1404       fclose(p->out);
1405     }
1406     if( strcmp(azArg[1],"stdout")==0 ){
1407       p->out = stdout;
1408       sqlite3_snprintf(sizeof(p->outfile), p->outfile, "stdout");
1409     }else{
1410       p->out = fopen(azArg[1], "wb");
1411       if( p->out==0 ){
1412         fprintf(stderr,"can't write to \"%s\"\n", azArg[1]);
1413         p->out = stdout;
1414       } else {
1415          sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
1416       }
1417     }
1418   }else
1419 
1420   if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
1421     if( nArg >= 2) {
1422       strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
1423     }
1424     if( nArg >= 3) {
1425       strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
1426     }
1427   }else
1428 
1429   if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
1430     rc = 2;
1431   }else
1432 
1433   if( c=='r' && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
1434     FILE *alt = fopen(azArg[1], "rb");
1435     if( alt==0 ){
1436       fprintf(stderr,"can't open \"%s\"\n", azArg[1]);
1437     }else{
1438       process_input(p, alt);
1439       fclose(alt);
1440     }
1441   }else
1442 
1443   if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
1444     struct callback_data data;
1445     char *zErrMsg = 0;
1446     open_db(p);
1447     memcpy(&data, p, sizeof(data));
1448     data.showHeader = 0;
1449     data.mode = MODE_Semi;
1450     if( nArg>1 ){
1451       int i;
1452       for(i=0; azArg[1][i]; i++) azArg[1][i] = tolower(azArg[1][i]);
1453       if( strcmp(azArg[1],"sqlite_master")==0 ){
1454         char *new_argv[2], *new_colv[2];
1455         new_argv[0] = "CREATE TABLE sqlite_master (\n"
1456                       "  type text,\n"
1457                       "  name text,\n"
1458                       "  tbl_name text,\n"
1459                       "  rootpage integer,\n"
1460                       "  sql text\n"
1461                       ")";
1462         new_argv[1] = 0;
1463         new_colv[0] = "sql";
1464         new_colv[1] = 0;
1465         callback(&data, 1, new_argv, new_colv);
1466       }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
1467         char *new_argv[2], *new_colv[2];
1468         new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
1469                       "  type text,\n"
1470                       "  name text,\n"
1471                       "  tbl_name text,\n"
1472                       "  rootpage integer,\n"
1473                       "  sql text\n"
1474                       ")";
1475         new_argv[1] = 0;
1476         new_colv[0] = "sql";
1477         new_colv[1] = 0;
1478         callback(&data, 1, new_argv, new_colv);
1479       }else{
1480         zShellStatic = azArg[1];
1481         sqlite3_exec(p->db,
1482           "SELECT sql FROM "
1483           "  (SELECT * FROM sqlite_master UNION ALL"
1484           "   SELECT * FROM sqlite_temp_master) "
1485           "WHERE tbl_name LIKE shellstatic() AND type!='meta' AND sql NOTNULL "
1486           "ORDER BY substr(type,2,1), name",
1487           callback, &data, &zErrMsg);
1488         zShellStatic = 0;
1489       }
1490     }else{
1491       sqlite3_exec(p->db,
1492          "SELECT sql FROM "
1493          "  (SELECT * FROM sqlite_master UNION ALL"
1494          "   SELECT * FROM sqlite_temp_master) "
1495          "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
1496          "ORDER BY substr(type,2,1), name",
1497          callback, &data, &zErrMsg
1498       );
1499     }
1500     if( zErrMsg ){
1501       fprintf(stderr,"Error: %s\n", zErrMsg);
1502       sqlite3_free(zErrMsg);
1503     }
1504   }else
1505 
1506   if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
1507     sqlite3_snprintf(sizeof(p->separator), p->separator,
1508                      "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
1509   }else
1510 
1511   if( c=='s' && strncmp(azArg[0], "show", n)==0){
1512     int i;
1513     fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
1514     fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
1515     fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
1516     fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
1517     fprintf(p->out,"%9.9s: ", "nullvalue");
1518       output_c_string(p->out, p->nullvalue);
1519       fprintf(p->out, "\n");
1520     fprintf(p->out,"%9.9s: %s\n","output",
1521                                  strlen(p->outfile) ? p->outfile : "stdout");
1522     fprintf(p->out,"%9.9s: ", "separator");
1523       output_c_string(p->out, p->separator);
1524       fprintf(p->out, "\n");
1525     fprintf(p->out,"%9.9s: ","width");
1526     for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
1527       fprintf(p->out,"%d ",p->colWidth[i]);
1528     }
1529     fprintf(p->out,"\n");
1530   }else
1531 
1532   if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
1533     char **azResult;
1534     int nRow, rc;
1535     char *zErrMsg;
1536     open_db(p);
1537     if( nArg==1 ){
1538       rc = sqlite3_get_table(p->db,
1539         "SELECT name FROM sqlite_master "
1540         "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'"
1541         "UNION ALL "
1542         "SELECT name FROM sqlite_temp_master "
1543         "WHERE type IN ('table','view') "
1544         "ORDER BY 1",
1545         &azResult, &nRow, 0, &zErrMsg
1546       );
1547     }else{
1548       zShellStatic = azArg[1];
1549       rc = sqlite3_get_table(p->db,
1550         "SELECT name FROM sqlite_master "
1551         "WHERE type IN ('table','view') AND name LIKE '%'||shellstatic()||'%' "
1552         "UNION ALL "
1553         "SELECT name FROM sqlite_temp_master "
1554         "WHERE type IN ('table','view') AND name LIKE '%'||shellstatic()||'%' "
1555         "ORDER BY 1",
1556         &azResult, &nRow, 0, &zErrMsg
1557       );
1558       zShellStatic = 0;
1559     }
1560     if( zErrMsg ){
1561       fprintf(stderr,"Error: %s\n", zErrMsg);
1562       sqlite3_free(zErrMsg);
1563     }
1564     if( rc==SQLITE_OK ){
1565       int len, maxlen = 0;
1566       int i, j;
1567       int nPrintCol, nPrintRow;
1568       for(i=1; i<=nRow; i++){
1569         if( azResult[i]==0 ) continue;
1570         len = strlen(azResult[i]);
1571         if( len>maxlen ) maxlen = len;
1572       }
1573       nPrintCol = 80/(maxlen+2);
1574       if( nPrintCol<1 ) nPrintCol = 1;
1575       nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
1576       for(i=0; i<nPrintRow; i++){
1577         for(j=i+1; j<=nRow; j+=nPrintRow){
1578           char *zSp = j<=nPrintRow ? "" : "  ";
1579           printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
1580         }
1581         printf("\n");
1582       }
1583     }else{
1584       rc = 1;
1585     }
1586     sqlite3_free_table(azResult);
1587   }else
1588 
1589   if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg>=2 ){
1590     open_db(p);
1591     sqlite3_busy_timeout(p->db, atoi(azArg[1]));
1592   }else
1593 
1594 #if HAS_TIMER
1595   if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 && nArg>1 ){
1596     enableTimer = booleanValue(azArg[1]);
1597   }else
1598 #endif
1599 
1600   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
1601     int j;
1602     assert( nArg<=ArraySize(azArg) );
1603     for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
1604       p->colWidth[j-1] = atoi(azArg[j]);
1605     }
1606   }else
1607 
1608 
1609   {
1610     fprintf(stderr, "unknown command or invalid arguments: "
1611       " \"%s\". Enter \".help\" for help\n", azArg[0]);
1612   }
1613 
1614   return rc;
1615 }
1616 
1617 /*
1618 ** Return TRUE if a semicolon occurs anywhere in the first N characters
1619 ** of string z[].
1620 */
_contains_semicolon(const char * z,int N)1621 static int _contains_semicolon(const char *z, int N){
1622   int i;
1623   for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
1624   return 0;
1625 }
1626 
1627 /*
1628 ** Test to see if a line consists entirely of whitespace.
1629 */
_all_whitespace(const char * z)1630 static int _all_whitespace(const char *z){
1631   for(; *z; z++){
1632     if( isspace(*(unsigned char*)z) ) continue;
1633     if( *z=='/' && z[1]=='*' ){
1634       z += 2;
1635       while( *z && (*z!='*' || z[1]!='/') ){ z++; }
1636       if( *z==0 ) return 0;
1637       z++;
1638       continue;
1639     }
1640     if( *z=='-' && z[1]=='-' ){
1641       z += 2;
1642       while( *z && *z!='\n' ){ z++; }
1643       if( *z==0 ) return 1;
1644       continue;
1645     }
1646     return 0;
1647   }
1648   return 1;
1649 }
1650 
1651 /*
1652 ** Return TRUE if the line typed in is an SQL command terminator other
1653 ** than a semi-colon.  The SQL Server style "go" command is understood
1654 ** as is the Oracle "/".
1655 */
_is_command_terminator(const char * zLine)1656 static int _is_command_terminator(const char *zLine){
1657   while( isspace(*(unsigned char*)zLine) ){ zLine++; };
1658   if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ) return 1;  /* Oracle */
1659   if( tolower(zLine[0])=='g' && tolower(zLine[1])=='o'
1660          && _all_whitespace(&zLine[2]) ){
1661     return 1;  /* SQL Server */
1662   }
1663   return 0;
1664 }
1665 
1666 /*
1667 ** Read input from *in and process it.  If *in==0 then input
1668 ** is interactive - the user is typing it it.  Otherwise, input
1669 ** is coming from a file or device.  A prompt is issued and history
1670 ** is saved only if input is interactive.  An interrupt signal will
1671 ** cause this routine to exit immediately, unless input is interactive.
1672 **
1673 ** Return the number of errors.
1674 */
process_input(struct callback_data * p,FILE * in)1675 static int process_input(struct callback_data *p, FILE *in){
1676   char *zLine = 0;
1677   char *zSql = 0;
1678   int nSql = 0;
1679   int nSqlPrior = 0;
1680   char *zErrMsg;
1681   int rc;
1682   int errCnt = 0;
1683   int lineno = 0;
1684   int startline = 0;
1685 
1686   while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
1687     fflush(p->out);
1688     free(zLine);
1689     zLine = one_input_line(zSql, in);
1690     if( zLine==0 ){
1691       break;  /* We have reached EOF */
1692     }
1693     if( seenInterrupt ){
1694       if( in!=0 ) break;
1695       seenInterrupt = 0;
1696     }
1697     lineno++;
1698     if( p->echoOn ) printf("%s\n", zLine);
1699     if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
1700     if( zLine && zLine[0]=='.' && nSql==0 ){
1701       rc = do_meta_command(zLine, p);
1702       if( rc==2 ){
1703         break;
1704       }else if( rc ){
1705         errCnt++;
1706       }
1707       continue;
1708     }
1709     if( _is_command_terminator(zLine) ){
1710       memcpy(zLine,";",2);
1711     }
1712     nSqlPrior = nSql;
1713     if( zSql==0 ){
1714       int i;
1715       for(i=0; zLine[i] && isspace((unsigned char)zLine[i]); i++){}
1716       if( zLine[i]!=0 ){
1717         nSql = strlen(zLine);
1718         zSql = malloc( nSql+1 );
1719         if( zSql==0 ){
1720           fprintf(stderr, "out of memory\n");
1721           exit(1);
1722         }
1723         memcpy(zSql, zLine, nSql+1);
1724         startline = lineno;
1725       }
1726     }else{
1727       int len = strlen(zLine);
1728       zSql = realloc( zSql, nSql + len + 2 );
1729       if( zSql==0 ){
1730         fprintf(stderr,"%s: out of memory!\n", Argv0);
1731         exit(1);
1732       }
1733       zSql[nSql++] = '\n';
1734       memcpy(&zSql[nSql], zLine, len+1);
1735       nSql += len;
1736     }
1737     if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
1738                 && sqlite3_complete(zSql) ){
1739       p->cnt = 0;
1740       open_db(p);
1741       BEGIN_TIMER;
1742       rc = sqlite3_exec(p->db, zSql, callback, p, &zErrMsg);
1743       END_TIMER;
1744       if( rc || zErrMsg ){
1745         char zPrefix[100];
1746         if( in!=0 || !stdin_is_interactive ){
1747           sqlite3_snprintf(sizeof(zPrefix), zPrefix,
1748                            "SQL error near line %d:", startline);
1749         }else{
1750           sqlite3_snprintf(sizeof(zPrefix), zPrefix, "SQL error:");
1751         }
1752         if( zErrMsg!=0 ){
1753           printf("%s %s\n", zPrefix, zErrMsg);
1754           sqlite3_free(zErrMsg);
1755           zErrMsg = 0;
1756         }else{
1757           printf("%s %s\n", zPrefix, sqlite3_errmsg(p->db));
1758         }
1759         errCnt++;
1760       }
1761       free(zSql);
1762       zSql = 0;
1763       nSql = 0;
1764     }
1765   }
1766   if( zSql ){
1767     if( !_all_whitespace(zSql) ) printf("Incomplete SQL: %s\n", zSql);
1768     free(zSql);
1769   }
1770   free(zLine);
1771   return errCnt;
1772 }
1773 
1774 /*
1775 ** Return a pathname which is the user's home directory.  A
1776 ** 0 return indicates an error of some kind.  Space to hold the
1777 ** resulting string is obtained from malloc().  The calling
1778 ** function should free the result.
1779 */
find_home_dir(void)1780 static char *find_home_dir(void){
1781   char *home_dir = NULL;
1782 
1783 #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(_WIN32_WCE)
1784   struct passwd *pwent;
1785   uid_t uid = getuid();
1786   if( (pwent=getpwuid(uid)) != NULL) {
1787     home_dir = pwent->pw_dir;
1788   }
1789 #endif
1790 
1791 #if defined(_WIN32_WCE)
1792   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
1793    */
1794   home_dir = strdup("/");
1795 #else
1796 
1797 #if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
1798   if (!home_dir) {
1799     home_dir = getenv("USERPROFILE");
1800   }
1801 #endif
1802 
1803   if (!home_dir) {
1804     home_dir = getenv("HOME");
1805   }
1806 
1807 #if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
1808   if (!home_dir) {
1809     char *zDrive, *zPath;
1810     int n;
1811     zDrive = getenv("HOMEDRIVE");
1812     zPath = getenv("HOMEPATH");
1813     if( zDrive && zPath ){
1814       n = strlen(zDrive) + strlen(zPath) + 1;
1815       home_dir = malloc( n );
1816       if( home_dir==0 ) return 0;
1817       sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
1818       return home_dir;
1819     }
1820     home_dir = "c:\\";
1821   }
1822 #endif
1823 
1824 #endif /* !_WIN32_WCE */
1825 
1826   if( home_dir ){
1827     int n = strlen(home_dir) + 1;
1828     char *z = malloc( n );
1829     if( z ) memcpy(z, home_dir, n);
1830     home_dir = z;
1831   }
1832 
1833   return home_dir;
1834 }
1835 
1836 /*
1837 ** Read input from the file given by sqliterc_override.  Or if that
1838 ** parameter is NULL, take input from ~/.sqliterc
1839 */
process_sqliterc(struct callback_data * p,const char * sqliterc_override)1840 static void process_sqliterc(
1841   struct callback_data *p,        /* Configuration data */
1842   const char *sqliterc_override   /* Name of config file. NULL to use default */
1843 ){
1844   char *home_dir = NULL;
1845   const char *sqliterc = sqliterc_override;
1846   char *zBuf = 0;
1847   FILE *in = NULL;
1848   int nBuf;
1849 
1850   if (sqliterc == NULL) {
1851     home_dir = find_home_dir();
1852     if( home_dir==0 ){
1853       fprintf(stderr,"%s: cannot locate your home directory!\n", Argv0);
1854       return;
1855     }
1856     nBuf = strlen(home_dir) + 16;
1857     zBuf = malloc( nBuf );
1858     if( zBuf==0 ){
1859       fprintf(stderr,"%s: out of memory!\n", Argv0);
1860       exit(1);
1861     }
1862     sqlite3_snprintf(nBuf, zBuf,"%s/.sqliterc",home_dir);
1863     free(home_dir);
1864     sqliterc = (const char*)zBuf;
1865   }
1866   in = fopen(sqliterc,"rb");
1867   if( in ){
1868     if( stdin_is_interactive ){
1869       printf("-- Loading resources from %s\n",sqliterc);
1870     }
1871     process_input(p,in);
1872     fclose(in);
1873   }
1874   free(zBuf);
1875   return;
1876 }
1877 
1878 /*
1879 ** Show available command line options
1880 */
1881 static const char zOptions[] =
1882   "   -init filename       read/process named file\n"
1883   "   -echo                print commands before execution\n"
1884   "   -[no]header          turn headers on or off\n"
1885   "   -bail                stop after hitting an error\n"
1886   "   -interactive         force interactive I/O\n"
1887   "   -batch               force batch I/O\n"
1888   "   -column              set output mode to 'column'\n"
1889   "   -csv                 set output mode to 'csv'\n"
1890   "   -html                set output mode to HTML\n"
1891   "   -line                set output mode to 'line'\n"
1892   "   -list                set output mode to 'list'\n"
1893   "   -separator 'x'       set output field separator (|)\n"
1894   "   -nullvalue 'text'    set text string for NULL values\n"
1895   "   -version             show SQLite version\n"
1896 ;
usage(int showDetail)1897 static void usage(int showDetail){
1898   fprintf(stderr,
1899       "Usage: %s [OPTIONS] FILENAME [SQL]\n"
1900       "FILENAME is the name of an SQLite database. A new database is created\n"
1901       "if the file does not previously exist.\n", Argv0);
1902   if( showDetail ){
1903     fprintf(stderr, "OPTIONS include:\n%s", zOptions);
1904   }else{
1905     fprintf(stderr, "Use the -help option for additional information\n");
1906   }
1907   exit(1);
1908 }
1909 
1910 /*
1911 ** Initialize the state information in data
1912 */
main_init(struct callback_data * data)1913 static void main_init(struct callback_data *data) {
1914   memset(data, 0, sizeof(*data));
1915   data->mode = MODE_List;
1916   memcpy(data->separator,"|", 2);
1917   data->showHeader = 0;
1918   sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
1919   sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
1920 }
1921 
main(int argc,char ** argv)1922 int main(int argc, char **argv){
1923   char *zErrMsg = 0;
1924   struct callback_data data;
1925   const char *zInitFile = 0;
1926   char *zFirstCmd = 0;
1927   int i;
1928   int rc = 0;
1929 
1930   Argv0 = argv[0];
1931   main_init(&data);
1932   stdin_is_interactive = isatty(0);
1933 
1934   /* Make sure we have a valid signal handler early, before anything
1935   ** else is done.
1936   */
1937 #ifdef SIGINT
1938   signal(SIGINT, interrupt_handler);
1939 #endif
1940 
1941   /* Do an initial pass through the command-line argument to locate
1942   ** the name of the database file, the name of the initialization file,
1943   ** and the first command to execute.
1944   */
1945   for(i=1; i<argc-1; i++){
1946     char *z;
1947     if( argv[i][0]!='-' ) break;
1948     z = argv[i];
1949     if( z[0]=='-' && z[1]=='-' ) z++;
1950     if( strcmp(argv[i],"-separator")==0 || strcmp(argv[i],"-nullvalue")==0 ){
1951       i++;
1952     }else if( strcmp(argv[i],"-init")==0 ){
1953       i++;
1954       zInitFile = argv[i];
1955     }
1956   }
1957   if( i<argc ){
1958 #ifdef OS_OS2
1959     data.zDbFilename = (const char *)convertCpPathToUtf8( argv[i++] );
1960 #else
1961     data.zDbFilename = argv[i++];
1962 #endif
1963   }else{
1964 #ifndef SQLITE_OMIT_MEMORYDB
1965     data.zDbFilename = ":memory:";
1966 #else
1967     data.zDbFilename = 0;
1968 #endif
1969   }
1970   if( i<argc ){
1971     zFirstCmd = argv[i++];
1972   }
1973   data.out = stdout;
1974 
1975 #ifdef SQLITE_OMIT_MEMORYDB
1976   if( data.zDbFilename==0 ){
1977     fprintf(stderr,"%s: no database filename specified\n", argv[0]);
1978     exit(1);
1979   }
1980 #endif
1981 
1982   /* Go ahead and open the database file if it already exists.  If the
1983   ** file does not exist, delay opening it.  This prevents empty database
1984   ** files from being created if a user mistypes the database name argument
1985   ** to the sqlite command-line tool.
1986   */
1987   if( access(data.zDbFilename, 0)==0 ){
1988     open_db(&data);
1989   }
1990 
1991   /* Process the initialization file if there is one.  If no -init option
1992   ** is given on the command line, look for a file named ~/.sqliterc and
1993   ** try to process it.
1994   */
1995   process_sqliterc(&data,zInitFile);
1996 
1997   /* Make a second pass through the command-line argument and set
1998   ** options.  This second pass is delayed until after the initialization
1999   ** file is processed so that the command-line arguments will override
2000   ** settings in the initialization file.
2001   */
2002   for(i=1; i<argc && argv[i][0]=='-'; i++){
2003     char *z = argv[i];
2004     if( z[1]=='-' ){ z++; }
2005     if( strcmp(z,"-init")==0 ){
2006       i++;
2007     }else if( strcmp(z,"-html")==0 ){
2008       data.mode = MODE_Html;
2009     }else if( strcmp(z,"-list")==0 ){
2010       data.mode = MODE_List;
2011     }else if( strcmp(z,"-line")==0 ){
2012       data.mode = MODE_Line;
2013     }else if( strcmp(z,"-column")==0 ){
2014       data.mode = MODE_Column;
2015     }else if( strcmp(z,"-csv")==0 ){
2016       data.mode = MODE_Csv;
2017       memcpy(data.separator,",",2);
2018     }else if( strcmp(z,"-separator")==0 ){
2019       i++;
2020       sqlite3_snprintf(sizeof(data.separator), data.separator,
2021                        "%.*s",(int)sizeof(data.separator)-1,argv[i]);
2022     }else if( strcmp(z,"-nullvalue")==0 ){
2023       i++;
2024       sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
2025                        "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
2026     }else if( strcmp(z,"-header")==0 ){
2027       data.showHeader = 1;
2028     }else if( strcmp(z,"-noheader")==0 ){
2029       data.showHeader = 0;
2030     }else if( strcmp(z,"-echo")==0 ){
2031       data.echoOn = 1;
2032     }else if( strcmp(z,"-bail")==0 ){
2033       bail_on_error = 1;
2034     }else if( strcmp(z,"-version")==0 ){
2035       printf("%s\n", sqlite3_libversion());
2036       return 0;
2037     }else if( strcmp(z,"-interactive")==0 ){
2038       stdin_is_interactive = 1;
2039     }else if( strcmp(z,"-batch")==0 ){
2040       stdin_is_interactive = 0;
2041     }else if( strcmp(z,"-help")==0 || strcmp(z, "--help")==0 ){
2042       usage(1);
2043     }else{
2044       fprintf(stderr,"%s: unknown option: %s\n", Argv0, z);
2045       fprintf(stderr,"Use -help for a list of options.\n");
2046       return 1;
2047     }
2048   }
2049 
2050   if( zFirstCmd ){
2051     /* Run just the command that follows the database name
2052     */
2053     if( zFirstCmd[0]=='.' ){
2054       do_meta_command(zFirstCmd, &data);
2055       exit(0);
2056     }else{
2057       int rc;
2058       open_db(&data);
2059       rc = sqlite3_exec(data.db, zFirstCmd, callback, &data, &zErrMsg);
2060       if( rc!=0 && zErrMsg!=0 ){
2061         fprintf(stderr,"SQL error: %s\n", zErrMsg);
2062         exit(1);
2063       }
2064     }
2065   }else{
2066     /* Run commands received from standard input
2067     */
2068     if( stdin_is_interactive ){
2069       char *zHome;
2070       char *zHistory = 0;
2071       int nHistory;
2072       printf(
2073         "SQLite version %s\n"
2074         "Enter \".help\" for instructions\n",
2075         sqlite3_libversion()
2076       );
2077       zHome = find_home_dir();
2078       if( zHome && (zHistory = malloc(nHistory = strlen(zHome)+20))!=0 ){
2079         sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
2080       }
2081 #if defined(HAVE_READLINE) && HAVE_READLINE==1
2082       if( zHistory ) read_history(zHistory);
2083 #endif
2084       rc = process_input(&data, 0);
2085       if( zHistory ){
2086         stifle_history(100);
2087         write_history(zHistory);
2088         free(zHistory);
2089       }
2090       free(zHome);
2091     }else{
2092       rc = process_input(&data, stdin);
2093     }
2094   }
2095   set_table_name(&data, 0);
2096   if( db ){
2097     if( sqlite3_close(db)!=SQLITE_OK ){
2098       fprintf(stderr,"error closing database: %s\n", sqlite3_errmsg(db));
2099     }
2100   }
2101   return rc;
2102 }
2103