[BACK]Return to shell.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / sqlite3

Annotation of src/usr.bin/sqlite3/shell.c, Revision 1.1.1.4

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