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