00001 /* 00002 ** 2001 September 15 00003 ** 00004 ** The author disclaims copyright to this source code. In place of 00005 ** a legal notice, here is a blessing: 00006 ** 00007 ** May you do good and not evil. 00008 ** May you find forgiveness for yourself and forgive others. 00009 ** May you share freely, never taking more than you give. 00010 ** 00011 ************************************************************************* 00012 ** This file contains code to implement the "sqlite" command line 00013 ** utility for accessing SQLite databases. 00014 ** 00015 ** $Id: shell.c,v 1.187 2008/11/11 18:55:04 drh Exp $ 00016 */ 00017 #include <stdlib.h> 00018 #include <string.h> 00019 #include <stdio.h> 00020 #include <assert.h> 00021 #include "sqlite3.h" 00022 #include <ctype.h> 00023 #include <stdarg.h> 00024 00025 #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) 00026 # include <signal.h> 00027 # include <pwd.h> 00028 # include <unistd.h> 00029 # include <sys/types.h> 00030 #endif 00031 00032 #ifdef __OS2__ 00033 # include <unistd.h> 00034 #endif 00035 00036 #if defined(HAVE_READLINE) && HAVE_READLINE==1 00037 # include <readline/readline.h> 00038 # include <readline/history.h> 00039 #else 00040 # define readline(p) local_getline(p,stdin) 00041 # define add_history(X) 00042 # define read_history(X) 00043 # define write_history(X) 00044 # define stifle_history(X) 00045 #endif 00046 00047 #if defined(_WIN32) || defined(WIN32) 00048 # include <io.h> 00049 #else 00050 /* Make sure isatty() has a prototype. 00051 */ 00052 extern int isatty(); 00053 #endif 00054 00055 #if defined(_WIN32_WCE) 00056 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() 00057 * thus we always assume that we have a console. That can be 00058 * overridden with the -batch command line option. 00059 */ 00060 #define isatty(x) 1 00061 #endif 00062 00063 #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) 00064 #include <sys/time.h> 00065 #include <sys/resource.h> 00066 00067 /* Saved resource information for the beginning of an operation */ 00068 static struct rusage sBegin; 00069 00070 /* True if the timer is enabled */ 00071 static int enableTimer = 0; 00072 00073 /* 00074 ** Begin timing an operation 00075 */ 00076 static void beginTimer(void){ 00077 if( enableTimer ){ 00078 getrusage(RUSAGE_SELF, &sBegin); 00079 } 00080 } 00081 00082 /* Return the difference of two time_structs in seconds */ 00083 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ 00084 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + 00085 (double)(pEnd->tv_sec - pStart->tv_sec); 00086 } 00087 00088 /* 00089 ** Print the timing results. 00090 */ 00091 static void endTimer(void){ 00092 if( enableTimer ){ 00093 struct rusage sEnd; 00094 getrusage(RUSAGE_SELF, &sEnd); 00095 printf("CPU Time: user %f sys %f\n", 00096 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), 00097 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); 00098 } 00099 } 00100 #define BEGIN_TIMER beginTimer() 00101 #define END_TIMER endTimer() 00102 #define HAS_TIMER 1 00103 #else 00104 #define BEGIN_TIMER 00105 #define END_TIMER 00106 #define HAS_TIMER 0 00107 #endif 00108 00109 00110 /* 00111 ** If the following flag is set, then command execution stops 00112 ** at an error if we are not interactive. 00113 */ 00114 static int bail_on_error = 0; 00115 00116 /* 00117 ** Threat stdin as an interactive input if the following variable 00118 ** is true. Otherwise, assume stdin is connected to a file or pipe. 00119 */ 00120 static int stdin_is_interactive = 1; 00121 00122 /* 00123 ** The following is the open SQLite database. We make a pointer 00124 ** to this database a static variable so that it can be accessed 00125 ** by the SIGINT handler to interrupt database processing. 00126 */ 00127 static sqlite3 *db = 0; 00128 00129 /* 00130 ** True if an interrupt (Control-C) has been received. 00131 */ 00132 static volatile int seenInterrupt = 0; 00133 00134 /* 00135 ** This is the name of our program. It is set in main(), used 00136 ** in a number of other places, mostly for error messages. 00137 */ 00138 static char *Argv0; 00139 00140 /* 00141 ** Prompt strings. Initialized in main. Settable with 00142 ** .prompt main continue 00143 */ 00144 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ 00145 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ 00146 00147 /* 00148 ** Write I/O traces to the following stream. 00149 */ 00150 #ifdef SQLITE_ENABLE_IOTRACE 00151 static FILE *iotrace = 0; 00152 #endif 00153 00154 /* 00155 ** This routine works like printf in that its first argument is a 00156 ** format string and subsequent arguments are values to be substituted 00157 ** in place of % fields. The result of formatting this string 00158 ** is written to iotrace. 00159 */ 00160 #ifdef SQLITE_ENABLE_IOTRACE 00161 static void iotracePrintf(const char *zFormat, ...){ 00162 va_list ap; 00163 char *z; 00164 if( iotrace==0 ) return; 00165 va_start(ap, zFormat); 00166 z = sqlite3_vmprintf(zFormat, ap); 00167 va_end(ap); 00168 fprintf(iotrace, "%s", z); 00169 sqlite3_free(z); 00170 } 00171 #endif 00172 00173 00174 /* 00175 ** Determines if a string is a number of not. 00176 */ 00177 static int isNumber(const char *z, int *realnum){ 00178 if( *z=='-' || *z=='+' ) z++; 00179 if( !isdigit(*z) ){ 00180 return 0; 00181 } 00182 z++; 00183 if( realnum ) *realnum = 0; 00184 while( isdigit(*z) ){ z++; } 00185 if( *z=='.' ){ 00186 z++; 00187 if( !isdigit(*z) ) return 0; 00188 while( isdigit(*z) ){ z++; } 00189 if( realnum ) *realnum = 1; 00190 } 00191 if( *z=='e' || *z=='E' ){ 00192 z++; 00193 if( *z=='+' || *z=='-' ) z++; 00194 if( !isdigit(*z) ) return 0; 00195 while( isdigit(*z) ){ z++; } 00196 if( realnum ) *realnum = 1; 00197 } 00198 return *z==0; 00199 } 00200 00201 /* 00202 ** A global char* and an SQL function to access its current value 00203 ** from within an SQL statement. This program used to use the 00204 ** sqlite_exec_printf() API to substitue a string into an SQL statement. 00205 ** The correct way to do this with sqlite3 is to use the bind API, but 00206 ** since the shell is built around the callback paradigm it would be a lot 00207 ** of work. Instead just use this hack, which is quite harmless. 00208 */ 00209 static const char *zShellStatic = 0; 00210 static void shellstaticFunc( 00211 sqlite3_context *context, 00212 int argc, 00213 sqlite3_value **argv 00214 ){ 00215 assert( 0==argc ); 00216 assert( zShellStatic ); 00217 sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC); 00218 } 00219 00220 00221 /* 00222 ** This routine reads a line of text from FILE in, stores 00223 ** the text in memory obtained from malloc() and returns a pointer 00224 ** to the text. NULL is returned at end of file, or if malloc() 00225 ** fails. 00226 ** 00227 ** The interface is like "readline" but no command-line editing 00228 ** is done. 00229 */ 00230 static char *local_getline(char *zPrompt, FILE *in){ 00231 char *zLine; 00232 int nLine; 00233 int n; 00234 int eol; 00235 00236 if( zPrompt && *zPrompt ){ 00237 printf("%s",zPrompt); 00238 fflush(stdout); 00239 } 00240 nLine = 100; 00241 zLine = malloc( nLine ); 00242 if( zLine==0 ) return 0; 00243 n = 0; 00244 eol = 0; 00245 while( !eol ){ 00246 if( n+100>nLine ){ 00247 nLine = nLine*2 + 100; 00248 zLine = realloc(zLine, nLine); 00249 if( zLine==0 ) return 0; 00250 } 00251 if( fgets(&zLine[n], nLine - n, in)==0 ){ 00252 if( n==0 ){ 00253 free(zLine); 00254 return 0; 00255 } 00256 zLine[n] = 0; 00257 eol = 1; 00258 break; 00259 } 00260 while( zLine[n] ){ n++; } 00261 if( n>0 && zLine[n-1]=='\n' ){ 00262 n--; 00263 zLine[n] = 0; 00264 eol = 1; 00265 } 00266 } 00267 zLine = realloc( zLine, n+1 ); 00268 return zLine; 00269 } 00270 00271 /* 00272 ** Retrieve a single line of input text. 00273 ** 00274 ** zPrior is a string of prior text retrieved. If not the empty 00275 ** string, then issue a continuation prompt. 00276 */ 00277 static char *one_input_line(const char *zPrior, FILE *in){ 00278 char *zPrompt; 00279 char *zResult; 00280 if( in!=0 ){ 00281 return local_getline(0, in); 00282 } 00283 if( zPrior && zPrior[0] ){ 00284 zPrompt = continuePrompt; 00285 }else{ 00286 zPrompt = mainPrompt; 00287 } 00288 zResult = readline(zPrompt); 00289 #if defined(HAVE_READLINE) && HAVE_READLINE==1 00290 if( zResult && *zResult ) add_history(zResult); 00291 #endif 00292 return zResult; 00293 } 00294 00295 struct previous_mode_data { 00296 int valid; /* Is there legit data in here? */ 00297 int mode; 00298 int showHeader; 00299 int colWidth[100]; 00300 }; 00301 00302 /* 00303 ** An pointer to an instance of this structure is passed from 00304 ** the main program to the callback. This is used to communicate 00305 ** state and mode information. 00306 */ 00307 struct callback_data { 00308 sqlite3 *db; /* The database */ 00309 int echoOn; /* True to echo input commands */ 00310 int cnt; /* Number of records displayed so far */ 00311 FILE *out; /* Write results here */ 00312 int mode; /* An output mode setting */ 00313 int writableSchema; /* True if PRAGMA writable_schema=ON */ 00314 int showHeader; /* True to show column names in List or Column mode */ 00315 char *zDestTable; /* Name of destination table when MODE_Insert */ 00316 char separator[20]; /* Separator character for MODE_List */ 00317 int colWidth[100]; /* Requested width of each column when in column mode*/ 00318 int actualWidth[100]; /* Actual width of each column */ 00319 char nullvalue[20]; /* The text to print when a NULL comes back from 00320 ** the database */ 00321 struct previous_mode_data explainPrev; 00322 /* Holds the mode information just before 00323 ** .explain ON */ 00324 char outfile[FILENAME_MAX]; /* Filename for *out */ 00325 const char *zDbFilename; /* name of the database file */ 00326 }; 00327 00328 /* 00329 ** These are the allowed modes. 00330 */ 00331 #define MODE_Line 0 /* One column per line. Blank line between records */ 00332 #define MODE_Column 1 /* One record per line in neat columns */ 00333 #define MODE_List 2 /* One record per line with a separator */ 00334 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ 00335 #define MODE_Html 4 /* Generate an XHTML table */ 00336 #define MODE_Insert 5 /* Generate SQL "insert" statements */ 00337 #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */ 00338 #define MODE_Csv 7 /* Quote strings, numbers are plain */ 00339 #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */ 00340 00341 static const char *modeDescr[] = { 00342 "line", 00343 "column", 00344 "list", 00345 "semi", 00346 "html", 00347 "insert", 00348 "tcl", 00349 "csv", 00350 "explain", 00351 }; 00352 00353 /* 00354 ** Number of elements in an array 00355 */ 00356 #define ArraySize(X) (sizeof(X)/sizeof(X[0])) 00357 00358 /* 00359 ** Output the given string as a quoted string using SQL quoting conventions. 00360 */ 00361 static void output_quoted_string(FILE *out, const char *z){ 00362 int i; 00363 int nSingle = 0; 00364 for(i=0; z[i]; i++){ 00365 if( z[i]=='\'' ) nSingle++; 00366 } 00367 if( nSingle==0 ){ 00368 fprintf(out,"'%s'",z); 00369 }else{ 00370 fprintf(out,"'"); 00371 while( *z ){ 00372 for(i=0; z[i] && z[i]!='\''; i++){} 00373 if( i==0 ){ 00374 fprintf(out,"''"); 00375 z++; 00376 }else if( z[i]=='\'' ){ 00377 fprintf(out,"%.*s''",i,z); 00378 z += i+1; 00379 }else{ 00380 fprintf(out,"%s",z); 00381 break; 00382 } 00383 } 00384 fprintf(out,"'"); 00385 } 00386 } 00387 00388 /* 00389 ** Output the given string as a quoted according to C or TCL quoting rules. 00390 */ 00391 static void output_c_string(FILE *out, const char *z){ 00392 unsigned int c; 00393 fputc('"', out); 00394 while( (c = *(z++))!=0 ){ 00395 if( c=='\\' ){ 00396 fputc(c, out); 00397 fputc(c, out); 00398 }else if( c=='\t' ){ 00399 fputc('\\', out); 00400 fputc('t', out); 00401 }else if( c=='\n' ){ 00402 fputc('\\', out); 00403 fputc('n', out); 00404 }else if( c=='\r' ){ 00405 fputc('\\', out); 00406 fputc('r', out); 00407 }else if( !isprint(c) ){ 00408 fprintf(out, "\\%03o", c&0xff); 00409 }else{ 00410 fputc(c, out); 00411 } 00412 } 00413 fputc('"', out); 00414 } 00415 00416 /* 00417 ** Output the given string with characters that are special to 00418 ** HTML escaped. 00419 */ 00420 static void output_html_string(FILE *out, const char *z){ 00421 int i; 00422 while( *z ){ 00423 for(i=0; z[i] && z[i]!='<' && z[i]!='&'; i++){} 00424 if( i>0 ){ 00425 fprintf(out,"%.*s",i,z); 00426 } 00427 if( z[i]=='<' ){ 00428 fprintf(out,"<"); 00429 }else if( z[i]=='&' ){ 00430 fprintf(out,"&"); 00431 }else{ 00432 break; 00433 } 00434 z += i + 1; 00435 } 00436 } 00437 00438 /* 00439 ** If a field contains any character identified by a 1 in the following 00440 ** array, then the string must be quoted for CSV. 00441 */ 00442 static const char needCsvQuote[] = { 00443 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 00444 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 00445 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 00446 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 00447 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 00448 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 00449 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 00450 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 00451 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 00452 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 00453 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 00454 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 00455 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 00456 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 00457 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 00458 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 00459 }; 00460 00461 /* 00462 ** Output a single term of CSV. Actually, p->separator is used for 00463 ** the separator, which may or may not be a comma. p->nullvalue is 00464 ** the null value. Strings are quoted using ANSI-C rules. Numbers 00465 ** appear outside of quotes. 00466 */ 00467 static void output_csv(struct callback_data *p, const char *z, int bSep){ 00468 FILE *out = p->out; 00469 if( z==0 ){ 00470 fprintf(out,"%s",p->nullvalue); 00471 }else{ 00472 int i; 00473 int nSep = strlen(p->separator); 00474 for(i=0; z[i]; i++){ 00475 if( needCsvQuote[((unsigned char*)z)[i]] 00476 || (z[i]==p->separator[0] && 00477 (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){ 00478 i = 0; 00479 break; 00480 } 00481 } 00482 if( i==0 ){ 00483 putc('"', out); 00484 for(i=0; z[i]; i++){ 00485 if( z[i]=='"' ) putc('"', out); 00486 putc(z[i], out); 00487 } 00488 putc('"', out); 00489 }else{ 00490 fprintf(out, "%s", z); 00491 } 00492 } 00493 if( bSep ){ 00494 fprintf(p->out, "%s", p->separator); 00495 } 00496 } 00497 00498 #ifdef SIGINT 00499 /* 00500 ** This routine runs when the user presses Ctrl-C 00501 */ 00502 static void interrupt_handler(int NotUsed){ 00503 seenInterrupt = 1; 00504 if( db ) sqlite3_interrupt(db); 00505 } 00506 #endif 00507 00508 /* 00509 ** This is the callback routine that the SQLite library 00510 ** invokes for each row of a query result. 00511 */ 00512 static int callback(void *pArg, int nArg, char **azArg, char **azCol){ 00513 int i; 00514 struct callback_data *p = (struct callback_data*)pArg; 00515 switch( p->mode ){ 00516 case MODE_Line: { 00517 int w = 5; 00518 if( azArg==0 ) break; 00519 for(i=0; i<nArg; i++){ 00520 int len = strlen(azCol[i] ? azCol[i] : ""); 00521 if( len>w ) w = len; 00522 } 00523 if( p->cnt++>0 ) fprintf(p->out,"\n"); 00524 for(i=0; i<nArg; i++){ 00525 fprintf(p->out,"%*s = %s\n", w, azCol[i], 00526 azArg[i] ? azArg[i] : p->nullvalue); 00527 } 00528 break; 00529 } 00530 case MODE_Explain: 00531 case MODE_Column: { 00532 if( p->cnt++==0 ){ 00533 for(i=0; i<nArg; i++){ 00534 int w, n; 00535 if( i<ArraySize(p->colWidth) ){ 00536 w = p->colWidth[i]; 00537 }else{ 00538 w = 0; 00539 } 00540 if( w<=0 ){ 00541 w = strlen(azCol[i] ? azCol[i] : ""); 00542 if( w<10 ) w = 10; 00543 n = strlen(azArg && azArg[i] ? azArg[i] : p->nullvalue); 00544 if( w<n ) w = n; 00545 } 00546 if( i<ArraySize(p->actualWidth) ){ 00547 p->actualWidth[i] = w; 00548 } 00549 if( p->showHeader ){ 00550 fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " "); 00551 } 00552 } 00553 if( p->showHeader ){ 00554 for(i=0; i<nArg; i++){ 00555 int w; 00556 if( i<ArraySize(p->actualWidth) ){ 00557 w = p->actualWidth[i]; 00558 }else{ 00559 w = 10; 00560 } 00561 fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------" 00562 "----------------------------------------------------------", 00563 i==nArg-1 ? "\n": " "); 00564 } 00565 } 00566 } 00567 if( azArg==0 ) break; 00568 for(i=0; i<nArg; i++){ 00569 int w; 00570 if( i<ArraySize(p->actualWidth) ){ 00571 w = p->actualWidth[i]; 00572 }else{ 00573 w = 10; 00574 } 00575 if( p->mode==MODE_Explain && azArg[i] && strlen(azArg[i])>w ){ 00576 w = strlen(azArg[i]); 00577 } 00578 fprintf(p->out,"%-*.*s%s",w,w, 00579 azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " "); 00580 } 00581 break; 00582 } 00583 case MODE_Semi: 00584 case MODE_List: { 00585 if( p->cnt++==0 && p->showHeader ){ 00586 for(i=0; i<nArg; i++){ 00587 fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator); 00588 } 00589 } 00590 if( azArg==0 ) break; 00591 for(i=0; i<nArg; i++){ 00592 char *z = azArg[i]; 00593 if( z==0 ) z = p->nullvalue; 00594 fprintf(p->out, "%s", z); 00595 if( i<nArg-1 ){ 00596 fprintf(p->out, "%s", p->separator); 00597 }else if( p->mode==MODE_Semi ){ 00598 fprintf(p->out, ";\n"); 00599 }else{ 00600 fprintf(p->out, "\n"); 00601 } 00602 } 00603 break; 00604 } 00605 case MODE_Html: { 00606 if( p->cnt++==0 && p->showHeader ){ 00607 fprintf(p->out,"<TR>"); 00608 for(i=0; i<nArg; i++){ 00609 fprintf(p->out,"<TH>%s</TH>",azCol[i]); 00610 } 00611 fprintf(p->out,"</TR>\n"); 00612 } 00613 if( azArg==0 ) break; 00614 fprintf(p->out,"<TR>"); 00615 for(i=0; i<nArg; i++){ 00616 fprintf(p->out,"<TD>"); 00617 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue); 00618 fprintf(p->out,"</TD>\n"); 00619 } 00620 fprintf(p->out,"</TR>\n"); 00621 break; 00622 } 00623 case MODE_Tcl: { 00624 if( p->cnt++==0 && p->showHeader ){ 00625 for(i=0; i<nArg; i++){ 00626 output_c_string(p->out,azCol[i] ? azCol[i] : ""); 00627 fprintf(p->out, "%s", p->separator); 00628 } 00629 fprintf(p->out,"\n"); 00630 } 00631 if( azArg==0 ) break; 00632 for(i=0; i<nArg; i++){ 00633 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue); 00634 fprintf(p->out, "%s", p->separator); 00635 } 00636 fprintf(p->out,"\n"); 00637 break; 00638 } 00639 case MODE_Csv: { 00640 if( p->cnt++==0 && p->showHeader ){ 00641 for(i=0; i<nArg; i++){ 00642 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); 00643 } 00644 fprintf(p->out,"\n"); 00645 } 00646 if( azArg==0 ) break; 00647 for(i=0; i<nArg; i++){ 00648 output_csv(p, azArg[i], i<nArg-1); 00649 } 00650 fprintf(p->out,"\n"); 00651 break; 00652 } 00653 case MODE_Insert: { 00654 if( azArg==0 ) break; 00655 fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable); 00656 for(i=0; i<nArg; i++){ 00657 char *zSep = i>0 ? ",": ""; 00658 if( azArg[i]==0 ){ 00659 fprintf(p->out,"%sNULL",zSep); 00660 }else if( isNumber(azArg[i], 0) ){ 00661 fprintf(p->out,"%s%s",zSep, azArg[i]); 00662 }else{ 00663 if( zSep[0] ) fprintf(p->out,"%s",zSep); 00664 output_quoted_string(p->out, azArg[i]); 00665 } 00666 } 00667 fprintf(p->out,");\n"); 00668 break; 00669 } 00670 } 00671 return 0; 00672 } 00673 00674 /* 00675 ** Set the destination table field of the callback_data structure to 00676 ** the name of the table given. Escape any quote characters in the 00677 ** table name. 00678 */ 00679 static void set_table_name(struct callback_data *p, const char *zName){ 00680 int i, n; 00681 int needQuote; 00682 char *z; 00683 00684 if( p->zDestTable ){ 00685 free(p->zDestTable); 00686 p->zDestTable = 0; 00687 } 00688 if( zName==0 ) return; 00689 needQuote = !isalpha((unsigned char)*zName) && *zName!='_'; 00690 for(i=n=0; zName[i]; i++, n++){ 00691 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){ 00692 needQuote = 1; 00693 if( zName[i]=='\'' ) n++; 00694 } 00695 } 00696 if( needQuote ) n += 2; 00697 z = p->zDestTable = malloc( n+1 ); 00698 if( z==0 ){ 00699 fprintf(stderr,"Out of memory!\n"); 00700 exit(1); 00701 } 00702 n = 0; 00703 if( needQuote ) z[n++] = '\''; 00704 for(i=0; zName[i]; i++){ 00705 z[n++] = zName[i]; 00706 if( zName[i]=='\'' ) z[n++] = '\''; 00707 } 00708 if( needQuote ) z[n++] = '\''; 00709 z[n] = 0; 00710 } 00711 00712 /* zIn is either a pointer to a NULL-terminated string in memory obtained 00713 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is 00714 ** added to zIn, and the result returned in memory obtained from malloc(). 00715 ** zIn, if it was not NULL, is freed. 00716 ** 00717 ** If the third argument, quote, is not '\0', then it is used as a 00718 ** quote character for zAppend. 00719 */ 00720 static char *appendText(char *zIn, char const *zAppend, char quote){ 00721 int len; 00722 int i; 00723 int nAppend = strlen(zAppend); 00724 int nIn = (zIn?strlen(zIn):0); 00725 00726 len = nAppend+nIn+1; 00727 if( quote ){ 00728 len += 2; 00729 for(i=0; i<nAppend; i++){ 00730 if( zAppend[i]==quote ) len++; 00731 } 00732 } 00733 00734 zIn = (char *)realloc(zIn, len); 00735 if( !zIn ){ 00736 return 0; 00737 } 00738 00739 if( quote ){ 00740 char *zCsr = &zIn[nIn]; 00741 *zCsr++ = quote; 00742 for(i=0; i<nAppend; i++){ 00743 *zCsr++ = zAppend[i]; 00744 if( zAppend[i]==quote ) *zCsr++ = quote; 00745 } 00746 *zCsr++ = quote; 00747 *zCsr++ = '\0'; 00748 assert( (zCsr-zIn)==len ); 00749 }else{ 00750 memcpy(&zIn[nIn], zAppend, nAppend); 00751 zIn[len-1] = '\0'; 00752 } 00753 00754 return zIn; 00755 } 00756 00757 00758 /* 00759 ** Execute a query statement that has a single result column. Print 00760 ** that result column on a line by itself with a semicolon terminator. 00761 ** 00762 ** This is used, for example, to show the schema of the database by 00763 ** querying the SQLITE_MASTER table. 00764 */ 00765 static int run_table_dump_query(FILE *out, sqlite3 *db, const char *zSelect){ 00766 sqlite3_stmt *pSelect; 00767 int rc; 00768 rc = sqlite3_prepare(db, zSelect, -1, &pSelect, 0); 00769 if( rc!=SQLITE_OK || !pSelect ){ 00770 return rc; 00771 } 00772 rc = sqlite3_step(pSelect); 00773 while( rc==SQLITE_ROW ){ 00774 fprintf(out, "%s;\n", sqlite3_column_text(pSelect, 0)); 00775 rc = sqlite3_step(pSelect); 00776 } 00777 return sqlite3_finalize(pSelect); 00778 } 00779 00780 00781 /* 00782 ** This is a different callback routine used for dumping the database. 00783 ** Each row received by this callback consists of a table name, 00784 ** the table type ("index" or "table") and SQL to create the table. 00785 ** This routine should print text sufficient to recreate the table. 00786 */ 00787 static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ 00788 int rc; 00789 const char *zTable; 00790 const char *zType; 00791 const char *zSql; 00792 struct callback_data *p = (struct callback_data *)pArg; 00793 00794 if( nArg!=3 ) return 1; 00795 zTable = azArg[0]; 00796 zType = azArg[1]; 00797 zSql = azArg[2]; 00798 00799 if( strcmp(zTable, "sqlite_sequence")==0 ){ 00800 fprintf(p->out, "DELETE FROM sqlite_sequence;\n"); 00801 }else if( strcmp(zTable, "sqlite_stat1")==0 ){ 00802 fprintf(p->out, "ANALYZE sqlite_master;\n"); 00803 }else if( strncmp(zTable, "sqlite_", 7)==0 ){ 00804 return 0; 00805 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ 00806 char *zIns; 00807 if( !p->writableSchema ){ 00808 fprintf(p->out, "PRAGMA writable_schema=ON;\n"); 00809 p->writableSchema = 1; 00810 } 00811 zIns = sqlite3_mprintf( 00812 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" 00813 "VALUES('table','%q','%q',0,'%q');", 00814 zTable, zTable, zSql); 00815 fprintf(p->out, "%s\n", zIns); 00816 sqlite3_free(zIns); 00817 return 0; 00818 }else{ 00819 fprintf(p->out, "%s;\n", zSql); 00820 } 00821 00822 if( strcmp(zType, "table")==0 ){ 00823 sqlite3_stmt *pTableInfo = 0; 00824 char *zSelect = 0; 00825 char *zTableInfo = 0; 00826 char *zTmp = 0; 00827 00828 zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0); 00829 zTableInfo = appendText(zTableInfo, zTable, '"'); 00830 zTableInfo = appendText(zTableInfo, ");", 0); 00831 00832 rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0); 00833 if( zTableInfo ) free(zTableInfo); 00834 if( rc!=SQLITE_OK || !pTableInfo ){ 00835 return 1; 00836 } 00837 00838 zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0); 00839 zTmp = appendText(zTmp, zTable, '"'); 00840 if( zTmp ){ 00841 zSelect = appendText(zSelect, zTmp, '\''); 00842 } 00843 zSelect = appendText(zSelect, " || ' VALUES(' || ", 0); 00844 rc = sqlite3_step(pTableInfo); 00845 while( rc==SQLITE_ROW ){ 00846 const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1); 00847 zSelect = appendText(zSelect, "quote(", 0); 00848 zSelect = appendText(zSelect, zText, '"'); 00849 rc = sqlite3_step(pTableInfo); 00850 if( rc==SQLITE_ROW ){ 00851 zSelect = appendText(zSelect, ") || ',' || ", 0); 00852 }else{ 00853 zSelect = appendText(zSelect, ") ", 0); 00854 } 00855 } 00856 rc = sqlite3_finalize(pTableInfo); 00857 if( rc!=SQLITE_OK ){ 00858 if( zSelect ) free(zSelect); 00859 return 1; 00860 } 00861 zSelect = appendText(zSelect, "|| ')' FROM ", 0); 00862 zSelect = appendText(zSelect, zTable, '"'); 00863 00864 rc = run_table_dump_query(p->out, p->db, zSelect); 00865 if( rc==SQLITE_CORRUPT ){ 00866 zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0); 00867 rc = run_table_dump_query(p->out, p->db, zSelect); 00868 } 00869 if( zSelect ) free(zSelect); 00870 } 00871 return 0; 00872 } 00873 00874 /* 00875 ** Run zQuery. Use dump_callback() as the callback routine so that 00876 ** the contents of the query are output as SQL statements. 00877 ** 00878 ** If we get a SQLITE_CORRUPT error, rerun the query after appending 00879 ** "ORDER BY rowid DESC" to the end. 00880 */ 00881 static int run_schema_dump_query( 00882 struct callback_data *p, 00883 const char *zQuery, 00884 char **pzErrMsg 00885 ){ 00886 int rc; 00887 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, pzErrMsg); 00888 if( rc==SQLITE_CORRUPT ){ 00889 char *zQ2; 00890 int len = strlen(zQuery); 00891 if( pzErrMsg ) sqlite3_free(*pzErrMsg); 00892 zQ2 = malloc( len+100 ); 00893 if( zQ2==0 ) return rc; 00894 sqlite3_snprintf(sizeof(zQ2), zQ2, "%s ORDER BY rowid DESC", zQuery); 00895 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, pzErrMsg); 00896 free(zQ2); 00897 } 00898 return rc; 00899 } 00900 00901 /* 00902 ** Text of a help message 00903 */ 00904 static char zHelp[] = 00905 ".bail ON|OFF Stop after hitting an error. Default OFF\n" 00906 ".databases List names and files of attached databases\n" 00907 ".dump ?TABLE? ... Dump the database in an SQL text format\n" 00908 ".echo ON|OFF Turn command echo on or off\n" 00909 ".exit Exit this program\n" 00910 ".explain ON|OFF Turn output mode suitable for EXPLAIN on or off.\n" 00911 ".header(s) ON|OFF Turn display of headers on or off\n" 00912 ".help Show this message\n" 00913 ".import FILE TABLE Import data from FILE into TABLE\n" 00914 ".indices TABLE Show names of all indices on TABLE\n" 00915 #ifdef SQLITE_ENABLE_IOTRACE 00916 ".iotrace FILE Enable I/O diagnostic logging to FILE\n" 00917 #endif 00918 #ifndef SQLITE_OMIT_LOAD_EXTENSION 00919 ".load FILE ?ENTRY? Load an extension library\n" 00920 #endif 00921 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n" 00922 " csv Comma-separated values\n" 00923 " column Left-aligned columns. (See .width)\n" 00924 " html HTML <table> code\n" 00925 " insert SQL insert statements for TABLE\n" 00926 " line One value per line\n" 00927 " list Values delimited by .separator string\n" 00928 " tabs Tab-separated values\n" 00929 " tcl TCL list elements\n" 00930 ".nullvalue STRING Print STRING in place of NULL values\n" 00931 ".output FILENAME Send output to FILENAME\n" 00932 ".output stdout Send output to the screen\n" 00933 ".prompt MAIN CONTINUE Replace the standard prompts\n" 00934 ".quit Exit this program\n" 00935 ".read FILENAME Execute SQL in FILENAME\n" 00936 ".schema ?TABLE? Show the CREATE statements\n" 00937 ".separator STRING Change separator used by output mode and .import\n" 00938 ".show Show the current values for various settings\n" 00939 ".tables ?PATTERN? List names of tables matching a LIKE pattern\n" 00940 ".timeout MS Try opening locked tables for MS milliseconds\n" 00941 #if HAS_TIMER 00942 ".timer ON|OFF Turn the CPU timer measurement on or off\n" 00943 #endif 00944 ".width NUM NUM ... Set column widths for \"column\" mode\n" 00945 ; 00946 00947 /* Forward reference */ 00948 static int process_input(struct callback_data *p, FILE *in); 00949 00950 /* 00951 ** Make sure the database is open. If it is not, then open it. If 00952 ** the database fails to open, print an error message and exit. 00953 */ 00954 static void open_db(struct callback_data *p){ 00955 if( p->db==0 ){ 00956 sqlite3_open(p->zDbFilename, &p->db); 00957 db = p->db; 00958 if( db && sqlite3_errcode(db)==SQLITE_OK ){ 00959 sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0, 00960 shellstaticFunc, 0, 0); 00961 } 00962 if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){ 00963 fprintf(stderr,"Unable to open database \"%s\": %s\n", 00964 p->zDbFilename, sqlite3_errmsg(db)); 00965 exit(1); 00966 } 00967 #ifndef SQLITE_OMIT_LOAD_EXTENSION 00968 sqlite3_enable_load_extension(p->db, 1); 00969 #endif 00970 } 00971 } 00972 00973 /* 00974 ** Do C-language style dequoting. 00975 ** 00976 ** \t -> tab 00977 ** \n -> newline 00978 ** \r -> carriage return 00979 ** \NNN -> ascii character NNN in octal 00980 ** \\ -> backslash 00981 */ 00982 static void resolve_backslashes(char *z){ 00983 int i, j, c; 00984 for(i=j=0; (c = z[i])!=0; i++, j++){ 00985 if( c=='\\' ){ 00986 c = z[++i]; 00987 if( c=='n' ){ 00988 c = '\n'; 00989 }else if( c=='t' ){ 00990 c = '\t'; 00991 }else if( c=='r' ){ 00992 c = '\r'; 00993 }else if( c>='0' && c<='7' ){ 00994 c -= '0'; 00995 if( z[i+1]>='0' && z[i+1]<='7' ){ 00996 i++; 00997 c = (c<<3) + z[i] - '0'; 00998 if( z[i+1]>='0' && z[i+1]<='7' ){ 00999 i++; 01000 c = (c<<3) + z[i] - '0'; 01001 } 01002 } 01003 } 01004 } 01005 z[j] = c; 01006 } 01007 z[j] = 0; 01008 } 01009 01010 /* 01011 ** Interpret zArg as a boolean value. Return either 0 or 1. 01012 */ 01013 static int booleanValue(char *zArg){ 01014 int val = atoi(zArg); 01015 int j; 01016 for(j=0; zArg[j]; j++){ 01017 zArg[j] = tolower(zArg[j]); 01018 } 01019 if( strcmp(zArg,"on")==0 ){ 01020 val = 1; 01021 }else if( strcmp(zArg,"yes")==0 ){ 01022 val = 1; 01023 } 01024 return val; 01025 } 01026 01027 /* 01028 ** If an input line begins with "." then invoke this routine to 01029 ** process that line. 01030 ** 01031 ** Return 1 on error, 2 to exit, and 0 otherwise. 01032 */ 01033 static int do_meta_command(char *zLine, struct callback_data *p){ 01034 int i = 1; 01035 int nArg = 0; 01036 int n, c; 01037 int rc = 0; 01038 char *azArg[50]; 01039 01040 /* Parse the input line into tokens. 01041 */ 01042 while( zLine[i] && nArg<ArraySize(azArg) ){ 01043 while( isspace((unsigned char)zLine[i]) ){ i++; } 01044 if( zLine[i]==0 ) break; 01045 if( zLine[i]=='\'' || zLine[i]=='"' ){ 01046 int delim = zLine[i++]; 01047 azArg[nArg++] = &zLine[i]; 01048 while( zLine[i] && zLine[i]!=delim ){ i++; } 01049 if( zLine[i]==delim ){ 01050 zLine[i++] = 0; 01051 } 01052 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); 01053 }else{ 01054 azArg[nArg++] = &zLine[i]; 01055 while( zLine[i] && !isspace((unsigned char)zLine[i]) ){ i++; } 01056 if( zLine[i] ) zLine[i++] = 0; 01057 resolve_backslashes(azArg[nArg-1]); 01058 } 01059 } 01060 01061 /* Process the input line. 01062 */ 01063 if( nArg==0 ) return rc; 01064 n = strlen(azArg[0]); 01065 c = azArg[0][0]; 01066 if( c=='b' && n>1 && strncmp(azArg[0], "bail", n)==0 && nArg>1 ){ 01067 bail_on_error = booleanValue(azArg[1]); 01068 }else 01069 01070 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ 01071 struct callback_data data; 01072 char *zErrMsg = 0; 01073 open_db(p); 01074 memcpy(&data, p, sizeof(data)); 01075 data.showHeader = 1; 01076 data.mode = MODE_Column; 01077 data.colWidth[0] = 3; 01078 data.colWidth[1] = 15; 01079 data.colWidth[2] = 58; 01080 data.cnt = 0; 01081 sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg); 01082 if( zErrMsg ){ 01083 fprintf(stderr,"Error: %s\n", zErrMsg); 01084 sqlite3_free(zErrMsg); 01085 } 01086 }else 01087 01088 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ 01089 char *zErrMsg = 0; 01090 open_db(p); 01091 fprintf(p->out, "BEGIN TRANSACTION;\n"); 01092 p->writableSchema = 0; 01093 sqlite3_exec(p->db, "PRAGMA writable_schema=ON", 0, 0, 0); 01094 if( nArg==1 ){ 01095 run_schema_dump_query(p, 01096 "SELECT name, type, sql FROM sqlite_master " 01097 "WHERE sql NOT NULL AND type=='table'", 0 01098 ); 01099 run_table_dump_query(p->out, p->db, 01100 "SELECT sql FROM sqlite_master " 01101 "WHERE sql NOT NULL AND type IN ('index','trigger','view')" 01102 ); 01103 }else{ 01104 int i; 01105 for(i=1; i<nArg; i++){ 01106 zShellStatic = azArg[i]; 01107 run_schema_dump_query(p, 01108 "SELECT name, type, sql FROM sqlite_master " 01109 "WHERE tbl_name LIKE shellstatic() AND type=='table'" 01110 " AND sql NOT NULL", 0); 01111 run_table_dump_query(p->out, p->db, 01112 "SELECT sql FROM sqlite_master " 01113 "WHERE sql NOT NULL" 01114 " AND type IN ('index','trigger','view')" 01115 " AND tbl_name LIKE shellstatic()" 01116 ); 01117 zShellStatic = 0; 01118 } 01119 } 01120 if( p->writableSchema ){ 01121 fprintf(p->out, "PRAGMA writable_schema=OFF;\n"); 01122 p->writableSchema = 0; 01123 } 01124 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF", 0, 0, 0); 01125 if( zErrMsg ){ 01126 fprintf(stderr,"Error: %s\n", zErrMsg); 01127 sqlite3_free(zErrMsg); 01128 }else{ 01129 fprintf(p->out, "COMMIT;\n"); 01130 } 01131 }else 01132 01133 if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 ){ 01134 p->echoOn = booleanValue(azArg[1]); 01135 }else 01136 01137 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ 01138 rc = 2; 01139 }else 01140 01141 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ 01142 int val = nArg>=2 ? booleanValue(azArg[1]) : 1; 01143 if(val == 1) { 01144 if(!p->explainPrev.valid) { 01145 p->explainPrev.valid = 1; 01146 p->explainPrev.mode = p->mode; 01147 p->explainPrev.showHeader = p->showHeader; 01148 memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth)); 01149 } 01150 /* We could put this code under the !p->explainValid 01151 ** condition so that it does not execute if we are already in 01152 ** explain mode. However, always executing it allows us an easy 01153 ** was to reset to explain mode in case the user previously 01154 ** did an .explain followed by a .width, .mode or .header 01155 ** command. 01156 */ 01157 p->mode = MODE_Explain; 01158 p->showHeader = 1; 01159 memset(p->colWidth,0,ArraySize(p->colWidth)); 01160 p->colWidth[0] = 4; /* addr */ 01161 p->colWidth[1] = 13; /* opcode */ 01162 p->colWidth[2] = 4; /* P1 */ 01163 p->colWidth[3] = 4; /* P2 */ 01164 p->colWidth[4] = 4; /* P3 */ 01165 p->colWidth[5] = 13; /* P4 */ 01166 p->colWidth[6] = 2; /* P5 */ 01167 p->colWidth[7] = 13; /* Comment */ 01168 }else if (p->explainPrev.valid) { 01169 p->explainPrev.valid = 0; 01170 p->mode = p->explainPrev.mode; 01171 p->showHeader = p->explainPrev.showHeader; 01172 memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth)); 01173 } 01174 }else 01175 01176 if( c=='h' && (strncmp(azArg[0], "header", n)==0 || 01177 strncmp(azArg[0], "headers", n)==0 )&& nArg>1 ){ 01178 p->showHeader = booleanValue(azArg[1]); 01179 }else 01180 01181 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ 01182 fprintf(stderr,zHelp); 01183 }else 01184 01185 if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg>=3 ){ 01186 char *zTable = azArg[2]; /* Insert data into this table */ 01187 char *zFile = azArg[1]; /* The file from which to extract data */ 01188 sqlite3_stmt *pStmt; /* A statement */ 01189 int rc; /* Result code */ 01190 int nCol; /* Number of columns in the table */ 01191 int nByte; /* Number of bytes in an SQL string */ 01192 int i, j; /* Loop counters */ 01193 int nSep; /* Number of bytes in p->separator[] */ 01194 char *zSql; /* An SQL statement */ 01195 char *zLine; /* A single line of input from the file */ 01196 char **azCol; /* zLine[] broken up into columns */ 01197 char *zCommit; /* How to commit changes */ 01198 FILE *in; /* The input file */ 01199 int lineno = 0; /* Line number of input file */ 01200 01201 open_db(p); 01202 nSep = strlen(p->separator); 01203 if( nSep==0 ){ 01204 fprintf(stderr, "non-null separator required for import\n"); 01205 return 0; 01206 } 01207 zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable); 01208 if( zSql==0 ) return 0; 01209 nByte = strlen(zSql); 01210 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); 01211 sqlite3_free(zSql); 01212 if( rc ){ 01213 fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db)); 01214 nCol = 0; 01215 rc = 1; 01216 }else{ 01217 nCol = sqlite3_column_count(pStmt); 01218 } 01219 sqlite3_finalize(pStmt); 01220 if( nCol==0 ) return 0; 01221 zSql = malloc( nByte + 20 + nCol*2 ); 01222 if( zSql==0 ) return 0; 01223 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO '%q' VALUES(?", zTable); 01224 j = strlen(zSql); 01225 for(i=1; i<nCol; i++){ 01226 zSql[j++] = ','; 01227 zSql[j++] = '?'; 01228 } 01229 zSql[j++] = ')'; 01230 zSql[j] = 0; 01231 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); 01232 free(zSql); 01233 if( rc ){ 01234 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db)); 01235 sqlite3_finalize(pStmt); 01236 return 1; 01237 } 01238 in = fopen(zFile, "rb"); 01239 if( in==0 ){ 01240 fprintf(stderr, "cannot open file: %s\n", zFile); 01241 sqlite3_finalize(pStmt); 01242 return 0; 01243 } 01244 azCol = malloc( sizeof(azCol[0])*(nCol+1) ); 01245 if( azCol==0 ){ 01246 fclose(in); 01247 return 0; 01248 } 01249 sqlite3_exec(p->db, "BEGIN", 0, 0, 0); 01250 zCommit = "COMMIT"; 01251 while( (zLine = local_getline(0, in))!=0 ){ 01252 char *z; 01253 i = 0; 01254 lineno++; 01255 azCol[0] = zLine; 01256 for(i=0, z=zLine; *z && *z!='\n' && *z!='\r'; z++){ 01257 if( *z==p->separator[0] && strncmp(z, p->separator, nSep)==0 ){ 01258 *z = 0; 01259 i++; 01260 if( i<nCol ){ 01261 azCol[i] = &z[nSep]; 01262 z += nSep-1; 01263 } 01264 } 01265 } 01266 *z = 0; 01267 if( i+1!=nCol ){ 01268 fprintf(stderr,"%s line %d: expected %d columns of data but found %d\n", 01269 zFile, lineno, nCol, i+1); 01270 zCommit = "ROLLBACK"; 01271 break; 01272 } 01273 for(i=0; i<nCol; i++){ 01274 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC); 01275 } 01276 sqlite3_step(pStmt); 01277 rc = sqlite3_reset(pStmt); 01278 free(zLine); 01279 if( rc!=SQLITE_OK ){ 01280 fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db)); 01281 zCommit = "ROLLBACK"; 01282 rc = 1; 01283 break; 01284 } 01285 } 01286 free(azCol); 01287 fclose(in); 01288 sqlite3_finalize(pStmt); 01289 sqlite3_exec(p->db, zCommit, 0, 0, 0); 01290 }else 01291 01292 if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg>1 ){ 01293 struct callback_data data; 01294 char *zErrMsg = 0; 01295 open_db(p); 01296 memcpy(&data, p, sizeof(data)); 01297 data.showHeader = 0; 01298 data.mode = MODE_List; 01299 zShellStatic = azArg[1]; 01300 sqlite3_exec(p->db, 01301 "SELECT name FROM sqlite_master " 01302 "WHERE type='index' AND tbl_name LIKE shellstatic() " 01303 "UNION ALL " 01304 "SELECT name FROM sqlite_temp_master " 01305 "WHERE type='index' AND tbl_name LIKE shellstatic() " 01306 "ORDER BY 1", 01307 callback, &data, &zErrMsg 01308 ); 01309 zShellStatic = 0; 01310 if( zErrMsg ){ 01311 fprintf(stderr,"Error: %s\n", zErrMsg); 01312 sqlite3_free(zErrMsg); 01313 } 01314 }else 01315 01316 #ifdef SQLITE_ENABLE_IOTRACE 01317 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ 01318 extern void (*sqlite3IoTrace)(const char*, ...); 01319 if( iotrace && iotrace!=stdout ) fclose(iotrace); 01320 iotrace = 0; 01321 if( nArg<2 ){ 01322 sqlite3IoTrace = 0; 01323 }else if( strcmp(azArg[1], "-")==0 ){ 01324 sqlite3IoTrace = iotracePrintf; 01325 iotrace = stdout; 01326 }else{ 01327 iotrace = fopen(azArg[1], "w"); 01328 if( iotrace==0 ){ 01329 fprintf(stderr, "cannot open \"%s\"\n", azArg[1]); 01330 sqlite3IoTrace = 0; 01331 }else{ 01332 sqlite3IoTrace = iotracePrintf; 01333 } 01334 } 01335 }else 01336 #endif 01337 01338 #ifndef SQLITE_OMIT_LOAD_EXTENSION 01339 if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){ 01340 const char *zFile, *zProc; 01341 char *zErrMsg = 0; 01342 int rc; 01343 zFile = azArg[1]; 01344 zProc = nArg>=3 ? azArg[2] : 0; 01345 open_db(p); 01346 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); 01347 if( rc!=SQLITE_OK ){ 01348 fprintf(stderr, "%s\n", zErrMsg); 01349 sqlite3_free(zErrMsg); 01350 rc = 1; 01351 } 01352 }else 01353 #endif 01354 01355 if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg>=2 ){ 01356 int n2 = strlen(azArg[1]); 01357 if( strncmp(azArg[1],"line",n2)==0 01358 || 01359 strncmp(azArg[1],"lines",n2)==0 ){ 01360 p->mode = MODE_Line; 01361 }else if( strncmp(azArg[1],"column",n2)==0 01362 || 01363 strncmp(azArg[1],"columns",n2)==0 ){ 01364 p->mode = MODE_Column; 01365 }else if( strncmp(azArg[1],"list",n2)==0 ){ 01366 p->mode = MODE_List; 01367 }else if( strncmp(azArg[1],"html",n2)==0 ){ 01368 p->mode = MODE_Html; 01369 }else if( strncmp(azArg[1],"tcl",n2)==0 ){ 01370 p->mode = MODE_Tcl; 01371 }else if( strncmp(azArg[1],"csv",n2)==0 ){ 01372 p->mode = MODE_Csv; 01373 sqlite3_snprintf(sizeof(p->separator), p->separator, ","); 01374 }else if( strncmp(azArg[1],"tabs",n2)==0 ){ 01375 p->mode = MODE_List; 01376 sqlite3_snprintf(sizeof(p->separator), p->separator, "\t"); 01377 }else if( strncmp(azArg[1],"insert",n2)==0 ){ 01378 p->mode = MODE_Insert; 01379 if( nArg>=3 ){ 01380 set_table_name(p, azArg[2]); 01381 }else{ 01382 set_table_name(p, "table"); 01383 } 01384 }else { 01385 fprintf(stderr,"mode should be one of: " 01386 "column csv html insert line list tabs tcl\n"); 01387 } 01388 }else 01389 01390 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) { 01391 sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue, 01392 "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]); 01393 }else 01394 01395 if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){ 01396 if( p->out!=stdout ){ 01397 fclose(p->out); 01398 } 01399 if( strcmp(azArg[1],"stdout")==0 ){ 01400 p->out = stdout; 01401 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "stdout"); 01402 }else{ 01403 p->out = fopen(azArg[1], "wb"); 01404 if( p->out==0 ){ 01405 fprintf(stderr,"can't write to \"%s\"\n", azArg[1]); 01406 p->out = stdout; 01407 } else { 01408 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]); 01409 } 01410 } 01411 }else 01412 01413 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){ 01414 if( nArg >= 2) { 01415 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); 01416 } 01417 if( nArg >= 3) { 01418 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); 01419 } 01420 }else 01421 01422 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ 01423 rc = 2; 01424 }else 01425 01426 if( c=='r' && strncmp(azArg[0], "read", n)==0 && nArg==2 ){ 01427 FILE *alt = fopen(azArg[1], "rb"); 01428 if( alt==0 ){ 01429 fprintf(stderr,"can't open \"%s\"\n", azArg[1]); 01430 }else{ 01431 process_input(p, alt); 01432 fclose(alt); 01433 } 01434 }else 01435 01436 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ 01437 struct callback_data data; 01438 char *zErrMsg = 0; 01439 open_db(p); 01440 memcpy(&data, p, sizeof(data)); 01441 data.showHeader = 0; 01442 data.mode = MODE_Semi; 01443 if( nArg>1 ){ 01444 int i; 01445 for(i=0; azArg[1][i]; i++) azArg[1][i] = tolower(azArg[1][i]); 01446 if( strcmp(azArg[1],"sqlite_master")==0 ){ 01447 char *new_argv[2], *new_colv[2]; 01448 new_argv[0] = "CREATE TABLE sqlite_master (\n" 01449 " type text,\n" 01450 " name text,\n" 01451 " tbl_name text,\n" 01452 " rootpage integer,\n" 01453 " sql text\n" 01454 ")"; 01455 new_argv[1] = 0; 01456 new_colv[0] = "sql"; 01457 new_colv[1] = 0; 01458 callback(&data, 1, new_argv, new_colv); 01459 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){ 01460 char *new_argv[2], *new_colv[2]; 01461 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n" 01462 " type text,\n" 01463 " name text,\n" 01464 " tbl_name text,\n" 01465 " rootpage integer,\n" 01466 " sql text\n" 01467 ")"; 01468 new_argv[1] = 0; 01469 new_colv[0] = "sql"; 01470 new_colv[1] = 0; 01471 callback(&data, 1, new_argv, new_colv); 01472 }else{ 01473 zShellStatic = azArg[1]; 01474 sqlite3_exec(p->db, 01475 "SELECT sql FROM " 01476 " (SELECT * FROM sqlite_master UNION ALL" 01477 " SELECT * FROM sqlite_temp_master) " 01478 "WHERE tbl_name LIKE shellstatic() AND type!='meta' AND sql NOTNULL " 01479 "ORDER BY substr(type,2,1), name", 01480 callback, &data, &zErrMsg); 01481 zShellStatic = 0; 01482 } 01483 }else{ 01484 sqlite3_exec(p->db, 01485 "SELECT sql FROM " 01486 " (SELECT * FROM sqlite_master UNION ALL" 01487 " SELECT * FROM sqlite_temp_master) " 01488 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'" 01489 "ORDER BY substr(type,2,1), name", 01490 callback, &data, &zErrMsg 01491 ); 01492 } 01493 if( zErrMsg ){ 01494 fprintf(stderr,"Error: %s\n", zErrMsg); 01495 sqlite3_free(zErrMsg); 01496 } 01497 }else 01498 01499 if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){ 01500 sqlite3_snprintf(sizeof(p->separator), p->separator, 01501 "%.*s", (int)sizeof(p->separator)-1, azArg[1]); 01502 }else 01503 01504 if( c=='s' && strncmp(azArg[0], "show", n)==0){ 01505 int i; 01506 fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off"); 01507 fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off"); 01508 fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off"); 01509 fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]); 01510 fprintf(p->out,"%9.9s: ", "nullvalue"); 01511 output_c_string(p->out, p->nullvalue); 01512 fprintf(p->out, "\n"); 01513 fprintf(p->out,"%9.9s: %s\n","output", 01514 strlen(p->outfile) ? p->outfile : "stdout"); 01515 fprintf(p->out,"%9.9s: ", "separator"); 01516 output_c_string(p->out, p->separator); 01517 fprintf(p->out, "\n"); 01518 fprintf(p->out,"%9.9s: ","width"); 01519 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { 01520 fprintf(p->out,"%d ",p->colWidth[i]); 01521 } 01522 fprintf(p->out,"\n"); 01523 }else 01524 01525 if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){ 01526 char **azResult; 01527 int nRow, rc; 01528 char *zErrMsg; 01529 open_db(p); 01530 if( nArg==1 ){ 01531 rc = sqlite3_get_table(p->db, 01532 "SELECT name FROM sqlite_master " 01533 "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'" 01534 "UNION ALL " 01535 "SELECT name FROM sqlite_temp_master " 01536 "WHERE type IN ('table','view') " 01537 "ORDER BY 1", 01538 &azResult, &nRow, 0, &zErrMsg 01539 ); 01540 }else{ 01541 zShellStatic = azArg[1]; 01542 rc = sqlite3_get_table(p->db, 01543 "SELECT name FROM sqlite_master " 01544 "WHERE type IN ('table','view') AND name LIKE '%'||shellstatic()||'%' " 01545 "UNION ALL " 01546 "SELECT name FROM sqlite_temp_master " 01547 "WHERE type IN ('table','view') AND name LIKE '%'||shellstatic()||'%' " 01548 "ORDER BY 1", 01549 &azResult, &nRow, 0, &zErrMsg 01550 ); 01551 zShellStatic = 0; 01552 } 01553 if( zErrMsg ){ 01554 fprintf(stderr,"Error: %s\n", zErrMsg); 01555 sqlite3_free(zErrMsg); 01556 } 01557 if( rc==SQLITE_OK ){ 01558 int len, maxlen = 0; 01559 int i, j; 01560 int nPrintCol, nPrintRow; 01561 for(i=1; i<=nRow; i++){ 01562 if( azResult[i]==0 ) continue; 01563 len = strlen(azResult[i]); 01564 if( len>maxlen ) maxlen = len; 01565 } 01566 nPrintCol = 80/(maxlen+2); 01567 if( nPrintCol<1 ) nPrintCol = 1; 01568 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; 01569 for(i=0; i<nPrintRow; i++){ 01570 for(j=i+1; j<=nRow; j+=nPrintRow){ 01571 char *zSp = j<=nPrintRow ? "" : " "; 01572 printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : ""); 01573 } 01574 printf("\n"); 01575 } 01576 }else{ 01577 rc = 1; 01578 } 01579 sqlite3_free_table(azResult); 01580 }else 01581 01582 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg>=2 ){ 01583 open_db(p); 01584 sqlite3_busy_timeout(p->db, atoi(azArg[1])); 01585 }else 01586 01587 #if HAS_TIMER 01588 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 && nArg>1 ){ 01589 enableTimer = booleanValue(azArg[1]); 01590 }else 01591 #endif 01592 01593 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ 01594 int j; 01595 assert( nArg<=ArraySize(azArg) ); 01596 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){ 01597 p->colWidth[j-1] = atoi(azArg[j]); 01598 } 01599 }else 01600 01601 01602 { 01603 fprintf(stderr, "unknown command or invalid arguments: " 01604 " \"%s\". Enter \".help\" for help\n", azArg[0]); 01605 } 01606 01607 return rc; 01608 } 01609 01610 /* 01611 ** Return TRUE if a semicolon occurs anywhere in the first N characters 01612 ** of string z[]. 01613 */ 01614 static int _contains_semicolon(const char *z, int N){ 01615 int i; 01616 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; } 01617 return 0; 01618 } 01619 01620 /* 01621 ** Test to see if a line consists entirely of whitespace. 01622 */ 01623 static int _all_whitespace(const char *z){ 01624 for(; *z; z++){ 01625 if( isspace(*(unsigned char*)z) ) continue; 01626 if( *z=='/' && z[1]=='*' ){ 01627 z += 2; 01628 while( *z && (*z!='*' || z[1]!='/') ){ z++; } 01629 if( *z==0 ) return 0; 01630 z++; 01631 continue; 01632 } 01633 if( *z=='-' && z[1]=='-' ){ 01634 z += 2; 01635 while( *z && *z!='\n' ){ z++; } 01636 if( *z==0 ) return 1; 01637 continue; 01638 } 01639 return 0; 01640 } 01641 return 1; 01642 } 01643 01644 /* 01645 ** Return TRUE if the line typed in is an SQL command terminator other 01646 ** than a semi-colon. The SQL Server style "go" command is understood 01647 ** as is the Oracle "/". 01648 */ 01649 static int _is_command_terminator(const char *zLine){ 01650 while( isspace(*(unsigned char*)zLine) ){ zLine++; }; 01651 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ) return 1; /* Oracle */ 01652 if( tolower(zLine[0])=='g' && tolower(zLine[1])=='o' 01653 && _all_whitespace(&zLine[2]) ){ 01654 return 1; /* SQL Server */ 01655 } 01656 return 0; 01657 } 01658 01659 /* 01660 ** Read input from *in and process it. If *in==0 then input 01661 ** is interactive - the user is typing it it. Otherwise, input 01662 ** is coming from a file or device. A prompt is issued and history 01663 ** is saved only if input is interactive. An interrupt signal will 01664 ** cause this routine to exit immediately, unless input is interactive. 01665 ** 01666 ** Return the number of errors. 01667 */ 01668 static int process_input(struct callback_data *p, FILE *in){ 01669 char *zLine = 0; 01670 char *zSql = 0; 01671 int nSql = 0; 01672 int nSqlPrior = 0; 01673 char *zErrMsg; 01674 int rc; 01675 int errCnt = 0; 01676 int lineno = 0; 01677 int startline = 0; 01678 01679 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){ 01680 fflush(p->out); 01681 free(zLine); 01682 zLine = one_input_line(zSql, in); 01683 if( zLine==0 ){ 01684 break; /* We have reached EOF */ 01685 } 01686 if( seenInterrupt ){ 01687 if( in!=0 ) break; 01688 seenInterrupt = 0; 01689 } 01690 lineno++; 01691 if( p->echoOn ) printf("%s\n", zLine); 01692 if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue; 01693 if( zLine && zLine[0]=='.' && nSql==0 ){ 01694 rc = do_meta_command(zLine, p); 01695 if( rc==2 ){ 01696 break; 01697 }else if( rc ){ 01698 errCnt++; 01699 } 01700 continue; 01701 } 01702 if( _is_command_terminator(zLine) && sqlite3_complete(zSql) ){ 01703 memcpy(zLine,";",2); 01704 } 01705 nSqlPrior = nSql; 01706 if( zSql==0 ){ 01707 int i; 01708 for(i=0; zLine[i] && isspace((unsigned char)zLine[i]); i++){} 01709 if( zLine[i]!=0 ){ 01710 nSql = strlen(zLine); 01711 zSql = malloc( nSql+1 ); 01712 if( zSql==0 ){ 01713 fprintf(stderr, "out of memory\n"); 01714 exit(1); 01715 } 01716 memcpy(zSql, zLine, nSql+1); 01717 startline = lineno; 01718 } 01719 }else{ 01720 int len = strlen(zLine); 01721 zSql = realloc( zSql, nSql + len + 2 ); 01722 if( zSql==0 ){ 01723 fprintf(stderr,"%s: out of memory!\n", Argv0); 01724 exit(1); 01725 } 01726 zSql[nSql++] = '\n'; 01727 memcpy(&zSql[nSql], zLine, len+1); 01728 nSql += len; 01729 } 01730 if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) 01731 && sqlite3_complete(zSql) ){ 01732 p->cnt = 0; 01733 open_db(p); 01734 BEGIN_TIMER; 01735 rc = sqlite3_exec(p->db, zSql, callback, p, &zErrMsg); 01736 END_TIMER; 01737 if( rc || zErrMsg ){ 01738 char zPrefix[100]; 01739 if( in!=0 || !stdin_is_interactive ){ 01740 sqlite3_snprintf(sizeof(zPrefix), zPrefix, 01741 "SQL error near line %d:", startline); 01742 }else{ 01743 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "SQL error:"); 01744 } 01745 if( zErrMsg!=0 ){ 01746 printf("%s %s\n", zPrefix, zErrMsg); 01747 sqlite3_free(zErrMsg); 01748 zErrMsg = 0; 01749 }else{ 01750 printf("%s %s\n", zPrefix, sqlite3_errmsg(p->db)); 01751 } 01752 errCnt++; 01753 } 01754 free(zSql); 01755 zSql = 0; 01756 nSql = 0; 01757 } 01758 } 01759 if( zSql ){ 01760 if( !_all_whitespace(zSql) ) fprintf(stderr, "Incomplete SQL: %s\n", zSql); 01761 free(zSql); 01762 } 01763 free(zLine); 01764 return errCnt; 01765 } 01766 01767 /* 01768 ** Return a pathname which is the user's home directory. A 01769 ** 0 return indicates an error of some kind. Space to hold the 01770 ** resulting string is obtained from malloc(). The calling 01771 ** function should free the result. 01772 */ 01773 static char *find_home_dir(void){ 01774 char *home_dir = NULL; 01775 01776 #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(_WIN32_WCE) 01777 struct passwd *pwent; 01778 uid_t uid = getuid(); 01779 if( (pwent=getpwuid(uid)) != NULL) { 01780 home_dir = pwent->pw_dir; 01781 } 01782 #endif 01783 01784 #if defined(_WIN32_WCE) 01785 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() 01786 */ 01787 home_dir = strdup("/"); 01788 #else 01789 01790 #if defined(_WIN32) || defined(WIN32) || defined(__OS2__) 01791 if (!home_dir) { 01792 home_dir = getenv("USERPROFILE"); 01793 } 01794 #endif 01795 01796 if (!home_dir) { 01797 home_dir = getenv("HOME"); 01798 } 01799 01800 #if defined(_WIN32) || defined(WIN32) || defined(__OS2__) 01801 if (!home_dir) { 01802 char *zDrive, *zPath; 01803 int n; 01804 zDrive = getenv("HOMEDRIVE"); 01805 zPath = getenv("HOMEPATH"); 01806 if( zDrive && zPath ){ 01807 n = strlen(zDrive) + strlen(zPath) + 1; 01808 home_dir = malloc( n ); 01809 if( home_dir==0 ) return 0; 01810 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); 01811 return home_dir; 01812 } 01813 home_dir = "c:\\"; 01814 } 01815 #endif 01816 01817 #endif /* !_WIN32_WCE */ 01818 01819 if( home_dir ){ 01820 int n = strlen(home_dir) + 1; 01821 char *z = malloc( n ); 01822 if( z ) memcpy(z, home_dir, n); 01823 home_dir = z; 01824 } 01825 01826 return home_dir; 01827 } 01828 01829 /* 01830 ** Read input from the file given by sqliterc_override. Or if that 01831 ** parameter is NULL, take input from ~/.sqliterc 01832 */ 01833 static void process_sqliterc( 01834 struct callback_data *p, /* Configuration data */ 01835 const char *sqliterc_override /* Name of config file. NULL to use default */ 01836 ){ 01837 char *home_dir = NULL; 01838 const char *sqliterc = sqliterc_override; 01839 char *zBuf = 0; 01840 FILE *in = NULL; 01841 int nBuf; 01842 01843 if (sqliterc == NULL) { 01844 home_dir = find_home_dir(); 01845 if( home_dir==0 ){ 01846 fprintf(stderr,"%s: cannot locate your home directory!\n", Argv0); 01847 return; 01848 } 01849 nBuf = strlen(home_dir) + 16; 01850 zBuf = malloc( nBuf ); 01851 if( zBuf==0 ){ 01852 fprintf(stderr,"%s: out of memory!\n", Argv0); 01853 exit(1); 01854 } 01855 sqlite3_snprintf(nBuf, zBuf,"%s/.sqliterc",home_dir); 01856 free(home_dir); 01857 sqliterc = (const char*)zBuf; 01858 } 01859 in = fopen(sqliterc,"rb"); 01860 if( in ){ 01861 if( stdin_is_interactive ){ 01862 printf("-- Loading resources from %s\n",sqliterc); 01863 } 01864 process_input(p,in); 01865 fclose(in); 01866 } 01867 free(zBuf); 01868 return; 01869 } 01870 01871 /* 01872 ** Show available command line options 01873 */ 01874 static const char zOptions[] = 01875 " -init filename read/process named file\n" 01876 " -echo print commands before execution\n" 01877 " -[no]header turn headers on or off\n" 01878 " -bail stop after hitting an error\n" 01879 " -interactive force interactive I/O\n" 01880 " -batch force batch I/O\n" 01881 " -column set output mode to 'column'\n" 01882 " -csv set output mode to 'csv'\n" 01883 " -html set output mode to HTML\n" 01884 " -line set output mode to 'line'\n" 01885 " -list set output mode to 'list'\n" 01886 " -separator 'x' set output field separator (|)\n" 01887 " -nullvalue 'text' set text string for NULL values\n" 01888 " -version show SQLite version\n" 01889 ; 01890 static void usage(int showDetail){ 01891 fprintf(stderr, 01892 "Usage: %s [OPTIONS] FILENAME [SQL]\n" 01893 "FILENAME is the name of an SQLite database. A new database is created\n" 01894 "if the file does not previously exist.\n", Argv0); 01895 if( showDetail ){ 01896 fprintf(stderr, "OPTIONS include:\n%s", zOptions); 01897 }else{ 01898 fprintf(stderr, "Use the -help option for additional information\n"); 01899 } 01900 exit(1); 01901 } 01902 01903 /* 01904 ** Initialize the state information in data 01905 */ 01906 static void main_init(struct callback_data *data) { 01907 memset(data, 0, sizeof(*data)); 01908 data->mode = MODE_List; 01909 memcpy(data->separator,"|", 2); 01910 data->showHeader = 0; 01911 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); 01912 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); 01913 } 01914 01915 int main(int argc, char **argv){ 01916 char *zErrMsg = 0; 01917 struct callback_data data; 01918 const char *zInitFile = 0; 01919 char *zFirstCmd = 0; 01920 int i; 01921 int rc = 0; 01922 01923 Argv0 = argv[0]; 01924 main_init(&data); 01925 stdin_is_interactive = isatty(0); 01926 01927 /* Make sure we have a valid signal handler early, before anything 01928 ** else is done. 01929 */ 01930 #ifdef SIGINT 01931 signal(SIGINT, interrupt_handler); 01932 #endif 01933 01934 /* Do an initial pass through the command-line argument to locate 01935 ** the name of the database file, the name of the initialization file, 01936 ** and the first command to execute. 01937 */ 01938 for(i=1; i<argc-1; i++){ 01939 char *z; 01940 if( argv[i][0]!='-' ) break; 01941 z = argv[i]; 01942 if( z[0]=='-' && z[1]=='-' ) z++; 01943 if( strcmp(argv[i],"-separator")==0 || strcmp(argv[i],"-nullvalue")==0 ){ 01944 i++; 01945 }else if( strcmp(argv[i],"-init")==0 ){ 01946 i++; 01947 zInitFile = argv[i]; 01948 } 01949 } 01950 if( i<argc ){ 01951 #if defined(SQLITE_OS_OS2) && SQLITE_OS_OS2 01952 data.zDbFilename = (const char *)convertCpPathToUtf8( argv[i++] ); 01953 #else 01954 data.zDbFilename = argv[i++]; 01955 #endif 01956 }else{ 01957 #ifndef SQLITE_OMIT_MEMORYDB 01958 data.zDbFilename = ":memory:"; 01959 #else 01960 data.zDbFilename = 0; 01961 #endif 01962 } 01963 if( i<argc ){ 01964 zFirstCmd = argv[i++]; 01965 } 01966 data.out = stdout; 01967 01968 #ifdef SQLITE_OMIT_MEMORYDB 01969 if( data.zDbFilename==0 ){ 01970 fprintf(stderr,"%s: no database filename specified\n", argv[0]); 01971 exit(1); 01972 } 01973 #endif 01974 01975 /* Go ahead and open the database file if it already exists. If the 01976 ** file does not exist, delay opening it. This prevents empty database 01977 ** files from being created if a user mistypes the database name argument 01978 ** to the sqlite command-line tool. 01979 */ 01980 if( access(data.zDbFilename, 0)==0 ){ 01981 open_db(&data); 01982 } 01983 01984 /* Process the initialization file if there is one. If no -init option 01985 ** is given on the command line, look for a file named ~/.sqliterc and 01986 ** try to process it. 01987 */ 01988 process_sqliterc(&data,zInitFile); 01989 01990 /* Make a second pass through the command-line argument and set 01991 ** options. This second pass is delayed until after the initialization 01992 ** file is processed so that the command-line arguments will override 01993 ** settings in the initialization file. 01994 */ 01995 for(i=1; i<argc && argv[i][0]=='-'; i++){ 01996 char *z = argv[i]; 01997 if( z[1]=='-' ){ z++; } 01998 if( strcmp(z,"-init")==0 ){ 01999 i++; 02000 }else if( strcmp(z,"-html")==0 ){ 02001 data.mode = MODE_Html; 02002 }else if( strcmp(z,"-list")==0 ){ 02003 data.mode = MODE_List; 02004 }else if( strcmp(z,"-line")==0 ){ 02005 data.mode = MODE_Line; 02006 }else if( strcmp(z,"-column")==0 ){ 02007 data.mode = MODE_Column; 02008 }else if( strcmp(z,"-csv")==0 ){ 02009 data.mode = MODE_Csv; 02010 memcpy(data.separator,",",2); 02011 }else if( strcmp(z,"-separator")==0 ){ 02012 i++; 02013 sqlite3_snprintf(sizeof(data.separator), data.separator, 02014 "%.*s",(int)sizeof(data.separator)-1,argv[i]); 02015 }else if( strcmp(z,"-nullvalue")==0 ){ 02016 i++; 02017 sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue, 02018 "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]); 02019 }else if( strcmp(z,"-header")==0 ){ 02020 data.showHeader = 1; 02021 }else if( strcmp(z,"-noheader")==0 ){ 02022 data.showHeader = 0; 02023 }else if( strcmp(z,"-echo")==0 ){ 02024 data.echoOn = 1; 02025 }else if( strcmp(z,"-bail")==0 ){ 02026 bail_on_error = 1; 02027 }else if( strcmp(z,"-version")==0 ){ 02028 printf("%s\n", sqlite3_libversion()); 02029 return 0; 02030 }else if( strcmp(z,"-interactive")==0 ){ 02031 stdin_is_interactive = 1; 02032 }else if( strcmp(z,"-batch")==0 ){ 02033 stdin_is_interactive = 0; 02034 }else if( strcmp(z,"-help")==0 || strcmp(z, "--help")==0 ){ 02035 usage(1); 02036 }else{ 02037 fprintf(stderr,"%s: unknown option: %s\n", Argv0, z); 02038 fprintf(stderr,"Use -help for a list of options.\n"); 02039 return 1; 02040 } 02041 } 02042 02043 if( zFirstCmd ){ 02044 /* Run just the command that follows the database name 02045 */ 02046 if( zFirstCmd[0]=='.' ){ 02047 do_meta_command(zFirstCmd, &data); 02048 exit(0); 02049 }else{ 02050 int rc; 02051 open_db(&data); 02052 rc = sqlite3_exec(data.db, zFirstCmd, callback, &data, &zErrMsg); 02053 if( rc!=0 && zErrMsg!=0 ){ 02054 fprintf(stderr,"SQL error: %s\n", zErrMsg); 02055 exit(1); 02056 } 02057 } 02058 }else{ 02059 /* Run commands received from standard input 02060 */ 02061 if( stdin_is_interactive ){ 02062 char *zHome; 02063 char *zHistory = 0; 02064 int nHistory; 02065 printf( 02066 "SQLite version %s\n" 02067 "Enter \".help\" for instructions\n" 02068 "Enter SQL statements terminated with a \";\"\n", 02069 sqlite3_libversion() 02070 ); 02071 zHome = find_home_dir(); 02072 if( zHome && (zHistory = malloc(nHistory = strlen(zHome)+20))!=0 ){ 02073 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); 02074 } 02075 #if defined(HAVE_READLINE) && HAVE_READLINE==1 02076 if( zHistory ) read_history(zHistory); 02077 #endif 02078 rc = process_input(&data, 0); 02079 if( zHistory ){ 02080 stifle_history(100); 02081 write_history(zHistory); 02082 free(zHistory); 02083 } 02084 free(zHome); 02085 }else{ 02086 rc = process_input(&data, stdin); 02087 } 02088 } 02089 set_table_name(&data, 0); 02090 if( db ){ 02091 if( sqlite3_close(db)!=SQLITE_OK ){ 02092 fprintf(stderr,"error closing database: %s\n", sqlite3_errmsg(db)); 02093 } 02094 } 02095 return rc; 02096 }
ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:56 2011 by Doxygen 1.6.1