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