shell.c
Go to the documentation of this file.
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 ** If requested, include the SQLite compiler options file for MSVC.
22 */
23 #if defined(INCLUDE_MSVC_H)
24 #include "msvc.h"
25 #endif
26 
27 /*
28 ** No support for loadable extensions in VxWorks.
29 */
30 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
31 # define SQLITE_OMIT_LOAD_EXTENSION 1
32 #endif
33 
34 /*
35 ** Enable large-file support for fopen() and friends on unix.
36 */
37 #ifndef SQLITE_DISABLE_LFS
38 # define _LARGE_FILE 1
39 # ifndef _FILE_OFFSET_BITS
40 # define _FILE_OFFSET_BITS 64
41 # endif
42 # define _LARGEFILE_SOURCE 1
43 #endif
44 
45 #include <stdlib.h>
46 #include <string.h>
47 #include <stdio.h>
48 #include <assert.h>
49 #include "sqlite3.h"
50 #if SQLITE_USER_AUTHENTICATION
51 # include "sqlite3userauth.h"
52 #endif
53 #include <ctype.h>
54 #include <stdarg.h>
55 
56 #if !defined(_WIN32) && !defined(WIN32)
57 # include <signal.h>
58 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
59 # include <pwd.h>
60 # endif
61 # include <unistd.h>
62 # include <sys/types.h>
63 #endif
64 
65 #if HAVE_READLINE
66 # include <readline/readline.h>
67 # include <readline/history.h>
68 #endif
69 
70 #if HAVE_EDITLINE
71 # include <editline/readline.h>
72 #endif
73 
74 #if HAVE_EDITLINE || HAVE_READLINE
75 
76 # define shell_add_history(X) add_history(X)
77 # define shell_read_history(X) read_history(X)
78 # define shell_write_history(X) write_history(X)
79 # define shell_stifle_history(X) stifle_history(X)
80 # define shell_readline(X) readline(X)
81 
82 #elif HAVE_LINENOISE
83 
84 # include "linenoise.h"
85 # define shell_add_history(X) linenoiseHistoryAdd(X)
86 # define shell_read_history(X) linenoiseHistoryLoad(X)
87 # define shell_write_history(X) linenoiseHistorySave(X)
88 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
89 # define shell_readline(X) linenoise(X)
90 
91 #else
92 
93 # define shell_read_history(X)
94 # define shell_write_history(X)
95 # define shell_stifle_history(X)
96 
97 # define SHELL_USE_LOCAL_GETLINE 1
98 #endif
99 
100 
101 #if defined(_WIN32) || defined(WIN32)
102 # include <io.h>
103 # include <fcntl.h>
104 # define isatty(h) _isatty(h)
105 # ifndef access
106 # define access(f,m) _access((f),(m))
107 # endif
108 # undef popen
109 # define popen _popen
110 # undef pclose
111 # define pclose _pclose
112 #else
113  /* Make sure isatty() has a prototype. */
114  extern int isatty(int);
115 
116 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
117  /* popen and pclose are not C89 functions and so are
118  ** sometimes omitted from the <stdio.h> header */
119  extern FILE *popen(const char*,const char*);
120  extern int pclose(FILE*);
121 # else
122 # define SQLITE_OMIT_POPEN 1
123 # endif
124 #endif
125 
126 #if defined(_WIN32_WCE)
127 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
128  * thus we always assume that we have a console. That can be
129  * overridden with the -batch command line option.
130  */
131 #define isatty(x) 1
132 #endif
133 
134 /* ctype macros that work with signed characters */
135 #define IsSpace(X) isspace((unsigned char)X)
136 #define IsDigit(X) isdigit((unsigned char)X)
137 #define ToLower(X) (char)tolower((unsigned char)X)
138 
139 #if defined(_WIN32) || defined(WIN32)
140 #include <windows.h>
141 
142 /* string conversion routines only needed on Win32 */
143 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
144 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
145 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
146 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
147 #endif
148 
149 /* On Windows, we normally run with output mode of TEXT so that \n characters
150 ** are automatically translated into \r\n. However, this behavior needs
151 ** to be disabled in some cases (ex: when generating CSV output and when
152 ** rendering quoted strings that contain \n characters). The following
153 ** routines take care of that.
154 */
155 #if defined(_WIN32) || defined(WIN32)
156 static void setBinaryMode(FILE *file, int isOutput){
157  if( isOutput ) fflush(file);
158  _setmode(_fileno(file), _O_BINARY);
159 }
160 static void setTextMode(FILE *file, int isOutput){
161  if( isOutput ) fflush(file);
162  _setmode(_fileno(file), _O_TEXT);
163 }
164 #else
165 # define setBinaryMode(X,Y)
166 # define setTextMode(X,Y)
167 #endif
168 
169 
170 /* True if the timer is enabled */
171 static int enableTimer = 0;
172 
173 /* Return the current wall-clock time */
175  static sqlite3_vfs *clockVfs = 0;
176  sqlite3_int64 t;
177  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
178  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
179  clockVfs->xCurrentTimeInt64(clockVfs, &t);
180  }else{
181  double r;
182  clockVfs->xCurrentTime(clockVfs, &r);
183  t = (sqlite3_int64)(r*86400000.0);
184  }
185  return t;
186 }
187 
188 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
189 #include <sys/time.h>
190 #include <sys/resource.h>
191 
192 /* VxWorks does not support getrusage() as far as we can determine */
193 #if defined(_WRS_KERNEL) || defined(__RTP__)
194 struct rusage {
195  struct timeval ru_utime; /* user CPU time used */
196  struct timeval ru_stime; /* system CPU time used */
197 };
198 #define getrusage(A,B) memset(B,0,sizeof(*B))
199 #endif
200 
201 /* Saved resource information for the beginning of an operation */
202 static struct rusage sBegin; /* CPU time at start */
203 static sqlite3_int64 iBegin; /* Wall-clock time at start */
204 
205 /*
206 ** Begin timing an operation
207 */
208 static void beginTimer(void){
209  if( enableTimer ){
210  getrusage(RUSAGE_SELF, &sBegin);
211  iBegin = timeOfDay();
212  }
213 }
214 
215 /* Return the difference of two time_structs in seconds */
216 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
217  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
218  (double)(pEnd->tv_sec - pStart->tv_sec);
219 }
220 
221 /*
222 ** Print the timing results.
223 */
224 static void endTimer(void){
225  if( enableTimer ){
226  sqlite3_int64 iEnd = timeOfDay();
227  struct rusage sEnd;
228  getrusage(RUSAGE_SELF, &sEnd);
229  printf("Run Time: real %.3f user %f sys %f\n",
230  (iEnd - iBegin)*0.001,
231  timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
232  timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
233  }
234 }
235 
236 #define BEGIN_TIMER beginTimer()
237 #define END_TIMER endTimer()
238 #define HAS_TIMER 1
239 
240 #elif (defined(_WIN32) || defined(WIN32))
241 
242 /* Saved resource information for the beginning of an operation */
243 static HANDLE hProcess;
244 static FILETIME ftKernelBegin;
245 static FILETIME ftUserBegin;
246 static sqlite3_int64 ftWallBegin;
247 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
248  LPFILETIME, LPFILETIME);
249 static GETPROCTIMES getProcessTimesAddr = NULL;
250 
251 /*
252 ** Check to see if we have timer support. Return 1 if necessary
253 ** support found (or found previously).
254 */
255 static int hasTimer(void){
256  if( getProcessTimesAddr ){
257  return 1;
258  } else {
259  /* GetProcessTimes() isn't supported in WIN95 and some other Windows
260  ** versions. See if the version we are running on has it, and if it
261  ** does, save off a pointer to it and the current process handle.
262  */
263  hProcess = GetCurrentProcess();
264  if( hProcess ){
265  HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
266  if( NULL != hinstLib ){
267  getProcessTimesAddr =
268  (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
269  if( NULL != getProcessTimesAddr ){
270  return 1;
271  }
272  FreeLibrary(hinstLib);
273  }
274  }
275  }
276  return 0;
277 }
278 
279 /*
280 ** Begin timing an operation
281 */
282 static void beginTimer(void){
283  if( enableTimer && getProcessTimesAddr ){
284  FILETIME ftCreation, ftExit;
285  getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
286  &ftKernelBegin,&ftUserBegin);
287  ftWallBegin = timeOfDay();
288  }
289 }
290 
291 /* Return the difference of two FILETIME structs in seconds */
292 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
293  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
294  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
295  return (double) ((i64End - i64Start) / 10000000.0);
296 }
297 
298 /*
299 ** Print the timing results.
300 */
301 static void endTimer(void){
302  if( enableTimer && getProcessTimesAddr){
303  FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
304  sqlite3_int64 ftWallEnd = timeOfDay();
305  getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
306  printf("Run Time: real %.3f user %f sys %f\n",
307  (ftWallEnd - ftWallBegin)*0.001,
308  timeDiff(&ftUserBegin, &ftUserEnd),
309  timeDiff(&ftKernelBegin, &ftKernelEnd));
310  }
311 }
312 
313 #define BEGIN_TIMER beginTimer()
314 #define END_TIMER endTimer()
315 #define HAS_TIMER hasTimer()
316 
317 #else
318 #define BEGIN_TIMER
319 #define END_TIMER
320 #define HAS_TIMER 0
321 #endif
322 
323 /*
324 ** Used to prevent warnings about unused parameters
325 */
326 #define UNUSED_PARAMETER(x) (void)(x)
327 
328 /*
329 ** If the following flag is set, then command execution stops
330 ** at an error if we are not interactive.
331 */
332 static int bail_on_error = 0;
333 
334 /*
335 ** Threat stdin as an interactive input if the following variable
336 ** is true. Otherwise, assume stdin is connected to a file or pipe.
337 */
338 static int stdin_is_interactive = 1;
339 
340 /*
341 ** On Windows systems we have to know if standard output is a console
342 ** in order to translate UTF-8 into MBCS. The following variable is
343 ** true if translation is required.
344 */
345 static int stdout_is_console = 1;
346 
347 /*
348 ** The following is the open SQLite database. We make a pointer
349 ** to this database a static variable so that it can be accessed
350 ** by the SIGINT handler to interrupt database processing.
351 */
352 static sqlite3 *globalDb = 0;
353 
354 /*
355 ** True if an interrupt (Control-C) has been received.
356 */
357 static volatile int seenInterrupt = 0;
358 
359 /*
360 ** This is the name of our program. It is set in main(), used
361 ** in a number of other places, mostly for error messages.
362 */
363 static char *Argv0;
364 
365 /*
366 ** Prompt strings. Initialized in main. Settable with
367 ** .prompt main continue
368 */
369 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
370 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
371 
372 /*
373 ** Render output like fprintf(). Except, if the output is going to the
374 ** console and if this is running on a Windows machine, translate the
375 ** output from UTF-8 into MBCS.
376 */
377 #if defined(_WIN32) || defined(WIN32)
378 void utf8_printf(FILE *out, const char *zFormat, ...){
379  va_list ap;
380  va_start(ap, zFormat);
381  if( stdout_is_console && (out==stdout || out==stderr) ){
382  char *z1 = sqlite3_vmprintf(zFormat, ap);
383  char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
384  sqlite3_free(z1);
385  fputs(z2, out);
386  sqlite3_free(z2);
387  }else{
388  vfprintf(out, zFormat, ap);
389  }
390  va_end(ap);
391 }
392 #elif !defined(utf8_printf)
393 # define utf8_printf fprintf
394 #endif
395 
396 /*
397 ** Render output like fprintf(). This should not be used on anything that
398 ** includes string formatting (e.g. "%s").
399 */
400 #if !defined(raw_printf)
401 # define raw_printf fprintf
402 #endif
403 
404 /*
405 ** Write I/O traces to the following stream.
406 */
407 #ifdef SQLITE_ENABLE_IOTRACE
408 static FILE *iotrace = 0;
409 #endif
410 
411 /*
412 ** This routine works like printf in that its first argument is a
413 ** format string and subsequent arguments are values to be substituted
414 ** in place of % fields. The result of formatting this string
415 ** is written to iotrace.
416 */
417 #ifdef SQLITE_ENABLE_IOTRACE
418 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
419  va_list ap;
420  char *z;
421  if( iotrace==0 ) return;
422  va_start(ap, zFormat);
423  z = sqlite3_vmprintf(zFormat, ap);
424  va_end(ap);
425  utf8_printf(iotrace, "%s", z);
426  sqlite3_free(z);
427 }
428 #endif
429 
430 
431 /*
432 ** Determines if a string is a number of not.
433 */
434 static int isNumber(const char *z, int *realnum){
435  if( *z=='-' || *z=='+' ) z++;
436  if( !IsDigit(*z) ){
437  return 0;
438  }
439  z++;
440  if( realnum ) *realnum = 0;
441  while( IsDigit(*z) ){ z++; }
442  if( *z=='.' ){
443  z++;
444  if( !IsDigit(*z) ) return 0;
445  while( IsDigit(*z) ){ z++; }
446  if( realnum ) *realnum = 1;
447  }
448  if( *z=='e' || *z=='E' ){
449  z++;
450  if( *z=='+' || *z=='-' ) z++;
451  if( !IsDigit(*z) ) return 0;
452  while( IsDigit(*z) ){ z++; }
453  if( realnum ) *realnum = 1;
454  }
455  return *z==0;
456 }
457 
458 /*
459 ** A global char* and an SQL function to access its current value
460 ** from within an SQL statement. This program used to use the
461 ** sqlite_exec_printf() API to substitue a string into an SQL statement.
462 ** The correct way to do this with sqlite3 is to use the bind API, but
463 ** since the shell is built around the callback paradigm it would be a lot
464 ** of work. Instead just use this hack, which is quite harmless.
465 */
466 static const char *zShellStatic = 0;
467 static void shellstaticFunc(
468  sqlite3_context *context,
469  int argc,
470  sqlite3_value **argv
471 ){
472  assert( 0==argc );
473  assert( zShellStatic );
474  UNUSED_PARAMETER(argc);
475  UNUSED_PARAMETER(argv);
476  sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
477 }
478 
479 
480 /*
481 ** Compute a string length that is limited to what can be stored in
482 ** lower 30 bits of a 32-bit signed integer.
483 */
484 static int strlen30(const char *z){
485  const char *z2 = z;
486  while( *z2 ){ z2++; }
487  return 0x3fffffff & (int)(z2 - z);
488 }
489 
490 /*
491 ** This routine reads a line of text from FILE in, stores
492 ** the text in memory obtained from malloc() and returns a pointer
493 ** to the text. NULL is returned at end of file, or if malloc()
494 ** fails.
495 **
496 ** If zLine is not NULL then it is a malloced buffer returned from
497 ** a previous call to this routine that may be reused.
498 */
499 static char *local_getline(char *zLine, FILE *in){
500  int nLine = zLine==0 ? 0 : 100;
501  int n = 0;
502 
503  while( 1 ){
504  if( n+100>nLine ){
505  nLine = nLine*2 + 100;
506  zLine = realloc(zLine, nLine);
507  if( zLine==0 ) return 0;
508  }
509  if( fgets(&zLine[n], nLine - n, in)==0 ){
510  if( n==0 ){
511  free(zLine);
512  return 0;
513  }
514  zLine[n] = 0;
515  break;
516  }
517  while( zLine[n] ) n++;
518  if( n>0 && zLine[n-1]=='\n' ){
519  n--;
520  if( n>0 && zLine[n-1]=='\r' ) n--;
521  zLine[n] = 0;
522  break;
523  }
524  }
525 #if defined(_WIN32) || defined(WIN32)
526  /* For interactive input on Windows systems, translate the
527  ** multi-byte characterset characters into UTF-8. */
528  if( stdin_is_interactive && in==stdin ){
529  char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
530  if( zTrans ){
531  int nTrans = strlen30(zTrans)+1;
532  if( nTrans>nLine ){
533  zLine = realloc(zLine, nTrans);
534  if( zLine==0 ){
535  sqlite3_free(zTrans);
536  return 0;
537  }
538  }
539  memcpy(zLine, zTrans, nTrans);
540  sqlite3_free(zTrans);
541  }
542  }
543 #endif /* defined(_WIN32) || defined(WIN32) */
544  return zLine;
545 }
546 
547 /*
548 ** Retrieve a single line of input text.
549 **
550 ** If in==0 then read from standard input and prompt before each line.
551 ** If isContinuation is true, then a continuation prompt is appropriate.
552 ** If isContinuation is zero, then the main prompt should be used.
553 **
554 ** If zPrior is not NULL then it is a buffer from a prior call to this
555 ** routine that can be reused.
556 **
557 ** The result is stored in space obtained from malloc() and must either
558 ** be freed by the caller or else passed back into this routine via the
559 ** zPrior argument for reuse.
560 */
561 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
562  char *zPrompt;
563  char *zResult;
564  if( in!=0 ){
565  zResult = local_getline(zPrior, in);
566  }else{
567  zPrompt = isContinuation ? continuePrompt : mainPrompt;
568 #if SHELL_USE_LOCAL_GETLINE
569  printf("%s", zPrompt);
570  fflush(stdout);
571  zResult = local_getline(zPrior, stdin);
572 #else
573  free(zPrior);
574  zResult = shell_readline(zPrompt);
575  if( zResult && *zResult ) shell_add_history(zResult);
576 #endif
577  }
578  return zResult;
579 }
580 
581 #if defined(SQLITE_ENABLE_SESSION)
582 /*
583 ** State information for a single open session
584 */
585 typedef struct OpenSession OpenSession;
586 struct OpenSession {
587  char *zName; /* Symbolic name for this session */
588  int nFilter; /* Number of xFilter rejection GLOB patterns */
589  char **azFilter; /* Array of xFilter rejection GLOB patterns */
590  sqlite3_session *p; /* The open session */
591 };
592 #endif
593 
594 /*
595 ** Shell output mode information from before ".explain on",
596 ** saved so that it can be restored by ".explain off"
597 */
600  int valid; /* Is there legit data in here? */
601  int mode; /* Mode prior to ".explain on" */
602  int showHeader; /* The ".header" setting prior to ".explain on" */
603  int colWidth[100]; /* Column widths prior to ".explain on" */
604 };
605 
606 /*
607 ** State information about the database connection is contained in an
608 ** instance of the following structure.
609 */
610 typedef struct ShellState ShellState;
611 struct ShellState {
612  sqlite3 *db; /* The database */
613  int echoOn; /* True to echo input commands */
614  int autoExplain; /* Automatically turn on .explain mode */
615  int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
616  int statsOn; /* True to display memory stats before each finalize */
617  int scanstatsOn; /* True to display scan stats before each finalize */
618  int countChanges; /* True to display change counts */
619  int backslashOn; /* Resolve C-style \x escapes in SQL input text */
620  int outCount; /* Revert to stdout when reaching zero */
621  int cnt; /* Number of records displayed so far */
622  FILE *out; /* Write results here */
623  FILE *traceOut; /* Output for sqlite3_trace() */
624  int nErr; /* Number of errors seen */
625  int mode; /* An output mode setting */
626  int cMode; /* temporary output mode for the current query */
627  int normalMode; /* Output mode before ".explain on" */
628  int writableSchema; /* True if PRAGMA writable_schema=ON */
629  int showHeader; /* True to show column names in List or Column mode */
630  int nCheck; /* Number of ".check" commands run */
631  unsigned shellFlgs; /* Various flags */
632  char *zDestTable; /* Name of destination table when MODE_Insert */
633  char zTestcase[30]; /* Name of current test case */
634  char colSeparator[20]; /* Column separator character for several modes */
635  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
636  int colWidth[100]; /* Requested width of each column when in column mode*/
637  int actualWidth[100]; /* Actual width of each column */
638  char nullValue[20]; /* The text to print when a NULL comes back from
639  ** the database */
640  char outfile[FILENAME_MAX]; /* Filename for *out */
641  const char *zDbFilename; /* name of the database file */
642  char *zFreeOnClose; /* Filename to free when closing */
643  const char *zVfs; /* Name of VFS to use */
644  sqlite3_stmt *pStmt; /* Current statement if any. */
645  FILE *pLog; /* Write log output here */
646  int *aiIndent; /* Array of indents used in MODE_Explain */
647  int nIndent; /* Size of array aiIndent[] */
648  int iIndent; /* Index of current op in aiIndent[] */
649 #if defined(SQLITE_ENABLE_SESSION)
650  int nSession; /* Number of active sessions */
651  OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
652 #endif
653 };
654 
655 /*
656 ** These are the allowed shellFlgs values
657 */
658 #define SHFLG_Scratch 0x00001 /* The --scratch option is used */
659 #define SHFLG_Pagecache 0x00002 /* The --pagecache option is used */
660 #define SHFLG_Lookaside 0x00004 /* Lookaside memory is used */
661 
662 /*
663 ** These are the allowed modes.
664 */
665 #define MODE_Line 0 /* One column per line. Blank line between records */
666 #define MODE_Column 1 /* One record per line in neat columns */
667 #define MODE_List 2 /* One record per line with a separator */
668 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
669 #define MODE_Html 4 /* Generate an XHTML table */
670 #define MODE_Insert 5 /* Generate SQL "insert" statements */
671 #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
672 #define MODE_Csv 7 /* Quote strings, numbers are plain */
673 #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
674 #define MODE_Ascii 9 /* Use ASCII unit and record separators (0x1F/0x1E) */
675 #define MODE_Pretty 10 /* Pretty-print schemas */
676 
677 static const char *modeDescr[] = {
678  "line",
679  "column",
680  "list",
681  "semi",
682  "html",
683  "insert",
684  "tcl",
685  "csv",
686  "explain",
687  "ascii",
688  "prettyprint",
689 };
690 
691 /*
692 ** These are the column/row/line separators used by the various
693 ** import/export modes.
694 */
695 #define SEP_Column "|"
696 #define SEP_Row "\n"
697 #define SEP_Tab "\t"
698 #define SEP_Space " "
699 #define SEP_Comma ","
700 #define SEP_CrLf "\r\n"
701 #define SEP_Unit "\x1F"
702 #define SEP_Record "\x1E"
703 
704 /*
705 ** Number of elements in an array
706 */
707 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
708 
709 /*
710 ** A callback for the sqlite3_log() interface.
711 */
712 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
713  ShellState *p = (ShellState*)pArg;
714  if( p->pLog==0 ) return;
715  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
716  fflush(p->pLog);
717 }
718 
719 /*
720 ** Output the given string as a hex-encoded blob (eg. X'1234' )
721 */
722 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
723  int i;
724  char *zBlob = (char *)pBlob;
725  raw_printf(out,"X'");
726  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
727  raw_printf(out,"'");
728 }
729 
730 /*
731 ** Output the given string as a quoted string using SQL quoting conventions.
732 */
733 static void output_quoted_string(FILE *out, const char *z){
734  int i;
735  int nSingle = 0;
736  setBinaryMode(out, 1);
737  for(i=0; z[i]; i++){
738  if( z[i]=='\'' ) nSingle++;
739  }
740  if( nSingle==0 ){
741  utf8_printf(out,"'%s'",z);
742  }else{
743  raw_printf(out,"'");
744  while( *z ){
745  for(i=0; z[i] && z[i]!='\''; i++){}
746  if( i==0 ){
747  raw_printf(out,"''");
748  z++;
749  }else if( z[i]=='\'' ){
750  utf8_printf(out,"%.*s''",i,z);
751  z += i+1;
752  }else{
753  utf8_printf(out,"%s",z);
754  break;
755  }
756  }
757  raw_printf(out,"'");
758  }
759  setTextMode(out, 1);
760 }
761 
762 /*
763 ** Output the given string as a quoted according to C or TCL quoting rules.
764 */
765 static void output_c_string(FILE *out, const char *z){
766  unsigned int c;
767  fputc('"', out);
768  while( (c = *(z++))!=0 ){
769  if( c=='\\' ){
770  fputc(c, out);
771  fputc(c, out);
772  }else if( c=='"' ){
773  fputc('\\', out);
774  fputc('"', out);
775  }else if( c=='\t' ){
776  fputc('\\', out);
777  fputc('t', out);
778  }else if( c=='\n' ){
779  fputc('\\', out);
780  fputc('n', out);
781  }else if( c=='\r' ){
782  fputc('\\', out);
783  fputc('r', out);
784  }else if( !isprint(c&0xff) ){
785  raw_printf(out, "\\%03o", c&0xff);
786  }else{
787  fputc(c, out);
788  }
789  }
790  fputc('"', out);
791 }
792 
793 /*
794 ** Output the given string with characters that are special to
795 ** HTML escaped.
796 */
797 static void output_html_string(FILE *out, const char *z){
798  int i;
799  if( z==0 ) z = "";
800  while( *z ){
801  for(i=0; z[i]
802  && z[i]!='<'
803  && z[i]!='&'
804  && z[i]!='>'
805  && z[i]!='\"'
806  && z[i]!='\'';
807  i++){}
808  if( i>0 ){
809  utf8_printf(out,"%.*s",i,z);
810  }
811  if( z[i]=='<' ){
812  raw_printf(out,"&lt;");
813  }else if( z[i]=='&' ){
814  raw_printf(out,"&amp;");
815  }else if( z[i]=='>' ){
816  raw_printf(out,"&gt;");
817  }else if( z[i]=='\"' ){
818  raw_printf(out,"&quot;");
819  }else if( z[i]=='\'' ){
820  raw_printf(out,"&#39;");
821  }else{
822  break;
823  }
824  z += i + 1;
825  }
826 }
827 
828 /*
829 ** If a field contains any character identified by a 1 in the following
830 ** array, then the string must be quoted for CSV.
831 */
832 static const char needCsvQuote[] = {
833  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
834  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
835  1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
836  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
837  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
838  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
839  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
840  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
841  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
842  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
843  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
844  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
845  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
846  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
847  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
848  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
849 };
850 
851 /*
852 ** Output a single term of CSV. Actually, p->colSeparator is used for
853 ** the separator, which may or may not be a comma. p->nullValue is
854 ** the null value. Strings are quoted if necessary. The separator
855 ** is only issued if bSep is true.
856 */
857 static void output_csv(ShellState *p, const char *z, int bSep){
858  FILE *out = p->out;
859  if( z==0 ){
860  utf8_printf(out,"%s",p->nullValue);
861  }else{
862  int i;
863  int nSep = strlen30(p->colSeparator);
864  for(i=0; z[i]; i++){
865  if( needCsvQuote[((unsigned char*)z)[i]]
866  || (z[i]==p->colSeparator[0] &&
867  (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
868  i = 0;
869  break;
870  }
871  }
872  if( i==0 ){
873  putc('"', out);
874  for(i=0; z[i]; i++){
875  if( z[i]=='"' ) putc('"', out);
876  putc(z[i], out);
877  }
878  putc('"', out);
879  }else{
880  utf8_printf(out, "%s", z);
881  }
882  }
883  if( bSep ){
884  utf8_printf(p->out, "%s", p->colSeparator);
885  }
886 }
887 
888 #ifdef SIGINT
889 /*
890 ** This routine runs when the user presses Ctrl-C
891 */
892 static void interrupt_handler(int NotUsed){
893  UNUSED_PARAMETER(NotUsed);
894  seenInterrupt++;
895  if( seenInterrupt>2 ) exit(1);
896  if( globalDb ) sqlite3_interrupt(globalDb);
897 }
898 #endif
899 
900 #ifndef SQLITE_OMIT_AUTHORIZATION
901 /*
902 ** When the ".auth ON" is set, the following authorizer callback is
903 ** invoked. It always returns SQLITE_OK.
904 */
905 static int shellAuth(
906  void *pClientData,
907  int op,
908  const char *zA1,
909  const char *zA2,
910  const char *zA3,
911  const char *zA4
912 ){
913  ShellState *p = (ShellState*)pClientData;
914  static const char *azAction[] = { 0,
915  "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
916  "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
917  "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
918  "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
919  "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
920  "DROP_TRIGGER", "DROP_VIEW", "INSERT",
921  "PRAGMA", "READ", "SELECT",
922  "TRANSACTION", "UPDATE", "ATTACH",
923  "DETACH", "ALTER_TABLE", "REINDEX",
924  "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
925  "FUNCTION", "SAVEPOINT", "RECURSIVE"
926  };
927  int i;
928  const char *az[4];
929  az[0] = zA1;
930  az[1] = zA2;
931  az[2] = zA3;
932  az[3] = zA4;
933  utf8_printf(p->out, "authorizer: %s", azAction[op]);
934  for(i=0; i<4; i++){
935  raw_printf(p->out, " ");
936  if( az[i] ){
937  output_c_string(p->out, az[i]);
938  }else{
939  raw_printf(p->out, "NULL");
940  }
941  }
942  raw_printf(p->out, "\n");
943  return SQLITE_OK;
944 }
945 #endif
946 
947 
948 /*
949 ** This is the callback routine that the shell
950 ** invokes for each row of a query result.
951 */
952 static int shell_callback(
953  void *pArg,
954  int nArg, /* Number of result columns */
955  char **azArg, /* Text of each result column */
956  char **azCol, /* Column names */
957  int *aiType /* Column types */
958 ){
959  int i;
960  ShellState *p = (ShellState*)pArg;
961 
962  switch( p->cMode ){
963  case MODE_Line: {
964  int w = 5;
965  if( azArg==0 ) break;
966  for(i=0; i<nArg; i++){
967  int len = strlen30(azCol[i] ? azCol[i] : "");
968  if( len>w ) w = len;
969  }
970  if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
971  for(i=0; i<nArg; i++){
972  utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
973  azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
974  }
975  break;
976  }
977  case MODE_Explain:
978  case MODE_Column: {
979  static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
980  const int *colWidth;
981  int showHdr;
982  char *rowSep;
983  if( p->cMode==MODE_Column ){
984  colWidth = p->colWidth;
985  showHdr = p->showHeader;
986  rowSep = p->rowSeparator;
987  }else{
988  colWidth = aExplainWidths;
989  showHdr = 1;
990  rowSep = SEP_Row;
991  }
992  if( p->cnt++==0 ){
993  for(i=0; i<nArg; i++){
994  int w, n;
995  if( i<ArraySize(p->colWidth) ){
996  w = colWidth[i];
997  }else{
998  w = 0;
999  }
1000  if( w==0 ){
1001  w = strlen30(azCol[i] ? azCol[i] : "");
1002  if( w<10 ) w = 10;
1003  n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
1004  if( w<n ) w = n;
1005  }
1006  if( i<ArraySize(p->actualWidth) ){
1007  p->actualWidth[i] = w;
1008  }
1009  if( showHdr ){
1010  if( w<0 ){
1011  utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i],
1012  i==nArg-1 ? rowSep : " ");
1013  }else{
1014  utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i],
1015  i==nArg-1 ? rowSep : " ");
1016  }
1017  }
1018  }
1019  if( showHdr ){
1020  for(i=0; i<nArg; i++){
1021  int w;
1022  if( i<ArraySize(p->actualWidth) ){
1023  w = p->actualWidth[i];
1024  if( w<0 ) w = -w;
1025  }else{
1026  w = 10;
1027  }
1028  utf8_printf(p->out,"%-*.*s%s",w,w,
1029  "----------------------------------------------------------"
1030  "----------------------------------------------------------",
1031  i==nArg-1 ? rowSep : " ");
1032  }
1033  }
1034  }
1035  if( azArg==0 ) break;
1036  for(i=0; i<nArg; i++){
1037  int w;
1038  if( i<ArraySize(p->actualWidth) ){
1039  w = p->actualWidth[i];
1040  }else{
1041  w = 10;
1042  }
1043  if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
1044  w = strlen30(azArg[i]);
1045  }
1046  if( i==1 && p->aiIndent && p->pStmt ){
1047  if( p->iIndent<p->nIndent ){
1048  utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
1049  }
1050  p->iIndent++;
1051  }
1052  if( w<0 ){
1053  utf8_printf(p->out,"%*.*s%s",-w,-w,
1054  azArg[i] ? azArg[i] : p->nullValue,
1055  i==nArg-1 ? rowSep : " ");
1056  }else{
1057  utf8_printf(p->out,"%-*.*s%s",w,w,
1058  azArg[i] ? azArg[i] : p->nullValue,
1059  i==nArg-1 ? rowSep : " ");
1060  }
1061  }
1062  break;
1063  }
1064  case MODE_Semi: { /* .schema and .fullschema output */
1065  utf8_printf(p->out, "%s;\n", azArg[0]);
1066  break;
1067  }
1068  case MODE_Pretty: { /* .schema and .fullschema with --indent */
1069  char *z;
1070  int j;
1071  int nParen = 0;
1072  char cEnd = 0;
1073  char c;
1074  int nLine = 0;
1075  assert( nArg==1 );
1076  if( azArg[0]==0 ) break;
1077  if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1078  || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1079  ){
1080  utf8_printf(p->out, "%s;\n", azArg[0]);
1081  break;
1082  }
1083  z = sqlite3_mprintf("%s", azArg[0]);
1084  j = 0;
1085  for(i=0; IsSpace(z[i]); i++){}
1086  for(; (c = z[i])!=0; i++){
1087  if( IsSpace(c) ){
1088  if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1089  }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1090  j--;
1091  }
1092  z[j++] = c;
1093  }
1094  while( j>0 && IsSpace(z[j-1]) ){ j--; }
1095  z[j] = 0;
1096  if( strlen30(z)>=79 ){
1097  for(i=j=0; (c = z[i])!=0; i++){
1098  if( c==cEnd ){
1099  cEnd = 0;
1100  }else if( c=='"' || c=='\'' || c=='`' ){
1101  cEnd = c;
1102  }else if( c=='[' ){
1103  cEnd = ']';
1104  }else if( c=='(' ){
1105  nParen++;
1106  }else if( c==')' ){
1107  nParen--;
1108  if( nLine>0 && nParen==0 && j>0 ){
1109  utf8_printf(p->out, "%.*s\n", j, z);
1110  j = 0;
1111  }
1112  }
1113  z[j++] = c;
1114  if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
1115  if( c=='\n' ) j--;
1116  utf8_printf(p->out, "%.*s\n ", j, z);
1117  j = 0;
1118  nLine++;
1119  while( IsSpace(z[i+1]) ){ i++; }
1120  }
1121  }
1122  z[j] = 0;
1123  }
1124  utf8_printf(p->out, "%s;\n", z);
1125  sqlite3_free(z);
1126  break;
1127  }
1128  case MODE_List: {
1129  if( p->cnt++==0 && p->showHeader ){
1130  for(i=0; i<nArg; i++){
1131  utf8_printf(p->out,"%s%s",azCol[i],
1132  i==nArg-1 ? p->rowSeparator : p->colSeparator);
1133  }
1134  }
1135  if( azArg==0 ) break;
1136  for(i=0; i<nArg; i++){
1137  char *z = azArg[i];
1138  if( z==0 ) z = p->nullValue;
1139  utf8_printf(p->out, "%s", z);
1140  if( i<nArg-1 ){
1141  utf8_printf(p->out, "%s", p->colSeparator);
1142  }else{
1143  utf8_printf(p->out, "%s", p->rowSeparator);
1144  }
1145  }
1146  break;
1147  }
1148  case MODE_Html: {
1149  if( p->cnt++==0 && p->showHeader ){
1150  raw_printf(p->out,"<TR>");
1151  for(i=0; i<nArg; i++){
1152  raw_printf(p->out,"<TH>");
1153  output_html_string(p->out, azCol[i]);
1154  raw_printf(p->out,"</TH>\n");
1155  }
1156  raw_printf(p->out,"</TR>\n");
1157  }
1158  if( azArg==0 ) break;
1159  raw_printf(p->out,"<TR>");
1160  for(i=0; i<nArg; i++){
1161  raw_printf(p->out,"<TD>");
1162  output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1163  raw_printf(p->out,"</TD>\n");
1164  }
1165  raw_printf(p->out,"</TR>\n");
1166  break;
1167  }
1168  case MODE_Tcl: {
1169  if( p->cnt++==0 && p->showHeader ){
1170  for(i=0; i<nArg; i++){
1171  output_c_string(p->out,azCol[i] ? azCol[i] : "");
1172  if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1173  }
1174  utf8_printf(p->out, "%s", p->rowSeparator);
1175  }
1176  if( azArg==0 ) break;
1177  for(i=0; i<nArg; i++){
1178  output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
1179  if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
1180  }
1181  utf8_printf(p->out, "%s", p->rowSeparator);
1182  break;
1183  }
1184  case MODE_Csv: {
1185  setBinaryMode(p->out, 1);
1186  if( p->cnt++==0 && p->showHeader ){
1187  for(i=0; i<nArg; i++){
1188  output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
1189  }
1190  utf8_printf(p->out, "%s", p->rowSeparator);
1191  }
1192  if( nArg>0 ){
1193  for(i=0; i<nArg; i++){
1194  output_csv(p, azArg[i], i<nArg-1);
1195  }
1196  utf8_printf(p->out, "%s", p->rowSeparator);
1197  }
1198  setTextMode(p->out, 1);
1199  break;
1200  }
1201  case MODE_Insert: {
1202  p->cnt++;
1203  if( azArg==0 ) break;
1204  utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
1205  if( p->showHeader ){
1206  raw_printf(p->out,"(");
1207  for(i=0; i<nArg; i++){
1208  char *zSep = i>0 ? ",": "";
1209  utf8_printf(p->out, "%s%s", zSep, azCol[i]);
1210  }
1211  raw_printf(p->out,")");
1212  }
1213  raw_printf(p->out," VALUES(");
1214  for(i=0; i<nArg; i++){
1215  char *zSep = i>0 ? ",": "";
1216  if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
1217  utf8_printf(p->out,"%sNULL",zSep);
1218  }else if( aiType && aiType[i]==SQLITE_TEXT ){
1219  if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
1220  output_quoted_string(p->out, azArg[i]);
1221  }else if( aiType && (aiType[i]==SQLITE_INTEGER
1222  || aiType[i]==SQLITE_FLOAT) ){
1223  utf8_printf(p->out,"%s%s",zSep, azArg[i]);
1224  }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
1225  const void *pBlob = sqlite3_column_blob(p->pStmt, i);
1226  int nBlob = sqlite3_column_bytes(p->pStmt, i);
1227  if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
1228  output_hex_blob(p->out, pBlob, nBlob);
1229  }else if( isNumber(azArg[i], 0) ){
1230  utf8_printf(p->out,"%s%s",zSep, azArg[i]);
1231  }else{
1232  if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
1233  output_quoted_string(p->out, azArg[i]);
1234  }
1235  }
1236  raw_printf(p->out,");\n");
1237  break;
1238  }
1239  case MODE_Ascii: {
1240  if( p->cnt++==0 && p->showHeader ){
1241  for(i=0; i<nArg; i++){
1242  if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1243  utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
1244  }
1245  utf8_printf(p->out, "%s", p->rowSeparator);
1246  }
1247  if( azArg==0 ) break;
1248  for(i=0; i<nArg; i++){
1249  if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
1250  utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
1251  }
1252  utf8_printf(p->out, "%s", p->rowSeparator);
1253  break;
1254  }
1255  }
1256  return 0;
1257 }
1258 
1259 /*
1260 ** This is the callback routine that the SQLite library
1261 ** invokes for each row of a query result.
1262 */
1263 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
1264  /* since we don't have type info, call the shell_callback with a NULL value */
1265  return shell_callback(pArg, nArg, azArg, azCol, NULL);
1266 }
1267 
1268 /*
1269 ** Set the destination table field of the ShellState structure to
1270 ** the name of the table given. Escape any quote characters in the
1271 ** table name.
1272 */
1273 static void set_table_name(ShellState *p, const char *zName){
1274  int i, n;
1275  int needQuote;
1276  char *z;
1277 
1278  if( p->zDestTable ){
1279  free(p->zDestTable);
1280  p->zDestTable = 0;
1281  }
1282  if( zName==0 ) return;
1283  needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
1284  for(i=n=0; zName[i]; i++, n++){
1285  if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
1286  needQuote = 1;
1287  if( zName[i]=='\'' ) n++;
1288  }
1289  }
1290  if( needQuote ) n += 2;
1291  z = p->zDestTable = malloc( n+1 );
1292  if( z==0 ){
1293  raw_printf(stderr,"Error: out of memory\n");
1294  exit(1);
1295  }
1296  n = 0;
1297  if( needQuote ) z[n++] = '\'';
1298  for(i=0; zName[i]; i++){
1299  z[n++] = zName[i];
1300  if( zName[i]=='\'' ) z[n++] = '\'';
1301  }
1302  if( needQuote ) z[n++] = '\'';
1303  z[n] = 0;
1304 }
1305 
1306 /* zIn is either a pointer to a NULL-terminated string in memory obtained
1307 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1308 ** added to zIn, and the result returned in memory obtained from malloc().
1309 ** zIn, if it was not NULL, is freed.
1310 **
1311 ** If the third argument, quote, is not '\0', then it is used as a
1312 ** quote character for zAppend.
1313 */
1314 static char *appendText(char *zIn, char const *zAppend, char quote){
1315  int len;
1316  int i;
1317  int nAppend = strlen30(zAppend);
1318  int nIn = (zIn?strlen30(zIn):0);
1319 
1320  len = nAppend+nIn+1;
1321  if( quote ){
1322  len += 2;
1323  for(i=0; i<nAppend; i++){
1324  if( zAppend[i]==quote ) len++;
1325  }
1326  }
1327 
1328  zIn = (char *)realloc(zIn, len);
1329  if( !zIn ){
1330  return 0;
1331  }
1332 
1333  if( quote ){
1334  char *zCsr = &zIn[nIn];
1335  *zCsr++ = quote;
1336  for(i=0; i<nAppend; i++){
1337  *zCsr++ = zAppend[i];
1338  if( zAppend[i]==quote ) *zCsr++ = quote;
1339  }
1340  *zCsr++ = quote;
1341  *zCsr++ = '\0';
1342  assert( (zCsr-zIn)==len );
1343  }else{
1344  memcpy(&zIn[nIn], zAppend, nAppend);
1345  zIn[len-1] = '\0';
1346  }
1347 
1348  return zIn;
1349 }
1350 
1351 
1352 /*
1353 ** Execute a query statement that will generate SQL output. Print
1354 ** the result columns, comma-separated, on a line and then add a
1355 ** semicolon terminator to the end of that line.
1356 **
1357 ** If the number of columns is 1 and that column contains text "--"
1358 ** then write the semicolon on a separate line. That way, if a
1359 ** "--" comment occurs at the end of the statement, the comment
1360 ** won't consume the semicolon terminator.
1361 */
1363  ShellState *p, /* Query context */
1364  const char *zSelect, /* SELECT statement to extract content */
1365  const char *zFirstRow /* Print before first row, if not NULL */
1366 ){
1367  sqlite3_stmt *pSelect;
1368  int rc;
1369  int nResult;
1370  int i;
1371  const char *z;
1372  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
1373  if( rc!=SQLITE_OK || !pSelect ){
1374  utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1375  sqlite3_errmsg(p->db));
1376  if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1377  return rc;
1378  }
1379  rc = sqlite3_step(pSelect);
1380  nResult = sqlite3_column_count(pSelect);
1381  while( rc==SQLITE_ROW ){
1382  if( zFirstRow ){
1383  utf8_printf(p->out, "%s", zFirstRow);
1384  zFirstRow = 0;
1385  }
1386  z = (const char*)sqlite3_column_text(pSelect, 0);
1387  utf8_printf(p->out, "%s", z);
1388  for(i=1; i<nResult; i++){
1389  utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
1390  }
1391  if( z==0 ) z = "";
1392  while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
1393  if( z[0] ){
1394  raw_printf(p->out, "\n;\n");
1395  }else{
1396  raw_printf(p->out, ";\n");
1397  }
1398  rc = sqlite3_step(pSelect);
1399  }
1400  rc = sqlite3_finalize(pSelect);
1401  if( rc!=SQLITE_OK ){
1402  utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
1403  sqlite3_errmsg(p->db));
1404  if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1405  }
1406  return rc;
1407 }
1408 
1409 /*
1410 ** Allocate space and save off current error string.
1411 */
1412 static char *save_err_msg(
1413  sqlite3 *db /* Database to query */
1414 ){
1415  int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
1416  char *zErrMsg = sqlite3_malloc64(nErrMsg);
1417  if( zErrMsg ){
1418  memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
1419  }
1420  return zErrMsg;
1421 }
1422 
1423 #ifdef __linux__
1424 /*
1425 ** Attempt to display I/O stats on Linux using /proc/PID/io
1426 */
1427 static void displayLinuxIoStats(FILE *out){
1428  FILE *in;
1429  char z[200];
1430  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
1431  in = fopen(z, "rb");
1432  if( in==0 ) return;
1433  while( fgets(z, sizeof(z), in)!=0 ){
1434  static const struct {
1435  const char *zPattern;
1436  const char *zDesc;
1437  } aTrans[] = {
1438  { "rchar: ", "Bytes received by read():" },
1439  { "wchar: ", "Bytes sent to write():" },
1440  { "syscr: ", "Read() system calls:" },
1441  { "syscw: ", "Write() system calls:" },
1442  { "read_bytes: ", "Bytes read from storage:" },
1443  { "write_bytes: ", "Bytes written to storage:" },
1444  { "cancelled_write_bytes: ", "Cancelled write bytes:" },
1445  };
1446  int i;
1447  for(i=0; i<ArraySize(aTrans); i++){
1448  int n = (int)strlen(aTrans[i].zPattern);
1449  if( strncmp(aTrans[i].zPattern, z, n)==0 ){
1450  utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
1451  break;
1452  }
1453  }
1454  }
1455  fclose(in);
1456 }
1457 #endif
1458 
1459 
1460 /*
1461 ** Display memory stats.
1462 */
1463 static int display_stats(
1464  sqlite3 *db, /* Database to query */
1465  ShellState *pArg, /* Pointer to ShellState */
1466  int bReset /* True to reset the stats */
1467 ){
1468  int iCur;
1469  int iHiwtr;
1470 
1471  if( pArg && pArg->out ){
1472 
1473  iHiwtr = iCur = -1;
1474  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
1475  raw_printf(pArg->out,
1476  "Memory Used: %d (max %d) bytes\n",
1477  iCur, iHiwtr);
1478  iHiwtr = iCur = -1;
1479  sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
1480  raw_printf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n",
1481  iCur, iHiwtr);
1482  if( pArg->shellFlgs & SHFLG_Pagecache ){
1483  iHiwtr = iCur = -1;
1484  sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
1485  raw_printf(pArg->out,
1486  "Number of Pcache Pages Used: %d (max %d) pages\n",
1487  iCur, iHiwtr);
1488  }
1489  iHiwtr = iCur = -1;
1490  sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
1491  raw_printf(pArg->out,
1492  "Number of Pcache Overflow Bytes: %d (max %d) bytes\n",
1493  iCur, iHiwtr);
1494  if( pArg->shellFlgs & SHFLG_Scratch ){
1495  iHiwtr = iCur = -1;
1496  sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
1497  raw_printf(pArg->out,
1498  "Number of Scratch Allocations Used: %d (max %d)\n",
1499  iCur, iHiwtr);
1500  }
1501  iHiwtr = iCur = -1;
1502  sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
1503  raw_printf(pArg->out,
1504  "Number of Scratch Overflow Bytes: %d (max %d) bytes\n",
1505  iCur, iHiwtr);
1506  iHiwtr = iCur = -1;
1507  sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
1508  raw_printf(pArg->out, "Largest Allocation: %d bytes\n",
1509  iHiwtr);
1510  iHiwtr = iCur = -1;
1511  sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
1512  raw_printf(pArg->out, "Largest Pcache Allocation: %d bytes\n",
1513  iHiwtr);
1514  iHiwtr = iCur = -1;
1515  sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
1516  raw_printf(pArg->out, "Largest Scratch Allocation: %d bytes\n",
1517  iHiwtr);
1518 #ifdef YYTRACKMAXSTACKDEPTH
1519  iHiwtr = iCur = -1;
1520  sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
1521  raw_printf(pArg->out, "Deepest Parser Stack: %d (max %d)\n",
1522  iCur, iHiwtr);
1523 #endif
1524  }
1525 
1526  if( pArg && pArg->out && db ){
1527  if( pArg->shellFlgs & SHFLG_Lookaside ){
1528  iHiwtr = iCur = -1;
1530  &iCur, &iHiwtr, bReset);
1531  raw_printf(pArg->out,
1532  "Lookaside Slots Used: %d (max %d)\n",
1533  iCur, iHiwtr);
1535  &iCur, &iHiwtr, bReset);
1536  raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
1537  iHiwtr);
1539  &iCur, &iHiwtr, bReset);
1540  raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
1541  iHiwtr);
1543  &iCur, &iHiwtr, bReset);
1544  raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
1545  iHiwtr);
1546  }
1547  iHiwtr = iCur = -1;
1548  sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
1549  raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
1550  iCur);
1551  iHiwtr = iCur = -1;
1552  sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
1553  raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
1554  iHiwtr = iCur = -1;
1555  sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
1556  raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
1557  iHiwtr = iCur = -1;
1558  sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
1559  raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
1560  iHiwtr = iCur = -1;
1561  sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
1562  raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
1563  iCur);
1564  iHiwtr = iCur = -1;
1565  sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
1566  raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
1567  iCur);
1568  }
1569 
1570  if( pArg && pArg->out && db && pArg->pStmt ){
1572  bReset);
1573  raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
1574  iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
1575  raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
1577  raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
1578  iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
1579  raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
1580  }
1581 
1582 #ifdef __linux__
1583  displayLinuxIoStats(pArg->out);
1584 #endif
1585 
1586  /* Do not remove this machine readable comment: extra-stats-output-here */
1587 
1588  return 0;
1589 }
1590 
1591 /*
1592 ** Display scan stats.
1593 */
1594 static void display_scanstats(
1595  sqlite3 *db, /* Database to query */
1596  ShellState *pArg /* Pointer to ShellState */
1597 ){
1598 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
1599  UNUSED_PARAMETER(db);
1600  UNUSED_PARAMETER(pArg);
1601 #else
1602  int i, k, n, mx;
1603  raw_printf(pArg->out, "-------- scanstats --------\n");
1604  mx = 0;
1605  for(k=0; k<=mx; k++){
1606  double rEstLoop = 1.0;
1607  for(i=n=0; 1; i++){
1608  sqlite3_stmt *p = pArg->pStmt;
1609  sqlite3_int64 nLoop, nVisit;
1610  double rEst;
1611  int iSid;
1612  const char *zExplain;
1613  if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
1614  break;
1615  }
1617  if( iSid>mx ) mx = iSid;
1618  if( iSid!=k ) continue;
1619  if( n==0 ){
1620  rEstLoop = (double)nLoop;
1621  if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
1622  }
1623  n++;
1624  sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
1625  sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
1626  sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
1627  utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
1628  rEstLoop *= rEst;
1629  raw_printf(pArg->out,
1630  " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
1631  nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
1632  );
1633  }
1634  }
1635  raw_printf(pArg->out, "---------------------------\n");
1636 #endif
1637 }
1638 
1639 /*
1640 ** Parameter azArray points to a zero-terminated array of strings. zStr
1641 ** points to a single nul-terminated string. Return non-zero if zStr
1642 ** is equal, according to strcmp(), to any of the strings in the array.
1643 ** Otherwise, return zero.
1644 */
1645 static int str_in_array(const char *zStr, const char **azArray){
1646  int i;
1647  for(i=0; azArray[i]; i++){
1648  if( 0==strcmp(zStr, azArray[i]) ) return 1;
1649  }
1650  return 0;
1651 }
1652 
1653 /*
1654 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
1655 ** and populate the ShellState.aiIndent[] array with the number of
1656 ** spaces each opcode should be indented before it is output.
1657 **
1658 ** The indenting rules are:
1659 **
1660 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
1661 ** all opcodes that occur between the p2 jump destination and the opcode
1662 ** itself by 2 spaces.
1663 **
1664 ** * For each "Goto", if the jump destination is earlier in the program
1665 ** and ends on one of:
1666 ** Yield SeekGt SeekLt RowSetRead Rewind
1667 ** or if the P1 parameter is one instead of zero,
1668 ** then indent all opcodes between the earlier instruction
1669 ** and "Goto" by 2 spaces.
1670 */
1672  const char *zSql; /* The text of the SQL statement */
1673  const char *z; /* Used to check if this is an EXPLAIN */
1674  int *abYield = 0; /* True if op is an OP_Yield */
1675  int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
1676  int iOp; /* Index of operation in p->aiIndent[] */
1677 
1678  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
1679  "NextIfOpen", "PrevIfOpen", 0 };
1680  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
1681  "Rewind", 0 };
1682  const char *azGoto[] = { "Goto", 0 };
1683 
1684  /* Try to figure out if this is really an EXPLAIN statement. If this
1685  ** cannot be verified, return early. */
1686  if( sqlite3_column_count(pSql)!=8 ){
1687  p->cMode = p->mode;
1688  return;
1689  }
1690  zSql = sqlite3_sql(pSql);
1691  if( zSql==0 ) return;
1692  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
1693  if( sqlite3_strnicmp(z, "explain", 7) ){
1694  p->cMode = p->mode;
1695  return;
1696  }
1697 
1698  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
1699  int i;
1700  int iAddr = sqlite3_column_int(pSql, 0);
1701  const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
1702 
1703  /* Set p2 to the P2 field of the current opcode. Then, assuming that
1704  ** p2 is an instruction address, set variable p2op to the index of that
1705  ** instruction in the aiIndent[] array. p2 and p2op may be different if
1706  ** the current instruction is part of a sub-program generated by an
1707  ** SQL trigger or foreign key. */
1708  int p2 = sqlite3_column_int(pSql, 3);
1709  int p2op = (p2 + (iOp-iAddr));
1710 
1711  /* Grow the p->aiIndent array as required */
1712  if( iOp>=nAlloc ){
1713  if( iOp==0 ){
1714  /* Do further verfication that this is explain output. Abort if
1715  ** it is not */
1716  static const char *explainCols[] = {
1717  "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
1718  int jj;
1719  for(jj=0; jj<ArraySize(explainCols); jj++){
1720  if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
1721  p->cMode = p->mode;
1722  sqlite3_reset(pSql);
1723  return;
1724  }
1725  }
1726  }
1727  nAlloc += 100;
1728  p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
1729  abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
1730  }
1731  abYield[iOp] = str_in_array(zOp, azYield);
1732  p->aiIndent[iOp] = 0;
1733  p->nIndent = iOp+1;
1734 
1735  if( str_in_array(zOp, azNext) ){
1736  for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
1737  }
1738  if( str_in_array(zOp, azGoto) && p2op<p->nIndent
1739  && (abYield[p2op] || sqlite3_column_int(pSql, 2))
1740  ){
1741  for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
1742  }
1743  }
1744 
1745  p->iIndent = 0;
1746  sqlite3_free(abYield);
1747  sqlite3_reset(pSql);
1748 }
1749 
1750 /*
1751 ** Free the array allocated by explain_data_prepare().
1752 */
1754  sqlite3_free(p->aiIndent);
1755  p->aiIndent = 0;
1756  p->nIndent = 0;
1757  p->iIndent = 0;
1758 }
1759 
1760 /*
1761 ** Disable and restore .wheretrace and .selecttrace settings.
1762 */
1763 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
1764 extern int sqlite3SelectTrace;
1765 static int savedSelectTrace;
1766 #endif
1767 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
1768 extern int sqlite3WhereTrace;
1769 static int savedWhereTrace;
1770 #endif
1771 static void disable_debug_trace_modes(void){
1772 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
1773  savedSelectTrace = sqlite3SelectTrace;
1774  sqlite3SelectTrace = 0;
1775 #endif
1776 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
1777  savedWhereTrace = sqlite3WhereTrace;
1778  sqlite3WhereTrace = 0;
1779 #endif
1780 }
1781 static void restore_debug_trace_modes(void){
1782 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
1783  sqlite3SelectTrace = savedSelectTrace;
1784 #endif
1785 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
1786  sqlite3WhereTrace = savedWhereTrace;
1787 #endif
1788 }
1789 
1790 /*
1791 ** Run a prepared statement
1792 */
1794  ShellState *pArg, /* Pointer to ShellState */
1795  sqlite3_stmt *pStmt, /* Statment to run */
1796  int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
1797 ){
1798  int rc;
1799 
1800  /* perform the first step. this will tell us if we
1801  ** have a result set or not and how wide it is.
1802  */
1803  rc = sqlite3_step(pStmt);
1804  /* if we have a result set... */
1805  if( SQLITE_ROW == rc ){
1806  /* if we have a callback... */
1807  if( xCallback ){
1808  /* allocate space for col name ptr, value ptr, and type */
1809  int nCol = sqlite3_column_count(pStmt);
1810  void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
1811  if( !pData ){
1812  rc = SQLITE_NOMEM;
1813  }else{
1814  char **azCols = (char **)pData; /* Names of result columns */
1815  char **azVals = &azCols[nCol]; /* Results */
1816  int *aiTypes = (int *)&azVals[nCol]; /* Result types */
1817  int i, x;
1818  assert(sizeof(int) <= sizeof(char *));
1819  /* save off ptrs to column names */
1820  for(i=0; i<nCol; i++){
1821  azCols[i] = (char *)sqlite3_column_name(pStmt, i);
1822  }
1823  do{
1824  /* extract the data and data types */
1825  for(i=0; i<nCol; i++){
1826  aiTypes[i] = x = sqlite3_column_type(pStmt, i);
1827  if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
1828  azVals[i] = "";
1829  }else{
1830  azVals[i] = (char*)sqlite3_column_text(pStmt, i);
1831  }
1832  if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
1833  rc = SQLITE_NOMEM;
1834  break; /* from for */
1835  }
1836  } /* end for */
1837 
1838  /* if data and types extracted successfully... */
1839  if( SQLITE_ROW == rc ){
1840  /* call the supplied callback with the result row data */
1841  if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
1842  rc = SQLITE_ABORT;
1843  }else{
1844  rc = sqlite3_step(pStmt);
1845  }
1846  }
1847  } while( SQLITE_ROW == rc );
1848  sqlite3_free(pData);
1849  }
1850  }else{
1851  do{
1852  rc = sqlite3_step(pStmt);
1853  } while( rc == SQLITE_ROW );
1854  }
1855  }
1856 }
1857 
1858 /*
1859 ** Execute a statement or set of statements. Print
1860 ** any result rows/columns depending on the current mode
1861 ** set via the supplied callback.
1862 **
1863 ** This is very similar to SQLite's built-in sqlite3_exec()
1864 ** function except it takes a slightly different callback
1865 ** and callback data argument.
1866 */
1867 static int shell_exec(
1868  sqlite3 *db, /* An open database */
1869  const char *zSql, /* SQL to be evaluated */
1870  int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
1871  /* (not the same as sqlite3_exec) */
1872  ShellState *pArg, /* Pointer to ShellState */
1873  char **pzErrMsg /* Error msg written here */
1874 ){
1875  sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
1876  int rc = SQLITE_OK; /* Return Code */
1877  int rc2;
1878  const char *zLeftover; /* Tail of unprocessed SQL */
1879 
1880  if( pzErrMsg ){
1881  *pzErrMsg = NULL;
1882  }
1883 
1884  while( zSql[0] && (SQLITE_OK == rc) ){
1885  static const char *zStmtSql;
1886  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
1887  if( SQLITE_OK != rc ){
1888  if( pzErrMsg ){
1889  *pzErrMsg = save_err_msg(db);
1890  }
1891  }else{
1892  if( !pStmt ){
1893  /* this happens for a comment or white-space */
1894  zSql = zLeftover;
1895  while( IsSpace(zSql[0]) ) zSql++;
1896  continue;
1897  }
1898  zStmtSql = sqlite3_sql(pStmt);
1899  while( IsSpace(zStmtSql[0]) ) zStmtSql++;
1900 
1901  /* save off the prepared statment handle and reset row count */
1902  if( pArg ){
1903  pArg->pStmt = pStmt;
1904  pArg->cnt = 0;
1905  }
1906 
1907  /* echo the sql statement if echo on */
1908  if( pArg && pArg->echoOn ){
1909  utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
1910  }
1911 
1912  /* Show the EXPLAIN QUERY PLAN if .eqp is on */
1913  if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
1914  sqlite3_stmt *pExplain;
1915  char *zEQP;
1917  zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
1918  rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
1919  if( rc==SQLITE_OK ){
1920  while( sqlite3_step(pExplain)==SQLITE_ROW ){
1921  raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
1922  raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
1923  raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
1924  utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
1925  }
1926  }
1927  sqlite3_finalize(pExplain);
1928  sqlite3_free(zEQP);
1929  if( pArg->autoEQP>=2 ){
1930  /* Also do an EXPLAIN for ".eqp full" mode */
1931  zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
1932  rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
1933  if( rc==SQLITE_OK ){
1934  pArg->cMode = MODE_Explain;
1935  explain_data_prepare(pArg, pExplain);
1936  exec_prepared_stmt(pArg, pExplain, xCallback);
1937  explain_data_delete(pArg);
1938  }
1939  sqlite3_finalize(pExplain);
1940  sqlite3_free(zEQP);
1941  }
1943  }
1944 
1945  if( pArg ){
1946  pArg->cMode = pArg->mode;
1947  if( pArg->autoExplain
1948  && sqlite3_column_count(pStmt)==8
1949  && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
1950  ){
1951  pArg->cMode = MODE_Explain;
1952  }
1953 
1954  /* If the shell is currently in ".explain" mode, gather the extra
1955  ** data required to add indents to the output.*/
1956  if( pArg->cMode==MODE_Explain ){
1957  explain_data_prepare(pArg, pStmt);
1958  }
1959  }
1960 
1961  exec_prepared_stmt(pArg, pStmt, xCallback);
1962  explain_data_delete(pArg);
1963 
1964  /* print usage stats if stats on */
1965  if( pArg && pArg->statsOn ){
1966  display_stats(db, pArg, 0);
1967  }
1968 
1969  /* print loop-counters if required */
1970  if( pArg && pArg->scanstatsOn ){
1971  display_scanstats(db, pArg);
1972  }
1973 
1974  /* Finalize the statement just executed. If this fails, save a
1975  ** copy of the error message. Otherwise, set zSql to point to the
1976  ** next statement to execute. */
1977  rc2 = sqlite3_finalize(pStmt);
1978  if( rc!=SQLITE_NOMEM ) rc = rc2;
1979  if( rc==SQLITE_OK ){
1980  zSql = zLeftover;
1981  while( IsSpace(zSql[0]) ) zSql++;
1982  }else if( pzErrMsg ){
1983  *pzErrMsg = save_err_msg(db);
1984  }
1985 
1986  /* clear saved stmt handle */
1987  if( pArg ){
1988  pArg->pStmt = NULL;
1989  }
1990  }
1991  } /* end while */
1992 
1993  return rc;
1994 }
1995 
1996 
1997 /*
1998 ** This is a different callback routine used for dumping the database.
1999 ** Each row received by this callback consists of a table name,
2000 ** the table type ("index" or "table") and SQL to create the table.
2001 ** This routine should print text sufficient to recreate the table.
2002 */
2003 static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
2004  int rc;
2005  const char *zTable;
2006  const char *zType;
2007  const char *zSql;
2008  const char *zPrepStmt = 0;
2009  ShellState *p = (ShellState *)pArg;
2010 
2011  UNUSED_PARAMETER(azCol);
2012  if( nArg!=3 ) return 1;
2013  zTable = azArg[0];
2014  zType = azArg[1];
2015  zSql = azArg[2];
2016 
2017  if( strcmp(zTable, "sqlite_sequence")==0 ){
2018  zPrepStmt = "DELETE FROM sqlite_sequence;\n";
2019  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2020  raw_printf(p->out, "ANALYZE sqlite_master;\n");
2021  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2022  return 0;
2023  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2024  char *zIns;
2025  if( !p->writableSchema ){
2026  raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2027  p->writableSchema = 1;
2028  }
2029  zIns = sqlite3_mprintf(
2030  "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2031  "VALUES('table','%q','%q',0,'%q');",
2032  zTable, zTable, zSql);
2033  utf8_printf(p->out, "%s\n", zIns);
2034  sqlite3_free(zIns);
2035  return 0;
2036  }else{
2037  utf8_printf(p->out, "%s;\n", zSql);
2038  }
2039 
2040  if( strcmp(zType, "table")==0 ){
2041  sqlite3_stmt *pTableInfo = 0;
2042  char *zSelect = 0;
2043  char *zTableInfo = 0;
2044  char *zTmp = 0;
2045  int nRow = 0;
2046 
2047  zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
2048  zTableInfo = appendText(zTableInfo, zTable, '"');
2049  zTableInfo = appendText(zTableInfo, ");", 0);
2050 
2051  rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0);
2052  free(zTableInfo);
2053  if( rc!=SQLITE_OK || !pTableInfo ){
2054  return 1;
2055  }
2056 
2057  zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
2058  /* Always quote the table name, even if it appears to be pure ascii,
2059  ** in case it is a keyword. Ex: INSERT INTO "table" ... */
2060  zTmp = appendText(zTmp, zTable, '"');
2061  if( zTmp ){
2062  zSelect = appendText(zSelect, zTmp, '\'');
2063  free(zTmp);
2064  }
2065  zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
2066  rc = sqlite3_step(pTableInfo);
2067  while( rc==SQLITE_ROW ){
2068  const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
2069  zSelect = appendText(zSelect, "quote(", 0);
2070  zSelect = appendText(zSelect, zText, '"');
2071  rc = sqlite3_step(pTableInfo);
2072  if( rc==SQLITE_ROW ){
2073  zSelect = appendText(zSelect, "), ", 0);
2074  }else{
2075  zSelect = appendText(zSelect, ") ", 0);
2076  }
2077  nRow++;
2078  }
2079  rc = sqlite3_finalize(pTableInfo);
2080  if( rc!=SQLITE_OK || nRow==0 ){
2081  free(zSelect);
2082  return 1;
2083  }
2084  zSelect = appendText(zSelect, "|| ')' FROM ", 0);
2085  zSelect = appendText(zSelect, zTable, '"');
2086 
2087  rc = run_table_dump_query(p, zSelect, zPrepStmt);
2088  if( rc==SQLITE_CORRUPT ){
2089  zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
2090  run_table_dump_query(p, zSelect, 0);
2091  }
2092  free(zSelect);
2093  }
2094  return 0;
2095 }
2096 
2097 /*
2098 ** Run zQuery. Use dump_callback() as the callback routine so that
2099 ** the contents of the query are output as SQL statements.
2100 **
2101 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
2102 ** "ORDER BY rowid DESC" to the end.
2103 */
2105  ShellState *p,
2106  const char *zQuery
2107 ){
2108  int rc;
2109  char *zErr = 0;
2110  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
2111  if( rc==SQLITE_CORRUPT ){
2112  char *zQ2;
2113  int len = strlen30(zQuery);
2114  raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2115  if( zErr ){
2116  utf8_printf(p->out, "/****** %s ******/\n", zErr);
2117  sqlite3_free(zErr);
2118  zErr = 0;
2119  }
2120  zQ2 = malloc( len+100 );
2121  if( zQ2==0 ) return rc;
2122  sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
2123  rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
2124  if( rc ){
2125  utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
2126  }else{
2127  rc = SQLITE_CORRUPT;
2128  }
2129  sqlite3_free(zErr);
2130  free(zQ2);
2131  }
2132  return rc;
2133 }
2134 
2135 /*
2136 ** Text of a help message
2137 */
2138 static char zHelp[] =
2139 #ifndef SQLITE_OMIT_AUTHORIZATION
2140  ".auth ON|OFF Show authorizer callbacks\n"
2141 #endif
2142  ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
2143  ".bail on|off Stop after hitting an error. Default OFF\n"
2144  ".binary on|off Turn binary output on or off. Default OFF\n"
2145  ".changes on|off Show number of rows changed by SQL\n"
2146  ".check GLOB Fail if output since .testcase does not match\n"
2147  ".clone NEWDB Clone data into NEWDB from the existing database\n"
2148  ".databases List names and files of attached databases\n"
2149  ".dbinfo ?DB? Show status information about the database\n"
2150  ".dump ?TABLE? ... Dump the database in an SQL text format\n"
2151  " If TABLE specified, only dump tables matching\n"
2152  " LIKE pattern TABLE.\n"
2153  ".echo on|off Turn command echo on or off\n"
2154  ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
2155  ".exit Exit this program\n"
2156  ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
2157  ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
2158  ".headers on|off Turn display of headers on or off\n"
2159  ".help Show this message\n"
2160  ".import FILE TABLE Import data from FILE into TABLE\n"
2161  ".indexes ?TABLE? Show names of all indexes\n"
2162  " If TABLE specified, only show indexes for tables\n"
2163  " matching LIKE pattern TABLE.\n"
2164 #ifdef SQLITE_ENABLE_IOTRACE
2165  ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
2166 #endif
2167  ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
2168 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2169  ".load FILE ?ENTRY? Load an extension library\n"
2170 #endif
2171  ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
2172  ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
2173  " ascii Columns/rows delimited by 0x1F and 0x1E\n"
2174  " csv Comma-separated values\n"
2175  " column Left-aligned columns. (See .width)\n"
2176  " html HTML <table> code\n"
2177  " insert SQL insert statements for TABLE\n"
2178  " line One value per line\n"
2179  " list Values delimited by .separator strings\n"
2180  " tabs Tab-separated values\n"
2181  " tcl TCL list elements\n"
2182  ".nullvalue STRING Use STRING in place of NULL values\n"
2183  ".once FILENAME Output for the next SQL command only to FILENAME\n"
2184  ".open ?--new? ?FILE? Close existing database and reopen FILE\n"
2185  " The --new starts with an empty file\n"
2186  ".output ?FILENAME? Send output to FILENAME or stdout\n"
2187  ".print STRING... Print literal STRING\n"
2188  ".prompt MAIN CONTINUE Replace the standard prompts\n"
2189  ".quit Exit this program\n"
2190  ".read FILENAME Execute SQL in FILENAME\n"
2191  ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
2192  ".save FILE Write in-memory database into FILE\n"
2193  ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
2194  ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
2195  " Add --indent for pretty-printing\n"
2196  ".separator COL ?ROW? Change the column separator and optionally the row\n"
2197  " separator for both the output mode and .import\n"
2198 #if defined(SQLITE_ENABLE_SESSION)
2199  ".session CMD ... Create or control sessions\n"
2200 #endif
2201  ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
2202  ".show Show the current values for various settings\n"
2203  ".stats ?on|off? Show stats or turn stats on or off\n"
2204  ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
2205  ".tables ?TABLE? List names of tables\n"
2206  " If TABLE specified, only list tables matching\n"
2207  " LIKE pattern TABLE.\n"
2208  ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
2209  ".timeout MS Try opening locked tables for MS milliseconds\n"
2210  ".timer on|off Turn SQL timer on or off\n"
2211  ".trace FILE|off Output each SQL statement as it is run\n"
2212  ".vfsinfo ?AUX? Information about the top-level VFS\n"
2213  ".vfslist List all available VFSes\n"
2214  ".vfsname ?AUX? Print the name of the VFS stack\n"
2215  ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
2216  " Negative values right-justify\n"
2217 ;
2218 
2219 #if defined(SQLITE_ENABLE_SESSION)
2220 /*
2221 ** Print help information for the ".sessions" command
2222 */
2223 void session_help(ShellState *p){
2224  raw_printf(p->out,
2225  ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
2226  "If ?NAME? is omitted, the first defined session is used.\n"
2227  "Subcommands:\n"
2228  " attach TABLE Attach TABLE\n"
2229  " changeset FILE Write a changeset into FILE\n"
2230  " close Close one session\n"
2231  " enable ?BOOLEAN? Set or query the enable bit\n"
2232  " filter GLOB... Reject tables matching GLOBs\n"
2233  " indirect ?BOOLEAN? Mark or query the indirect status\n"
2234  " isempty Query whether the session is empty\n"
2235  " list List currently open session names\n"
2236  " open DB NAME Open a new session on DB\n"
2237  " patchset FILE Write a patchset into FILE\n"
2238  );
2239 }
2240 #endif
2241 
2242 
2243 /* Forward reference */
2244 static int process_input(ShellState *p, FILE *in);
2245 
2246 
2247 /*
2248 ** Read the content of a file into memory obtained from sqlite3_malloc64().
2249 ** The caller is responsible for freeing the memory.
2250 **
2251 ** NULL is returned if any error is encountered.
2252 */
2253 static char *readFile(const char *zName){
2254  FILE *in = fopen(zName, "rb");
2255  long nIn;
2256  size_t nRead;
2257  char *pBuf;
2258  if( in==0 ) return 0;
2259  fseek(in, 0, SEEK_END);
2260  nIn = ftell(in);
2261  rewind(in);
2262  pBuf = sqlite3_malloc64( nIn+1 );
2263  if( pBuf==0 ) return 0;
2264  nRead = fread(pBuf, nIn, 1, in);
2265  fclose(in);
2266  if( nRead!=1 ){
2267  sqlite3_free(pBuf);
2268  return 0;
2269  }
2270  pBuf[nIn] = 0;
2271  return pBuf;
2272 }
2273 
2274 /*
2275 ** Implementation of the "readfile(X)" SQL function. The entire content
2276 ** of the file named X is read and returned as a BLOB. NULL is returned
2277 ** if the file does not exist or is unreadable.
2278 */
2279 static void readfileFunc(
2280  sqlite3_context *context,
2281  int argc,
2282  sqlite3_value **argv
2283 ){
2284  const char *zName;
2285  void *pBuf;
2286 
2287  UNUSED_PARAMETER(argc);
2288  zName = (const char*)sqlite3_value_text(argv[0]);
2289  if( zName==0 ) return;
2290  pBuf = readFile(zName);
2291  if( pBuf ) sqlite3_result_blob(context, pBuf, -1, sqlite3_free);
2292 }
2293 
2294 /*
2295 ** Implementation of the "writefile(X,Y)" SQL function. The argument Y
2296 ** is written into file X. The number of bytes written is returned. Or
2297 ** NULL is returned if something goes wrong, such as being unable to open
2298 ** file X for writing.
2299 */
2300 static void writefileFunc(
2301  sqlite3_context *context,
2302  int argc,
2303  sqlite3_value **argv
2304 ){
2305  FILE *out;
2306  const char *z;
2307  sqlite3_int64 rc;
2308  const char *zFile;
2309 
2310  UNUSED_PARAMETER(argc);
2311  zFile = (const char*)sqlite3_value_text(argv[0]);
2312  if( zFile==0 ) return;
2313  out = fopen(zFile, "wb");
2314  if( out==0 ) return;
2315  z = (const char*)sqlite3_value_blob(argv[1]);
2316  if( z==0 ){
2317  rc = 0;
2318  }else{
2319  rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
2320  }
2321  fclose(out);
2322  sqlite3_result_int64(context, rc);
2323 }
2324 
2325 #if defined(SQLITE_ENABLE_SESSION)
2326 /*
2327 ** Close a single OpenSession object and release all of its associated
2328 ** resources.
2329 */
2330 static void session_close(OpenSession *pSession){
2331  int i;
2332  sqlite3session_delete(pSession->p);
2333  sqlite3_free(pSession->zName);
2334  for(i=0; i<pSession->nFilter; i++){
2335  sqlite3_free(pSession->azFilter[i]);
2336  }
2337  sqlite3_free(pSession->azFilter);
2338  memset(pSession, 0, sizeof(OpenSession));
2339 }
2340 #endif
2341 
2342 /*
2343 ** Close all OpenSession objects and release all associated resources.
2344 */
2345 #if defined(SQLITE_ENABLE_SESSION)
2346 static void session_close_all(ShellState *p){
2347  int i;
2348  for(i=0; i<p->nSession; i++){
2349  session_close(&p->aSession[i]);
2350  }
2351  p->nSession = 0;
2352 }
2353 #else
2354 # define session_close_all(X)
2355 #endif
2356 
2357 /*
2358 ** Implementation of the xFilter function for an open session. Omit
2359 ** any tables named by ".session filter" but let all other table through.
2360 */
2361 #if defined(SQLITE_ENABLE_SESSION)
2362 static int session_filter(void *pCtx, const char *zTab){
2363  OpenSession *pSession = (OpenSession*)pCtx;
2364  int i;
2365  for(i=0; i<pSession->nFilter; i++){
2366  if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
2367  }
2368  return 1;
2369 }
2370 #endif
2371 
2372 /*
2373 ** Make sure the database is open. If it is not, then open it. If
2374 ** the database fails to open, print an error message and exit.
2375 */
2376 static void open_db(ShellState *p, int keepAlive){
2377  if( p->db==0 ){
2379  sqlite3_open(p->zDbFilename, &p->db);
2380  globalDb = p->db;
2381  if( p->db && sqlite3_errcode(p->db)==SQLITE_OK ){
2382  sqlite3_create_function(p->db, "shellstatic", 0, SQLITE_UTF8, 0,
2383  shellstaticFunc, 0, 0);
2384  }
2385  if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
2386  utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
2387  p->zDbFilename, sqlite3_errmsg(p->db));
2388  if( keepAlive ) return;
2389  exit(1);
2390  }
2391 #ifndef SQLITE_OMIT_LOAD_EXTENSION
2393 #endif
2394  sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
2395  readfileFunc, 0, 0);
2396  sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
2397  writefileFunc, 0, 0);
2398  }
2399 }
2400 
2401 /*
2402 ** Do C-language style dequoting.
2403 **
2404 ** \a -> alarm
2405 ** \b -> backspace
2406 ** \t -> tab
2407 ** \n -> newline
2408 ** \v -> vertical tab
2409 ** \f -> form feed
2410 ** \r -> carriage return
2411 ** \s -> space
2412 ** \" -> "
2413 ** \' -> '
2414 ** \\ -> backslash
2415 ** \NNN -> ascii character NNN in octal
2416 */
2417 static void resolve_backslashes(char *z){
2418  int i, j;
2419  char c;
2420  while( *z && *z!='\\' ) z++;
2421  for(i=j=0; (c = z[i])!=0; i++, j++){
2422  if( c=='\\' && z[i+1]!=0 ){
2423  c = z[++i];
2424  if( c=='a' ){
2425  c = '\a';
2426  }else if( c=='b' ){
2427  c = '\b';
2428  }else if( c=='t' ){
2429  c = '\t';
2430  }else if( c=='n' ){
2431  c = '\n';
2432  }else if( c=='v' ){
2433  c = '\v';
2434  }else if( c=='f' ){
2435  c = '\f';
2436  }else if( c=='r' ){
2437  c = '\r';
2438  }else if( c=='"' ){
2439  c = '"';
2440  }else if( c=='\'' ){
2441  c = '\'';
2442  }else if( c=='\\' ){
2443  c = '\\';
2444  }else if( c>='0' && c<='7' ){
2445  c -= '0';
2446  if( z[i+1]>='0' && z[i+1]<='7' ){
2447  i++;
2448  c = (c<<3) + z[i] - '0';
2449  if( z[i+1]>='0' && z[i+1]<='7' ){
2450  i++;
2451  c = (c<<3) + z[i] - '0';
2452  }
2453  }
2454  }
2455  }
2456  z[j] = c;
2457  }
2458  if( j<i ) z[j] = 0;
2459 }
2460 
2461 /*
2462 ** Return the value of a hexadecimal digit. Return -1 if the input
2463 ** is not a hex digit.
2464 */
2465 static int hexDigitValue(char c){
2466  if( c>='0' && c<='9' ) return c - '0';
2467  if( c>='a' && c<='f' ) return c - 'a' + 10;
2468  if( c>='A' && c<='F' ) return c - 'A' + 10;
2469  return -1;
2470 }
2471 
2472 /*
2473 ** Interpret zArg as an integer value, possibly with suffixes.
2474 */
2475 static sqlite3_int64 integerValue(const char *zArg){
2476  sqlite3_int64 v = 0;
2477  static const struct { char *zSuffix; int iMult; } aMult[] = {
2478  { "KiB", 1024 },
2479  { "MiB", 1024*1024 },
2480  { "GiB", 1024*1024*1024 },
2481  { "KB", 1000 },
2482  { "MB", 1000000 },
2483  { "GB", 1000000000 },
2484  { "K", 1000 },
2485  { "M", 1000000 },
2486  { "G", 1000000000 },
2487  };
2488  int i;
2489  int isNeg = 0;
2490  if( zArg[0]=='-' ){
2491  isNeg = 1;
2492  zArg++;
2493  }else if( zArg[0]=='+' ){
2494  zArg++;
2495  }
2496  if( zArg[0]=='0' && zArg[1]=='x' ){
2497  int x;
2498  zArg += 2;
2499  while( (x = hexDigitValue(zArg[0]))>=0 ){
2500  v = (v<<4) + x;
2501  zArg++;
2502  }
2503  }else{
2504  while( IsDigit(zArg[0]) ){
2505  v = v*10 + zArg[0] - '0';
2506  zArg++;
2507  }
2508  }
2509  for(i=0; i<ArraySize(aMult); i++){
2510  if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
2511  v *= aMult[i].iMult;
2512  break;
2513  }
2514  }
2515  return isNeg? -v : v;
2516 }
2517 
2518 /*
2519 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
2520 ** for TRUE and FALSE. Return the integer value if appropriate.
2521 */
2522 static int booleanValue(char *zArg){
2523  int i;
2524  if( zArg[0]=='0' && zArg[1]=='x' ){
2525  for(i=2; hexDigitValue(zArg[i])>=0; i++){}
2526  }else{
2527  for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
2528  }
2529  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
2530  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
2531  return 1;
2532  }
2533  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
2534  return 0;
2535  }
2536  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
2537  zArg);
2538  return 0;
2539 }
2540 
2541 /*
2542 ** Close an output file, assuming it is not stderr or stdout
2543 */
2544 static void output_file_close(FILE *f){
2545  if( f && f!=stdout && f!=stderr ) fclose(f);
2546 }
2547 
2548 /*
2549 ** Try to open an output file. The names "stdout" and "stderr" are
2550 ** recognized and do the right thing. NULL is returned if the output
2551 ** filename is "off".
2552 */
2553 static FILE *output_file_open(const char *zFile){
2554  FILE *f;
2555  if( strcmp(zFile,"stdout")==0 ){
2556  f = stdout;
2557  }else if( strcmp(zFile, "stderr")==0 ){
2558  f = stderr;
2559  }else if( strcmp(zFile, "off")==0 ){
2560  f = 0;
2561  }else{
2562  f = fopen(zFile, "wb");
2563  if( f==0 ){
2564  utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
2565  }
2566  }
2567  return f;
2568 }
2569 
2570 /*
2571 ** A routine for handling output from sqlite3_trace().
2572 */
2574  unsigned mType,
2575  void *pArg,
2576  void *pP,
2577  void *pX
2578 ){
2579  FILE *f = (FILE*)pArg;
2580  UNUSED_PARAMETER(mType);
2581  UNUSED_PARAMETER(pP);
2582  if( f ){
2583  const char *z = (const char*)pX;
2584  int i = (int)strlen(z);
2585  while( i>0 && z[i-1]==';' ){ i--; }
2586  utf8_printf(f, "%.*s;\n", i, z);
2587  }
2588  return 0;
2589 }
2590 
2591 /*
2592 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
2593 ** a useful spot to set a debugger breakpoint.
2594 */
2595 static void test_breakpoint(void){
2596  static int nCall = 0;
2597  nCall++;
2598 }
2599 
2600 /*
2601 ** An object used to read a CSV and other files for import.
2602 */
2603 typedef struct ImportCtx ImportCtx;
2604 struct ImportCtx {
2605  const char *zFile; /* Name of the input file */
2606  FILE *in; /* Read the CSV text from this input stream */
2607  char *z; /* Accumulated text for a field */
2608  int n; /* Number of bytes in z */
2609  int nAlloc; /* Space allocated for z[] */
2610  int nLine; /* Current line number */
2611  int cTerm; /* Character that terminated the most recent field */
2612  int cColSep; /* The column separator character. (Usually ",") */
2613  int cRowSep; /* The row separator character. (Usually "\n") */
2614 };
2615 
2616 /* Append a single byte to z[] */
2617 static void import_append_char(ImportCtx *p, int c){
2618  if( p->n+1>=p->nAlloc ){
2619  p->nAlloc += p->nAlloc + 100;
2620  p->z = sqlite3_realloc64(p->z, p->nAlloc);
2621  if( p->z==0 ){
2622  raw_printf(stderr, "out of memory\n");
2623  exit(1);
2624  }
2625  }
2626  p->z[p->n++] = (char)c;
2627 }
2628 
2629 /* Read a single field of CSV text. Compatible with rfc4180 and extended
2630 ** with the option of having a separator other than ",".
2631 **
2632 ** + Input comes from p->in.
2633 ** + Store results in p->z of length p->n. Space to hold p->z comes
2634 ** from sqlite3_malloc64().
2635 ** + Use p->cSep as the column separator. The default is ",".
2636 ** + Use p->rSep as the row separator. The default is "\n".
2637 ** + Keep track of the line number in p->nLine.
2638 ** + Store the character that terminates the field in p->cTerm. Store
2639 ** EOF on end-of-file.
2640 ** + Report syntax errors on stderr
2641 */
2643  int c;
2644  int cSep = p->cColSep;
2645  int rSep = p->cRowSep;
2646  p->n = 0;
2647  c = fgetc(p->in);
2648  if( c==EOF || seenInterrupt ){
2649  p->cTerm = EOF;
2650  return 0;
2651  }
2652  if( c=='"' ){
2653  int pc, ppc;
2654  int startLine = p->nLine;
2655  int cQuote = c;
2656  pc = ppc = 0;
2657  while( 1 ){
2658  c = fgetc(p->in);
2659  if( c==rSep ) p->nLine++;
2660  if( c==cQuote ){
2661  if( pc==cQuote ){
2662  pc = 0;
2663  continue;
2664  }
2665  }
2666  if( (c==cSep && pc==cQuote)
2667  || (c==rSep && pc==cQuote)
2668  || (c==rSep && pc=='\r' && ppc==cQuote)
2669  || (c==EOF && pc==cQuote)
2670  ){
2671  do{ p->n--; }while( p->z[p->n]!=cQuote );
2672  p->cTerm = c;
2673  break;
2674  }
2675  if( pc==cQuote && c!='\r' ){
2676  utf8_printf(stderr, "%s:%d: unescaped %c character\n",
2677  p->zFile, p->nLine, cQuote);
2678  }
2679  if( c==EOF ){
2680  utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
2681  p->zFile, startLine, cQuote);
2682  p->cTerm = c;
2683  break;
2684  }
2685  import_append_char(p, c);
2686  ppc = pc;
2687  pc = c;
2688  }
2689  }else{
2690  while( c!=EOF && c!=cSep && c!=rSep ){
2691  import_append_char(p, c);
2692  c = fgetc(p->in);
2693  }
2694  if( c==rSep ){
2695  p->nLine++;
2696  if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
2697  }
2698  p->cTerm = c;
2699  }
2700  if( p->z ) p->z[p->n] = 0;
2701  return p->z;
2702 }
2703 
2704 /* Read a single field of ASCII delimited text.
2705 **
2706 ** + Input comes from p->in.
2707 ** + Store results in p->z of length p->n. Space to hold p->z comes
2708 ** from sqlite3_malloc64().
2709 ** + Use p->cSep as the column separator. The default is "\x1F".
2710 ** + Use p->rSep as the row separator. The default is "\x1E".
2711 ** + Keep track of the row number in p->nLine.
2712 ** + Store the character that terminates the field in p->cTerm. Store
2713 ** EOF on end-of-file.
2714 ** + Report syntax errors on stderr
2715 */
2717  int c;
2718  int cSep = p->cColSep;
2719  int rSep = p->cRowSep;
2720  p->n = 0;
2721  c = fgetc(p->in);
2722  if( c==EOF || seenInterrupt ){
2723  p->cTerm = EOF;
2724  return 0;
2725  }
2726  while( c!=EOF && c!=cSep && c!=rSep ){
2727  import_append_char(p, c);
2728  c = fgetc(p->in);
2729  }
2730  if( c==rSep ){
2731  p->nLine++;
2732  }
2733  p->cTerm = c;
2734  if( p->z ) p->z[p->n] = 0;
2735  return p->z;
2736 }
2737 
2738 /*
2739 ** Try to transfer data for table zTable. If an error is seen while
2740 ** moving forward, try to go backwards. The backwards movement won't
2741 ** work for WITHOUT ROWID tables.
2742 */
2743 static void tryToCloneData(
2744  ShellState *p,
2745  sqlite3 *newDb,
2746  const char *zTable
2747 ){
2748  sqlite3_stmt *pQuery = 0;
2749  sqlite3_stmt *pInsert = 0;
2750  char *zQuery = 0;
2751  char *zInsert = 0;
2752  int rc;
2753  int i, j, n;
2754  int nTable = (int)strlen(zTable);
2755  int k = 0;
2756  int cnt = 0;
2757  const int spinRate = 10000;
2758 
2759  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
2760  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
2761  if( rc ){
2762  utf8_printf(stderr, "Error %d: %s on [%s]\n",
2764  zQuery);
2765  goto end_data_xfer;
2766  }
2767  n = sqlite3_column_count(pQuery);
2768  zInsert = sqlite3_malloc64(200 + nTable + n*3);
2769  if( zInsert==0 ){
2770  raw_printf(stderr, "out of memory\n");
2771  goto end_data_xfer;
2772  }
2773  sqlite3_snprintf(200+nTable,zInsert,
2774  "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
2775  i = (int)strlen(zInsert);
2776  for(j=1; j<n; j++){
2777  memcpy(zInsert+i, ",?", 2);
2778  i += 2;
2779  }
2780  memcpy(zInsert+i, ");", 3);
2781  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
2782  if( rc ){
2783  utf8_printf(stderr, "Error %d: %s on [%s]\n",
2785  zQuery);
2786  goto end_data_xfer;
2787  }
2788  for(k=0; k<2; k++){
2789  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
2790  for(i=0; i<n; i++){
2791  switch( sqlite3_column_type(pQuery, i) ){
2792  case SQLITE_NULL: {
2793  sqlite3_bind_null(pInsert, i+1);
2794  break;
2795  }
2796  case SQLITE_INTEGER: {
2797  sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
2798  break;
2799  }
2800  case SQLITE_FLOAT: {
2801  sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
2802  break;
2803  }
2804  case SQLITE_TEXT: {
2805  sqlite3_bind_text(pInsert, i+1,
2806  (const char*)sqlite3_column_text(pQuery,i),
2807  -1, SQLITE_STATIC);
2808  break;
2809  }
2810  case SQLITE_BLOB: {
2811  sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
2812  sqlite3_column_bytes(pQuery,i),
2813  SQLITE_STATIC);
2814  break;
2815  }
2816  }
2817  } /* End for */
2818  rc = sqlite3_step(pInsert);
2819  if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
2820  utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
2821  sqlite3_errmsg(newDb));
2822  }
2823  sqlite3_reset(pInsert);
2824  cnt++;
2825  if( (cnt%spinRate)==0 ){
2826  printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
2827  fflush(stdout);
2828  }
2829  } /* End while */
2830  if( rc==SQLITE_DONE ) break;
2831  sqlite3_finalize(pQuery);
2832  sqlite3_free(zQuery);
2833  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
2834  zTable);
2835  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
2836  if( rc ){
2837  utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
2838  break;
2839  }
2840  } /* End for(k=0...) */
2841 
2842 end_data_xfer:
2843  sqlite3_finalize(pQuery);
2844  sqlite3_finalize(pInsert);
2845  sqlite3_free(zQuery);
2846  sqlite3_free(zInsert);
2847 }
2848 
2849 
2850 /*
2851 ** Try to transfer all rows of the schema that match zWhere. For
2852 ** each row, invoke xForEach() on the object defined by that row.
2853 ** If an error is encountered while moving forward through the
2854 ** sqlite_master table, try again moving backwards.
2855 */
2856 static void tryToCloneSchema(
2857  ShellState *p,
2858  sqlite3 *newDb,
2859  const char *zWhere,
2860  void (*xForEach)(ShellState*,sqlite3*,const char*)
2861 ){
2862  sqlite3_stmt *pQuery = 0;
2863  char *zQuery = 0;
2864  int rc;
2865  const unsigned char *zName;
2866  const unsigned char *zSql;
2867  char *zErrMsg = 0;
2868 
2869  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
2870  " WHERE %s", zWhere);
2871  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
2872  if( rc ){
2873  utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
2875  zQuery);
2876  goto end_schema_xfer;
2877  }
2878  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
2879  zName = sqlite3_column_text(pQuery, 0);
2880  zSql = sqlite3_column_text(pQuery, 1);
2881  printf("%s... ", zName); fflush(stdout);
2882  sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
2883  if( zErrMsg ){
2884  utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
2885  sqlite3_free(zErrMsg);
2886  zErrMsg = 0;
2887  }
2888  if( xForEach ){
2889  xForEach(p, newDb, (const char*)zName);
2890  }
2891  printf("done\n");
2892  }
2893  if( rc!=SQLITE_DONE ){
2894  sqlite3_finalize(pQuery);
2895  sqlite3_free(zQuery);
2896  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
2897  " WHERE %s ORDER BY rowid DESC", zWhere);
2898  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
2899  if( rc ){
2900  utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
2902  zQuery);
2903  goto end_schema_xfer;
2904  }
2905  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
2906  zName = sqlite3_column_text(pQuery, 0);
2907  zSql = sqlite3_column_text(pQuery, 1);
2908  printf("%s... ", zName); fflush(stdout);
2909  sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
2910  if( zErrMsg ){
2911  utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
2912  sqlite3_free(zErrMsg);
2913  zErrMsg = 0;
2914  }
2915  if( xForEach ){
2916  xForEach(p, newDb, (const char*)zName);
2917  }
2918  printf("done\n");
2919  }
2920  }
2921 end_schema_xfer:
2922  sqlite3_finalize(pQuery);
2923  sqlite3_free(zQuery);
2924 }
2925 
2926 /*
2927 ** Open a new database file named "zNewDb". Try to recover as much information
2928 ** as possible out of the main database (which might be corrupt) and write it
2929 ** into zNewDb.
2930 */
2931 static void tryToClone(ShellState *p, const char *zNewDb){
2932  int rc;
2933  sqlite3 *newDb = 0;
2934  if( access(zNewDb,0)==0 ){
2935  utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
2936  return;
2937  }
2938  rc = sqlite3_open(zNewDb, &newDb);
2939  if( rc ){
2940  utf8_printf(stderr, "Cannot create output database: %s\n",
2941  sqlite3_errmsg(newDb));
2942  }else{
2943  sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
2944  sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
2945  tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
2946  tryToCloneSchema(p, newDb, "type!='table'", 0);
2947  sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
2948  sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
2949  }
2950  sqlite3_close(newDb);
2951 }
2952 
2953 /*
2954 ** Change the output file back to stdout
2955 */
2956 static void output_reset(ShellState *p){
2957  if( p->outfile[0]=='|' ){
2958 #ifndef SQLITE_OMIT_POPEN
2959  pclose(p->out);
2960 #endif
2961  }else{
2962  output_file_close(p->out);
2963  }
2964  p->outfile[0] = 0;
2965  p->out = stdout;
2966 }
2967 
2968 /*
2969 ** Run an SQL command and return the single integer result.
2970 */
2971 static int db_int(ShellState *p, const char *zSql){
2972  sqlite3_stmt *pStmt;
2973  int res = 0;
2974  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2975  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
2976  res = sqlite3_column_int(pStmt,0);
2977  }
2978  sqlite3_finalize(pStmt);
2979  return res;
2980 }
2981 
2982 /*
2983 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
2984 */
2985 static unsigned int get2byteInt(unsigned char *a){
2986  return (a[0]<<8) + a[1];
2987 }
2988 static unsigned int get4byteInt(unsigned char *a){
2989  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
2990 }
2991 
2992 /*
2993 ** Implementation of the ".info" command.
2994 **
2995 ** Return 1 on error, 2 to exit, and 0 otherwise.
2996 */
2997 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
2998  static const struct { const char *zName; int ofst; } aField[] = {
2999  { "file change counter:", 24 },
3000  { "database page count:", 28 },
3001  { "freelist page count:", 36 },
3002  { "schema cookie:", 40 },
3003  { "schema format:", 44 },
3004  { "default cache size:", 48 },
3005  { "autovacuum top root:", 52 },
3006  { "incremental vacuum:", 64 },
3007  { "text encoding:", 56 },
3008  { "user version:", 60 },
3009  { "application id:", 68 },
3010  { "software version:", 96 },
3011  };
3012  static const struct { const char *zName; const char *zSql; } aQuery[] = {
3013  { "number of tables:",
3014  "SELECT count(*) FROM %s WHERE type='table'" },
3015  { "number of indexes:",
3016  "SELECT count(*) FROM %s WHERE type='index'" },
3017  { "number of triggers:",
3018  "SELECT count(*) FROM %s WHERE type='trigger'" },
3019  { "number of views:",
3020  "SELECT count(*) FROM %s WHERE type='view'" },
3021  { "schema size:",
3022  "SELECT total(length(sql)) FROM %s" },
3023  };
3024  sqlite3_file *pFile = 0;
3025  int i;
3026  char *zSchemaTab;
3027  char *zDb = nArg>=2 ? azArg[1] : "main";
3028  unsigned char aHdr[100];
3029  open_db(p, 0);
3030  if( p->db==0 ) return 1;
3032  if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
3033  return 1;
3034  }
3035  i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
3036  if( i!=SQLITE_OK ){
3037  raw_printf(stderr, "unable to read database header\n");
3038  return 1;
3039  }
3040  i = get2byteInt(aHdr+16);
3041  if( i==1 ) i = 65536;
3042  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
3043  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
3044  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
3045  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
3046  for(i=0; i<ArraySize(aField); i++){
3047  int ofst = aField[i].ofst;
3048  unsigned int val = get4byteInt(aHdr + ofst);
3049  utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
3050  switch( ofst ){
3051  case 56: {
3052  if( val==1 ) raw_printf(p->out, " (utf8)");
3053  if( val==2 ) raw_printf(p->out, " (utf16le)");
3054  if( val==3 ) raw_printf(p->out, " (utf16be)");
3055  }
3056  }
3057  raw_printf(p->out, "\n");
3058  }
3059  if( zDb==0 ){
3060  zSchemaTab = sqlite3_mprintf("main.sqlite_master");
3061  }else if( strcmp(zDb,"temp")==0 ){
3062  zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
3063  }else{
3064  zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
3065  }
3066  for(i=0; i<ArraySize(aQuery); i++){
3067  char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
3068  int val = db_int(p, zSql);
3069  sqlite3_free(zSql);
3070  utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
3071  }
3072  sqlite3_free(zSchemaTab);
3073  return 0;
3074 }
3075 
3076 /*
3077 ** Print the current sqlite3_errmsg() value to stderr and return 1.
3078 */
3079 static int shellDatabaseError(sqlite3 *db){
3080  const char *zErr = sqlite3_errmsg(db);
3081  utf8_printf(stderr, "Error: %s\n", zErr);
3082  return 1;
3083 }
3084 
3085 /*
3086 ** Print an out-of-memory message to stderr and return 1.
3087 */
3088 static int shellNomemError(void){
3089  raw_printf(stderr, "Error: out of memory\n");
3090  return 1;
3091 }
3092 
3093 /*
3094 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
3095 ** if they match and FALSE (0) if they do not match.
3096 **
3097 ** Globbing rules:
3098 **
3099 ** '*' Matches any sequence of zero or more characters.
3100 **
3101 ** '?' Matches exactly one character.
3102 **
3103 ** [...] Matches one character from the enclosed list of
3104 ** characters.
3105 **
3106 ** [^...] Matches one character not in the enclosed list.
3107 **
3108 ** '#' Matches any sequence of one or more digits with an
3109 ** optional + or - sign in front
3110 **
3111 ** ' ' Any span of whitespace matches any other span of
3112 ** whitespace.
3113 **
3114 ** Extra whitespace at the end of z[] is ignored.
3115 */
3116 static int testcase_glob(const char *zGlob, const char *z){
3117  int c, c2;
3118  int invert;
3119  int seen;
3120 
3121  while( (c = (*(zGlob++)))!=0 ){
3122  if( IsSpace(c) ){
3123  if( !IsSpace(*z) ) return 0;
3124  while( IsSpace(*zGlob) ) zGlob++;
3125  while( IsSpace(*z) ) z++;
3126  }else if( c=='*' ){
3127  while( (c=(*(zGlob++))) == '*' || c=='?' ){
3128  if( c=='?' && (*(z++))==0 ) return 0;
3129  }
3130  if( c==0 ){
3131  return 1;
3132  }else if( c=='[' ){
3133  while( *z && testcase_glob(zGlob-1,z)==0 ){
3134  z++;
3135  }
3136  return (*z)!=0;
3137  }
3138  while( (c2 = (*(z++)))!=0 ){
3139  while( c2!=c ){
3140  c2 = *(z++);
3141  if( c2==0 ) return 0;
3142  }
3143  if( testcase_glob(zGlob,z) ) return 1;
3144  }
3145  return 0;
3146  }else if( c=='?' ){
3147  if( (*(z++))==0 ) return 0;
3148  }else if( c=='[' ){
3149  int prior_c = 0;
3150  seen = 0;
3151  invert = 0;
3152  c = *(z++);
3153  if( c==0 ) return 0;
3154  c2 = *(zGlob++);
3155  if( c2=='^' ){
3156  invert = 1;
3157  c2 = *(zGlob++);
3158  }
3159  if( c2==']' ){
3160  if( c==']' ) seen = 1;
3161  c2 = *(zGlob++);
3162  }
3163  while( c2 && c2!=']' ){
3164  if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
3165  c2 = *(zGlob++);
3166  if( c>=prior_c && c<=c2 ) seen = 1;
3167  prior_c = 0;
3168  }else{
3169  if( c==c2 ){
3170  seen = 1;
3171  }
3172  prior_c = c2;
3173  }
3174  c2 = *(zGlob++);
3175  }
3176  if( c2==0 || (seen ^ invert)==0 ) return 0;
3177  }else if( c=='#' ){
3178  if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
3179  if( !IsDigit(z[0]) ) return 0;
3180  z++;
3181  while( IsDigit(z[0]) ){ z++; }
3182  }else{
3183  if( c!=(*(z++)) ) return 0;
3184  }
3185  }
3186  while( IsSpace(*z) ){ z++; }
3187  return *z==0;
3188 }
3189 
3190 
3191 /*
3192 ** Compare the string as a command-line option with either one or two
3193 ** initial "-" characters.
3194 */
3195 static int optionMatch(const char *zStr, const char *zOpt){
3196  if( zStr[0]!='-' ) return 0;
3197  zStr++;
3198  if( zStr[0]=='-' ) zStr++;
3199  return strcmp(zStr, zOpt)==0;
3200 }
3201 
3202 /*
3203 ** Delete a file.
3204 */
3205 int shellDeleteFile(const char *zFilename){
3206  int rc;
3207 #ifdef _WIN32
3208  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
3209  rc = _wunlink(z);
3210  sqlite3_free(z);
3211 #else
3212  rc = unlink(zFilename);
3213 #endif
3214  return rc;
3215 }
3216 
3217 /*
3218 ** If an input line begins with "." then invoke this routine to
3219 ** process that line.
3220 **
3221 ** Return 1 on error, 2 to exit, and 0 otherwise.
3222 */
3223 static int do_meta_command(char *zLine, ShellState *p){
3224  int h = 1;
3225  int nArg = 0;
3226  int n, c;
3227  int rc = 0;
3228  char *azArg[50];
3229 
3230  /* Parse the input line into tokens.
3231  */
3232  while( zLine[h] && nArg<ArraySize(azArg) ){
3233  while( IsSpace(zLine[h]) ){ h++; }
3234  if( zLine[h]==0 ) break;
3235  if( zLine[h]=='\'' || zLine[h]=='"' ){
3236  int delim = zLine[h++];
3237  azArg[nArg++] = &zLine[h];
3238  while( zLine[h] && zLine[h]!=delim ){
3239  if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
3240  h++;
3241  }
3242  if( zLine[h]==delim ){
3243  zLine[h++] = 0;
3244  }
3245  if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
3246  }else{
3247  azArg[nArg++] = &zLine[h];
3248  while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
3249  if( zLine[h] ) zLine[h++] = 0;
3250  resolve_backslashes(azArg[nArg-1]);
3251  }
3252  }
3253 
3254  /* Process the input line.
3255  */
3256  if( nArg==0 ) return 0; /* no tokens, no error */
3257  n = strlen30(azArg[0]);
3258  c = azArg[0][0];
3259 
3260 #ifndef SQLITE_OMIT_AUTHORIZATION
3261  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
3262  if( nArg!=2 ){
3263  raw_printf(stderr, "Usage: .auth ON|OFF\n");
3264  rc = 1;
3265  goto meta_command_exit;
3266  }
3267  open_db(p, 0);
3268  if( booleanValue(azArg[1]) ){
3270  }else{
3271  sqlite3_set_authorizer(p->db, 0, 0);
3272  }
3273  }else
3274 #endif
3275 
3276  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
3277  || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
3278  ){
3279  const char *zDestFile = 0;
3280  const char *zDb = 0;
3281  sqlite3 *pDest;
3282  sqlite3_backup *pBackup;
3283  int j;
3284  for(j=1; j<nArg; j++){
3285  const char *z = azArg[j];
3286  if( z[0]=='-' ){
3287  while( z[0]=='-' ) z++;
3288  /* No options to process at this time */
3289  {
3290  utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
3291  return 1;
3292  }
3293  }else if( zDestFile==0 ){
3294  zDestFile = azArg[j];
3295  }else if( zDb==0 ){
3296  zDb = zDestFile;
3297  zDestFile = azArg[j];
3298  }else{
3299  raw_printf(stderr, "too many arguments to .backup\n");
3300  return 1;
3301  }
3302  }
3303  if( zDestFile==0 ){
3304  raw_printf(stderr, "missing FILENAME argument on .backup\n");
3305  return 1;
3306  }
3307  if( zDb==0 ) zDb = "main";
3308  rc = sqlite3_open(zDestFile, &pDest);
3309  if( rc!=SQLITE_OK ){
3310  utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
3311  sqlite3_close(pDest);
3312  return 1;
3313  }
3314  open_db(p, 0);
3315  pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
3316  if( pBackup==0 ){
3317  utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
3318  sqlite3_close(pDest);
3319  return 1;
3320  }
3321  while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
3322  sqlite3_backup_finish(pBackup);
3323  if( rc==SQLITE_DONE ){
3324  rc = 0;
3325  }else{
3326  utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
3327  rc = 1;
3328  }
3329  sqlite3_close(pDest);
3330  }else
3331 
3332  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
3333  if( nArg==2 ){
3334  bail_on_error = booleanValue(azArg[1]);
3335  }else{
3336  raw_printf(stderr, "Usage: .bail on|off\n");
3337  rc = 1;
3338  }
3339  }else
3340 
3341  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
3342  if( nArg==2 ){
3343  if( booleanValue(azArg[1]) ){
3344  setBinaryMode(p->out, 1);
3345  }else{
3346  setTextMode(p->out, 1);
3347  }
3348  }else{
3349  raw_printf(stderr, "Usage: .binary on|off\n");
3350  rc = 1;
3351  }
3352  }else
3353 
3354  /* The undocumented ".breakpoint" command causes a call to the no-op
3355  ** routine named test_breakpoint().
3356  */
3357  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
3358  test_breakpoint();
3359  }else
3360 
3361  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
3362  if( nArg==2 ){
3363  p->countChanges = booleanValue(azArg[1]);
3364  }else{
3365  raw_printf(stderr, "Usage: .changes on|off\n");
3366  rc = 1;
3367  }
3368  }else
3369 
3370  /* Cancel output redirection, if it is currently set (by .testcase)
3371  ** Then read the content of the testcase-out.txt file and compare against
3372  ** azArg[1]. If there are differences, report an error and exit.
3373  */
3374  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
3375  char *zRes = 0;
3376  output_reset(p);
3377  if( nArg!=2 ){
3378  raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
3379  rc = 2;
3380  }else if( (zRes = readFile("testcase-out.txt"))==0 ){
3381  raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
3382  rc = 2;
3383  }else if( testcase_glob(azArg[1],zRes)==0 ){
3384  utf8_printf(stderr,
3385  "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
3386  p->zTestcase, azArg[1], zRes);
3387  rc = 2;
3388  }else{
3389  utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
3390  p->nCheck++;
3391  }
3392  sqlite3_free(zRes);
3393  }else
3394 
3395  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
3396  if( nArg==2 ){
3397  tryToClone(p, azArg[1]);
3398  }else{
3399  raw_printf(stderr, "Usage: .clone FILENAME\n");
3400  rc = 1;
3401  }
3402  }else
3403 
3404  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
3405  ShellState data;
3406  char *zErrMsg = 0;
3407  open_db(p, 0);
3408  memcpy(&data, p, sizeof(data));
3409  data.showHeader = 1;
3410  data.cMode = data.mode = MODE_Column;
3411  data.colWidth[0] = 3;
3412  data.colWidth[1] = 15;
3413  data.colWidth[2] = 58;
3414  data.cnt = 0;
3415  sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
3416  if( zErrMsg ){
3417  utf8_printf(stderr,"Error: %s\n", zErrMsg);
3418  sqlite3_free(zErrMsg);
3419  rc = 1;
3420  }
3421  }else
3422 
3423  if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
3424  rc = shell_dbinfo_command(p, nArg, azArg);
3425  }else
3426 
3427  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
3428  open_db(p, 0);
3429  /* When playing back a "dump", the content might appear in an order
3430  ** which causes immediate foreign key constraints to be violated.
3431  ** So disable foreign-key constraint enforcement to prevent problems. */
3432  if( nArg!=1 && nArg!=2 ){
3433  raw_printf(stderr, "Usage: .dump ?LIKE-PATTERN?\n");
3434  rc = 1;
3435  goto meta_command_exit;
3436  }
3437  raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
3438  raw_printf(p->out, "BEGIN TRANSACTION;\n");
3439  p->writableSchema = 0;
3440  sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
3441  p->nErr = 0;
3442  if( nArg==1 ){
3444  "SELECT name, type, sql FROM sqlite_master "
3445  "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
3446  );
3448  "SELECT name, type, sql FROM sqlite_master "
3449  "WHERE name=='sqlite_sequence'"
3450  );
3452  "SELECT sql FROM sqlite_master "
3453  "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
3454  );
3455  }else{
3456  int i;
3457  for(i=1; i<nArg; i++){
3458  zShellStatic = azArg[i];
3460  "SELECT name, type, sql FROM sqlite_master "
3461  "WHERE tbl_name LIKE shellstatic() AND type=='table'"
3462  " AND sql NOT NULL");
3464  "SELECT sql FROM sqlite_master "
3465  "WHERE sql NOT NULL"
3466  " AND type IN ('index','trigger','view')"
3467  " AND tbl_name LIKE shellstatic()", 0
3468  );
3469  zShellStatic = 0;
3470  }
3471  }
3472  if( p->writableSchema ){
3473  raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
3474  p->writableSchema = 0;
3475  }
3476  sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
3477  sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
3478  raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
3479  }else
3480 
3481  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
3482  if( nArg==2 ){
3483  p->echoOn = booleanValue(azArg[1]);
3484  }else{
3485  raw_printf(stderr, "Usage: .echo on|off\n");
3486  rc = 1;
3487  }
3488  }else
3489 
3490  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
3491  if( nArg==2 ){
3492  if( strcmp(azArg[1],"full")==0 ){
3493  p->autoEQP = 2;
3494  }else{
3495  p->autoEQP = booleanValue(azArg[1]);
3496  }
3497  }else{
3498  raw_printf(stderr, "Usage: .eqp on|off|full\n");
3499  rc = 1;
3500  }
3501  }else
3502 
3503  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
3504  if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
3505  rc = 2;
3506  }else
3507 
3508  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
3509  int val = 1;
3510  if( nArg>=2 ){
3511  if( strcmp(azArg[1],"auto")==0 ){
3512  val = 99;
3513  }else{
3514  val = booleanValue(azArg[1]);
3515  }
3516  }
3517  if( val==1 && p->mode!=MODE_Explain ){
3518  p->normalMode = p->mode;
3519  p->mode = MODE_Explain;
3520  p->autoExplain = 0;
3521  }else if( val==0 ){
3522  if( p->mode==MODE_Explain ) p->mode = p->normalMode;
3523  p->autoExplain = 0;
3524  }else if( val==99 ){
3525  if( p->mode==MODE_Explain ) p->mode = p->normalMode;
3526  p->autoExplain = 1;
3527  }
3528  }else
3529 
3530  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
3531  ShellState data;
3532  char *zErrMsg = 0;
3533  int doStats = 0;
3534  memcpy(&data, p, sizeof(data));
3535  data.showHeader = 0;
3536  data.cMode = data.mode = MODE_Semi;
3537  if( nArg==2 && optionMatch(azArg[1], "indent") ){
3538  data.cMode = data.mode = MODE_Pretty;
3539  nArg = 1;
3540  }
3541  if( nArg!=1 ){
3542  raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
3543  rc = 1;
3544  goto meta_command_exit;
3545  }
3546  open_db(p, 0);
3547  rc = sqlite3_exec(p->db,
3548  "SELECT sql FROM"
3549  " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
3550  " FROM sqlite_master UNION ALL"
3551  " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
3552  "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
3553  "ORDER BY rowid",
3554  callback, &data, &zErrMsg
3555  );
3556  if( rc==SQLITE_OK ){
3557  sqlite3_stmt *pStmt;
3558  rc = sqlite3_prepare_v2(p->db,
3559  "SELECT rowid FROM sqlite_master"
3560  " WHERE name GLOB 'sqlite_stat[134]'",
3561  -1, &pStmt, 0);
3562  doStats = sqlite3_step(pStmt)==SQLITE_ROW;
3563  sqlite3_finalize(pStmt);
3564  }
3565  if( doStats==0 ){
3566  raw_printf(p->out, "/* No STAT tables available */\n");
3567  }else{
3568  raw_printf(p->out, "ANALYZE sqlite_master;\n");
3569  sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
3570  callback, &data, &zErrMsg);
3571  data.cMode = data.mode = MODE_Insert;
3572  data.zDestTable = "sqlite_stat1";
3573  shell_exec(p->db, "SELECT * FROM sqlite_stat1",
3574  shell_callback, &data,&zErrMsg);
3575  data.zDestTable = "sqlite_stat3";
3576  shell_exec(p->db, "SELECT * FROM sqlite_stat3",
3577  shell_callback, &data,&zErrMsg);
3578  data.zDestTable = "sqlite_stat4";
3579  shell_exec(p->db, "SELECT * FROM sqlite_stat4",
3580  shell_callback, &data, &zErrMsg);
3581  raw_printf(p->out, "ANALYZE sqlite_master;\n");
3582  }
3583  }else
3584 
3585  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
3586  if( nArg==2 ){
3587  p->showHeader = booleanValue(azArg[1]);
3588  }else{
3589  raw_printf(stderr, "Usage: .headers on|off\n");
3590  rc = 1;
3591  }
3592  }else
3593 
3594  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
3595  utf8_printf(p->out, "%s", zHelp);
3596  }else
3597 
3598  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
3599  char *zTable; /* Insert data into this table */
3600  char *zFile; /* Name of file to extra content from */
3601  sqlite3_stmt *pStmt = NULL; /* A statement */
3602  int nCol; /* Number of columns in the table */
3603  int nByte; /* Number of bytes in an SQL string */
3604  int i, j; /* Loop counters */
3605  int needCommit; /* True to COMMIT or ROLLBACK at end */
3606  int nSep; /* Number of bytes in p->colSeparator[] */
3607  char *zSql; /* An SQL statement */
3608  ImportCtx sCtx; /* Reader context */
3609  char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
3610  int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
3611 
3612  if( nArg!=3 ){
3613  raw_printf(stderr, "Usage: .import FILE TABLE\n");
3614  goto meta_command_exit;
3615  }
3616  zFile = azArg[1];
3617  zTable = azArg[2];
3618  seenInterrupt = 0;
3619  memset(&sCtx, 0, sizeof(sCtx));
3620  open_db(p, 0);
3621  nSep = strlen30(p->colSeparator);
3622  if( nSep==0 ){
3623  raw_printf(stderr,
3624  "Error: non-null column separator required for import\n");
3625  return 1;
3626  }
3627  if( nSep>1 ){
3628  raw_printf(stderr, "Error: multi-character column separators not allowed"
3629  " for import\n");
3630  return 1;
3631  }
3632  nSep = strlen30(p->rowSeparator);
3633  if( nSep==0 ){
3634  raw_printf(stderr, "Error: non-null row separator required for import\n");
3635  return 1;
3636  }
3637  if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
3638  /* When importing CSV (only), if the row separator is set to the
3639  ** default output row separator, change it to the default input
3640  ** row separator. This avoids having to maintain different input
3641  ** and output row separators. */
3643  nSep = strlen30(p->rowSeparator);
3644  }
3645  if( nSep>1 ){
3646  raw_printf(stderr, "Error: multi-character row separators not allowed"
3647  " for import\n");
3648  return 1;
3649  }
3650  sCtx.zFile = zFile;
3651  sCtx.nLine = 1;
3652  if( sCtx.zFile[0]=='|' ){
3653 #ifdef SQLITE_OMIT_POPEN
3654  raw_printf(stderr, "Error: pipes are not supported in this OS\n");
3655  return 1;
3656 #else
3657  sCtx.in = popen(sCtx.zFile+1, "r");
3658  sCtx.zFile = "<pipe>";
3659  xCloser = pclose;
3660 #endif
3661  }else{
3662  sCtx.in = fopen(sCtx.zFile, "rb");
3663  xCloser = fclose;
3664  }
3665  if( p->mode==MODE_Ascii ){
3666  xRead = ascii_read_one_field;
3667  }else{
3668  xRead = csv_read_one_field;
3669  }
3670  if( sCtx.in==0 ){
3671  utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
3672  return 1;
3673  }
3674  sCtx.cColSep = p->colSeparator[0];
3675  sCtx.cRowSep = p->rowSeparator[0];
3676  zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
3677  if( zSql==0 ){
3678  raw_printf(stderr, "Error: out of memory\n");
3679  xCloser(sCtx.in);
3680  return 1;
3681  }
3682  nByte = strlen30(zSql);
3683  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3684  import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
3685  if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
3686  char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
3687  char cSep = '(';
3688  while( xRead(&sCtx) ){
3689  zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
3690  cSep = ',';
3691  if( sCtx.cTerm!=sCtx.cColSep ) break;
3692  }
3693  if( cSep=='(' ){
3694  sqlite3_free(zCreate);
3695  sqlite3_free(sCtx.z);
3696  xCloser(sCtx.in);
3697  utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
3698  return 1;
3699  }
3700  zCreate = sqlite3_mprintf("%z\n)", zCreate);
3701  rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
3702  sqlite3_free(zCreate);
3703  if( rc ){
3704  utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
3705  sqlite3_errmsg(p->db));
3706  sqlite3_free(sCtx.z);
3707  xCloser(sCtx.in);
3708  return 1;
3709  }
3710  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3711  }
3712  sqlite3_free(zSql);
3713  if( rc ){
3714  if (pStmt) sqlite3_finalize(pStmt);
3715  utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
3716  xCloser(sCtx.in);
3717  return 1;
3718  }
3719  nCol = sqlite3_column_count(pStmt);
3720  sqlite3_finalize(pStmt);
3721  pStmt = 0;
3722  if( nCol==0 ) return 0; /* no columns, no error */
3723  zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
3724  if( zSql==0 ){
3725  raw_printf(stderr, "Error: out of memory\n");
3726  xCloser(sCtx.in);
3727  return 1;
3728  }
3729  sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
3730  j = strlen30(zSql);
3731  for(i=1; i<nCol; i++){
3732  zSql[j++] = ',';
3733  zSql[j++] = '?';
3734  }
3735  zSql[j++] = ')';
3736  zSql[j] = 0;
3737  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3738  sqlite3_free(zSql);
3739  if( rc ){
3740  utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
3741  if (pStmt) sqlite3_finalize(pStmt);
3742  xCloser(sCtx.in);
3743  return 1;
3744  }
3745  needCommit = sqlite3_get_autocommit(p->db);
3746  if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
3747  do{
3748  int startLine = sCtx.nLine;
3749  for(i=0; i<nCol; i++){
3750  char *z = xRead(&sCtx);
3751  /*
3752  ** Did we reach end-of-file before finding any columns?
3753  ** If so, stop instead of NULL filling the remaining columns.
3754  */
3755  if( z==0 && i==0 ) break;
3756  /*
3757  ** Did we reach end-of-file OR end-of-line before finding any
3758  ** columns in ASCII mode? If so, stop instead of NULL filling
3759  ** the remaining columns.
3760  */
3761  if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
3762  sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
3763  if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
3764  utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
3765  "filling the rest with NULL\n",
3766  sCtx.zFile, startLine, nCol, i+1);
3767  i += 2;
3768  while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
3769  }
3770  }
3771  if( sCtx.cTerm==sCtx.cColSep ){
3772  do{
3773  xRead(&sCtx);
3774  i++;
3775  }while( sCtx.cTerm==sCtx.cColSep );
3776  utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
3777  "extras ignored\n",
3778  sCtx.zFile, startLine, nCol, i);
3779  }
3780  if( i>=nCol ){
3781  sqlite3_step(pStmt);
3782  rc = sqlite3_reset(pStmt);
3783  if( rc!=SQLITE_OK ){
3784  utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
3785  startLine, sqlite3_errmsg(p->db));
3786  }
3787  }
3788  }while( sCtx.cTerm!=EOF );
3789 
3790  xCloser(sCtx.in);
3791  sqlite3_free(sCtx.z);
3792  sqlite3_finalize(pStmt);
3793  if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
3794  }else
3795 
3796  if( c=='i' && (strncmp(azArg[0], "indices", n)==0
3797  || strncmp(azArg[0], "indexes", n)==0) ){
3798  ShellState data;
3799  char *zErrMsg = 0;
3800  open_db(p, 0);
3801  memcpy(&data, p, sizeof(data));
3802  data.showHeader = 0;
3803  data.cMode = data.mode = MODE_List;
3804  if( nArg==1 ){
3805  rc = sqlite3_exec(p->db,
3806  "SELECT name FROM sqlite_master "
3807  "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
3808  "UNION ALL "
3809  "SELECT name FROM sqlite_temp_master "
3810  "WHERE type='index' "
3811  "ORDER BY 1",
3812  callback, &data, &zErrMsg
3813  );
3814  }else if( nArg==2 ){
3815  zShellStatic = azArg[1];
3816  rc = sqlite3_exec(p->db,
3817  "SELECT name FROM sqlite_master "
3818  "WHERE type='index' AND tbl_name LIKE shellstatic() "
3819  "UNION ALL "
3820  "SELECT name FROM sqlite_temp_master "
3821  "WHERE type='index' AND tbl_name LIKE shellstatic() "
3822  "ORDER BY 1",
3823  callback, &data, &zErrMsg
3824  );
3825  zShellStatic = 0;
3826  }else{
3827  raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
3828  rc = 1;
3829  goto meta_command_exit;
3830  }
3831  if( zErrMsg ){
3832  utf8_printf(stderr,"Error: %s\n", zErrMsg);
3833  sqlite3_free(zErrMsg);
3834  rc = 1;
3835  }else if( rc != SQLITE_OK ){
3836  raw_printf(stderr,
3837  "Error: querying sqlite_master and sqlite_temp_master\n");
3838  rc = 1;
3839  }
3840  }else
3841 
3842 #ifdef SQLITE_ENABLE_IOTRACE
3843  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
3844  SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
3845  if( iotrace && iotrace!=stdout ) fclose(iotrace);
3846  iotrace = 0;
3847  if( nArg<2 ){
3848  sqlite3IoTrace = 0;
3849  }else if( strcmp(azArg[1], "-")==0 ){
3850  sqlite3IoTrace = iotracePrintf;
3851  iotrace = stdout;
3852  }else{
3853  iotrace = fopen(azArg[1], "w");
3854  if( iotrace==0 ){
3855  utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
3856  sqlite3IoTrace = 0;
3857  rc = 1;
3858  }else{
3859  sqlite3IoTrace = iotracePrintf;
3860  }
3861  }
3862  }else
3863 #endif
3864  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
3865  static const struct {
3866  const char *zLimitName; /* Name of a limit */
3867  int limitCode; /* Integer code for that limit */
3868  } aLimit[] = {
3869  { "length", SQLITE_LIMIT_LENGTH },
3870  { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
3871  { "column", SQLITE_LIMIT_COLUMN },
3872  { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
3873  { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
3874  { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
3875  { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
3876  { "attached", SQLITE_LIMIT_ATTACHED },
3877  { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
3878  { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
3879  { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
3880  { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
3881  };
3882  int i, n2;
3883  open_db(p, 0);
3884  if( nArg==1 ){
3885  for(i=0; i<ArraySize(aLimit); i++){
3886  printf("%20s %d\n", aLimit[i].zLimitName,
3887  sqlite3_limit(p->db, aLimit[i].limitCode, -1));
3888  }
3889  }else if( nArg>3 ){
3890  raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
3891  rc = 1;
3892  goto meta_command_exit;
3893  }else{
3894  int iLimit = -1;
3895  n2 = strlen30(azArg[1]);
3896  for(i=0; i<ArraySize(aLimit); i++){
3897  if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
3898  if( iLimit<0 ){
3899  iLimit = i;
3900  }else{
3901  utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
3902  rc = 1;
3903  goto meta_command_exit;
3904  }
3905  }
3906  }
3907  if( iLimit<0 ){
3908  utf8_printf(stderr, "unknown limit: \"%s\"\n"
3909  "enter \".limits\" with no arguments for a list.\n",
3910  azArg[1]);
3911  rc = 1;
3912  goto meta_command_exit;
3913  }
3914  if( nArg==3 ){
3915  sqlite3_limit(p->db, aLimit[iLimit].limitCode,
3916  (int)integerValue(azArg[2]));
3917  }
3918  printf("%20s %d\n", aLimit[iLimit].zLimitName,
3919  sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
3920  }
3921  }else
3922 
3923 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3924  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
3925  const char *zFile, *zProc;
3926  char *zErrMsg = 0;
3927  if( nArg<2 ){
3928  raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
3929  rc = 1;
3930  goto meta_command_exit;
3931  }
3932  zFile = azArg[1];
3933  zProc = nArg>=3 ? azArg[2] : 0;
3934  open_db(p, 0);
3935  rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
3936  if( rc!=SQLITE_OK ){
3937  utf8_printf(stderr, "Error: %s\n", zErrMsg);
3938  sqlite3_free(zErrMsg);
3939  rc = 1;
3940  }
3941  }else
3942 #endif
3943 
3944  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
3945  if( nArg!=2 ){
3946  raw_printf(stderr, "Usage: .log FILENAME\n");
3947  rc = 1;
3948  }else{
3949  const char *zFile = azArg[1];
3950  output_file_close(p->pLog);
3951  p->pLog = output_file_open(zFile);
3952  }
3953  }else
3954 
3955  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
3956  const char *zMode = nArg>=2 ? azArg[1] : "";
3957  int n2 = (int)strlen(zMode);
3958  int c2 = zMode[0];
3959  if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
3960  p->mode = MODE_Line;
3961  }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
3962  p->mode = MODE_Column;
3963  }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
3964  p->mode = MODE_List;
3965  }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
3966  p->mode = MODE_Html;
3967  }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
3968  p->mode = MODE_Tcl;
3970  }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
3971  p->mode = MODE_Csv;
3974  }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
3975  p->mode = MODE_List;
3977  }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
3978  p->mode = MODE_Insert;
3979  set_table_name(p, nArg>=3 ? azArg[2] : "table");
3980  }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
3981  p->mode = MODE_Ascii;
3984  }else {
3985  raw_printf(stderr, "Error: mode should be one of: "
3986  "ascii column csv html insert line list tabs tcl\n");
3987  rc = 1;
3988  }
3989  p->cMode = p->mode;
3990  }else
3991 
3992  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
3993  if( nArg==2 ){
3994  sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
3995  "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
3996  }else{
3997  raw_printf(stderr, "Usage: .nullvalue STRING\n");
3998  rc = 1;
3999  }
4000  }else
4001 
4002  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
4003  char *zNewFilename; /* Name of the database file to open */
4004  int iName = 1; /* Index in azArg[] of the filename */
4005  int newFlag = 0; /* True to delete file before opening */
4006  /* Close the existing database */
4007  session_close_all(p);
4008  sqlite3_close(p->db);
4009  p->db = 0;
4011  p->zFreeOnClose = 0;
4012  /* Check for command-line arguments */
4013  for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
4014  const char *z = azArg[iName];
4015  if( optionMatch(z,"new") ){
4016  newFlag = 1;
4017  }else if( z[0]=='-' ){
4018  utf8_printf(stderr, "unknown option: %s\n", z);
4019  rc = 1;
4020  goto meta_command_exit;
4021  }
4022  }
4023  /* If a filename is specified, try to open it first */
4024  zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
4025  if( zNewFilename ){
4026  if( newFlag ) shellDeleteFile(zNewFilename);
4027  p->zDbFilename = zNewFilename;
4028  open_db(p, 1);
4029  if( p->db==0 ){
4030  utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
4031  sqlite3_free(zNewFilename);
4032  }else{
4033  p->zFreeOnClose = zNewFilename;
4034  }
4035  }
4036  if( p->db==0 ){
4037  /* As a fall-back open a TEMP database */
4038  p->zDbFilename = 0;
4039  open_db(p, 0);
4040  }
4041  }else
4042 
4043  if( c=='o'
4044  && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
4045  ){
4046  const char *zFile = nArg>=2 ? azArg[1] : "stdout";
4047  if( nArg>2 ){
4048  utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
4049  rc = 1;
4050  goto meta_command_exit;
4051  }
4052  if( n>1 && strncmp(azArg[0], "once", n)==0 ){
4053  if( nArg<2 ){
4054  raw_printf(stderr, "Usage: .once FILE\n");
4055  rc = 1;
4056  goto meta_command_exit;
4057  }
4058  p->outCount = 2;
4059  }else{
4060  p->outCount = 0;
4061  }
4062  output_reset(p);
4063  if( zFile[0]=='|' ){
4064 #ifdef SQLITE_OMIT_POPEN
4065  raw_printf(stderr, "Error: pipes are not supported in this OS\n");
4066  rc = 1;
4067  p->out = stdout;
4068 #else
4069  p->out = popen(zFile + 1, "w");
4070  if( p->out==0 ){
4071  utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
4072  p->out = stdout;
4073  rc = 1;
4074  }else{
4075  sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
4076  }
4077 #endif
4078  }else{
4079  p->out = output_file_open(zFile);
4080  if( p->out==0 ){
4081  if( strcmp(zFile,"off")!=0 ){
4082  utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
4083  }
4084  p->out = stdout;
4085  rc = 1;
4086  } else {
4087  sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
4088  }
4089  }
4090  }else
4091 
4092  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
4093  int i;
4094  for(i=1; i<nArg; i++){
4095  if( i>1 ) raw_printf(p->out, " ");
4096  utf8_printf(p->out, "%s", azArg[i]);
4097  }
4098  raw_printf(p->out, "\n");
4099  }else
4100 
4101  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
4102  if( nArg >= 2) {
4103  strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
4104  }
4105  if( nArg >= 3) {
4106  strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
4107  }
4108  }else
4109 
4110  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
4111  rc = 2;
4112  }else
4113 
4114  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
4115  FILE *alt;
4116  if( nArg!=2 ){
4117  raw_printf(stderr, "Usage: .read FILE\n");
4118  rc = 1;
4119  goto meta_command_exit;
4120  }
4121  alt = fopen(azArg[1], "rb");
4122  if( alt==0 ){
4123  utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
4124  rc = 1;
4125  }else{
4126  rc = process_input(p, alt);
4127  fclose(alt);
4128  }
4129  }else
4130 
4131  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
4132  const char *zSrcFile;
4133  const char *zDb;
4134  sqlite3 *pSrc;
4135  sqlite3_backup *pBackup;
4136  int nTimeout = 0;
4137 
4138  if( nArg==2 ){
4139  zSrcFile = azArg[1];
4140  zDb = "main";
4141  }else if( nArg==3 ){
4142  zSrcFile = azArg[2];
4143  zDb = azArg[1];
4144  }else{
4145  raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
4146  rc = 1;
4147  goto meta_command_exit;
4148  }
4149  rc = sqlite3_open(zSrcFile, &pSrc);
4150  if( rc!=SQLITE_OK ){
4151  utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
4152  sqlite3_close(pSrc);
4153  return 1;
4154  }
4155  open_db(p, 0);
4156  pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
4157  if( pBackup==0 ){
4158  utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
4159  sqlite3_close(pSrc);
4160  return 1;
4161  }
4162  while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
4163  || rc==SQLITE_BUSY ){
4164  if( rc==SQLITE_BUSY ){
4165  if( nTimeout++ >= 3 ) break;
4166  sqlite3_sleep(100);
4167  }
4168  }
4169  sqlite3_backup_finish(pBackup);
4170  if( rc==SQLITE_DONE ){
4171  rc = 0;
4172  }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
4173  raw_printf(stderr, "Error: source database is busy\n");
4174  rc = 1;
4175  }else{
4176  utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
4177  rc = 1;
4178  }
4179  sqlite3_close(pSrc);
4180  }else
4181 
4182 
4183  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
4184  if( nArg==2 ){
4185  p->scanstatsOn = booleanValue(azArg[1]);
4186 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
4187  raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
4188 #endif
4189  }else{
4190  raw_printf(stderr, "Usage: .scanstats on|off\n");
4191  rc = 1;
4192  }
4193  }else
4194 
4195  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
4196  ShellState data;
4197  char *zErrMsg = 0;
4198  open_db(p, 0);
4199  memcpy(&data, p, sizeof(data));
4200  data.showHeader = 0;
4201  data.cMode = data.mode = MODE_Semi;
4202  if( nArg>=2 && optionMatch(azArg[1], "indent") ){
4203  data.cMode = data.mode = MODE_Pretty;
4204  nArg--;
4205  if( nArg==2 ) azArg[1] = azArg[2];
4206  }
4207  if( nArg==2 && azArg[1][0]!='-' ){
4208  int i;
4209  for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
4210  if( strcmp(azArg[1],"sqlite_master")==0 ){
4211  char *new_argv[2], *new_colv[2];
4212  new_argv[0] = "CREATE TABLE sqlite_master (\n"
4213  " type text,\n"
4214  " name text,\n"
4215  " tbl_name text,\n"
4216  " rootpage integer,\n"
4217  " sql text\n"
4218  ")";
4219  new_argv[1] = 0;
4220  new_colv[0] = "sql";
4221  new_colv[1] = 0;
4222  callback(&data, 1, new_argv, new_colv);
4223  rc = SQLITE_OK;
4224  }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
4225  char *new_argv[2], *new_colv[2];
4226  new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
4227  " type text,\n"
4228  " name text,\n"
4229  " tbl_name text,\n"
4230  " rootpage integer,\n"
4231  " sql text\n"
4232  ")";
4233  new_argv[1] = 0;
4234  new_colv[0] = "sql";
4235  new_colv[1] = 0;
4236  callback(&data, 1, new_argv, new_colv);
4237  rc = SQLITE_OK;
4238  }else{
4239  zShellStatic = azArg[1];
4240  rc = sqlite3_exec(p->db,
4241  "SELECT sql FROM "
4242  " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4243  " FROM sqlite_master UNION ALL"
4244  " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4245  "WHERE lower(tbl_name) LIKE shellstatic()"
4246  " AND type!='meta' AND sql NOTNULL "
4247  "ORDER BY rowid",
4248  callback, &data, &zErrMsg);
4249  zShellStatic = 0;
4250  }
4251  }else if( nArg==1 ){
4252  rc = sqlite3_exec(p->db,
4253  "SELECT sql FROM "
4254  " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4255  " FROM sqlite_master UNION ALL"
4256  " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
4257  "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
4258  "ORDER BY rowid",
4259  callback, &data, &zErrMsg
4260  );
4261  }else{
4262  raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
4263  rc = 1;
4264  goto meta_command_exit;
4265  }
4266  if( zErrMsg ){
4267  utf8_printf(stderr,"Error: %s\n", zErrMsg);
4268  sqlite3_free(zErrMsg);
4269  rc = 1;
4270  }else if( rc != SQLITE_OK ){
4271  raw_printf(stderr,"Error: querying schema information\n");
4272  rc = 1;
4273  }else{
4274  rc = 0;
4275  }
4276  }else
4277 
4278 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
4279  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
4280  sqlite3SelectTrace = integerValue(azArg[1]);
4281  }else
4282 #endif
4283 
4284 #if defined(SQLITE_ENABLE_SESSION)
4285  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
4286  OpenSession *pSession = &p->aSession[0];
4287  char **azCmd = &azArg[1];
4288  int iSes = 0;
4289  int nCmd = nArg - 1;
4290  int i;
4291  if( nArg<=1 ) goto session_syntax_error;
4292  open_db(p, 0);
4293  if( nArg>=3 ){
4294  for(iSes=0; iSes<p->nSession; iSes++){
4295  if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
4296  }
4297  if( iSes<p->nSession ){
4298  pSession = &p->aSession[iSes];
4299  azCmd++;
4300  nCmd--;
4301  }else{
4302  pSession = &p->aSession[0];
4303  iSes = 0;
4304  }
4305  }
4306 
4307  /* .session attach TABLE
4308  ** Invoke the sqlite3session_attach() interface to attach a particular
4309  ** table so that it is never filtered.
4310  */
4311  if( strcmp(azCmd[0],"attach")==0 ){
4312  if( nCmd!=2 ) goto session_syntax_error;
4313  if( pSession->p==0 ){
4314  session_not_open:
4315  raw_printf(stderr, "ERROR: No sessions are open\n");
4316  }else{
4317  rc = sqlite3session_attach(pSession->p, azCmd[1]);
4318  if( rc ){
4319  raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
4320  rc = 0;
4321  }
4322  }
4323  }else
4324 
4325  /* .session changeset FILE
4326  ** .session patchset FILE
4327  ** Write a changeset or patchset into a file. The file is overwritten.
4328  */
4329  if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
4330  FILE *out = 0;
4331  if( nCmd!=2 ) goto session_syntax_error;
4332  if( pSession->p==0 ) goto session_not_open;
4333  out = fopen(azCmd[1], "wb");
4334  if( out==0 ){
4335  utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
4336  }else{
4337  int szChng;
4338  void *pChng;
4339  if( azCmd[0][0]=='c' ){
4340  rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
4341  }else{
4342  rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
4343  }
4344  if( rc ){
4345  printf("Error: error code %d\n", rc);
4346  rc = 0;
4347  }
4348  if( pChng
4349  && fwrite(pChng, szChng, 1, out)!=1 ){
4350  raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
4351  szChng);
4352  }
4353  sqlite3_free(pChng);
4354  fclose(out);
4355  }
4356  }else
4357 
4358  /* .session close
4359  ** Close the identified session
4360  */
4361  if( strcmp(azCmd[0], "close")==0 ){
4362  if( nCmd!=1 ) goto session_syntax_error;
4363  if( p->nSession ){
4364  session_close(pSession);
4365  p->aSession[iSes] = p->aSession[--p->nSession];
4366  }
4367  }else
4368 
4369  /* .session enable ?BOOLEAN?
4370  ** Query or set the enable flag
4371  */
4372  if( strcmp(azCmd[0], "enable")==0 ){
4373  int ii;
4374  if( nCmd>2 ) goto session_syntax_error;
4375  ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
4376  if( p->nSession ){
4377  ii = sqlite3session_enable(pSession->p, ii);
4378  utf8_printf(p->out, "session %s enable flag = %d\n",
4379  pSession->zName, ii);
4380  }
4381  }else
4382 
4383  /* .session filter GLOB ....
4384  ** Set a list of GLOB patterns of table names to be excluded.
4385  */
4386  if( strcmp(azCmd[0], "filter")==0 ){
4387  int ii, nByte;
4388  if( nCmd<2 ) goto session_syntax_error;
4389  if( p->nSession ){
4390  for(ii=0; ii<pSession->nFilter; ii++){
4391  sqlite3_free(pSession->azFilter[ii]);
4392  }
4393  sqlite3_free(pSession->azFilter);
4394  nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
4395  pSession->azFilter = sqlite3_malloc( nByte );
4396  if( pSession->azFilter==0 ){
4397  raw_printf(stderr, "Error: out or memory\n");
4398  exit(1);
4399  }
4400  for(ii=1; ii<nCmd; ii++){
4401  pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
4402  }
4403  pSession->nFilter = ii-1;
4404  }
4405  }else
4406 
4407  /* .session indirect ?BOOLEAN?
4408  ** Query or set the indirect flag
4409  */
4410  if( strcmp(azCmd[0], "indirect")==0 ){
4411  int ii;
4412  if( nCmd>2 ) goto session_syntax_error;
4413  ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
4414  if( p->nSession ){
4415  ii = sqlite3session_indirect(pSession->p, ii);
4416  utf8_printf(p->out, "session %s indirect flag = %d\n",
4417  pSession->zName, ii);
4418  }
4419  }else
4420 
4421  /* .session isempty
4422  ** Determine if the session is empty
4423  */
4424  if( strcmp(azCmd[0], "isempty")==0 ){
4425  int ii;
4426  if( nCmd!=1 ) goto session_syntax_error;
4427  if( p->nSession ){
4428  ii = sqlite3session_isempty(pSession->p);
4429  utf8_printf(p->out, "session %s isempty flag = %d\n",
4430  pSession->zName, ii);
4431  }
4432  }else
4433 
4434  /* .session list
4435  ** List all currently open sessions
4436  */
4437  if( strcmp(azCmd[0],"list")==0 ){
4438  for(i=0; i<p->nSession; i++){
4439  utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
4440  }
4441  }else
4442 
4443  /* .session open DB NAME
4444  ** Open a new session called NAME on the attached database DB.
4445  ** DB is normally "main".
4446  */
4447  if( strcmp(azCmd[0],"open")==0 ){
4448  char *zName;
4449  if( nCmd!=3 ) goto session_syntax_error;
4450  zName = azCmd[2];
4451  if( zName[0]==0 ) goto session_syntax_error;
4452  for(i=0; i<p->nSession; i++){
4453  if( strcmp(p->aSession[i].zName,zName)==0 ){
4454  utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
4455  goto meta_command_exit;
4456  }
4457  }
4458  if( p->nSession>=ArraySize(p->aSession) ){
4459  raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
4460  goto meta_command_exit;
4461  }
4462  pSession = &p->aSession[p->nSession];
4463  rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
4464  if( rc ){
4465  raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
4466  rc = 0;
4467  goto meta_command_exit;
4468  }
4469  pSession->nFilter = 0;
4470  sqlite3session_table_filter(pSession->p, session_filter, pSession);
4471  p->nSession++;
4472  pSession->zName = sqlite3_mprintf("%s", zName);
4473  }else
4474  /* If no command name matches, show a syntax error */
4475  session_syntax_error:
4476  session_help(p);
4477  }else
4478 #endif
4479 
4480 #ifdef SQLITE_DEBUG
4481  /* Undocumented commands for internal testing. Subject to change
4482  ** without notice. */
4483  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
4484  if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
4485  int i, v;
4486  for(i=1; i<nArg; i++){
4487  v = booleanValue(azArg[i]);
4488  utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
4489  }
4490  }
4491  if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
4492  int i; sqlite3_int64 v;
4493  for(i=1; i<nArg; i++){
4494  char zBuf[200];
4495  v = integerValue(azArg[i]);
4496  sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
4497  utf8_printf(p->out, "%s", zBuf);
4498  }
4499  }
4500  }else
4501 #endif
4502 
4503  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
4504  if( nArg<2 || nArg>3 ){
4505  raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
4506  rc = 1;
4507  }
4508  if( nArg>=2 ){
4510  "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
4511  }
4512  if( nArg>=3 ){
4514  "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
4515  }
4516  }else
4517 
4518  if( c=='s'
4519  && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
4520  ){
4521  char *zCmd;
4522  int i, x;
4523  if( nArg<2 ){
4524  raw_printf(stderr, "Usage: .system COMMAND\n");
4525  rc = 1;
4526  goto meta_command_exit;
4527  }
4528  zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
4529  for(i=2; i<nArg; i++){
4530  zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
4531  zCmd, azArg[i]);
4532  }
4533  x = system(zCmd);
4534  sqlite3_free(zCmd);
4535  if( x ) raw_printf(stderr, "System command returns %d\n", x);
4536  }else
4537 
4538  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
4539  static const char *azBool[] = { "off", "on", "full", "unk" };
4540  int i;
4541  if( nArg!=1 ){
4542  raw_printf(stderr, "Usage: .show\n");
4543  rc = 1;
4544  goto meta_command_exit;
4545  }
4546  utf8_printf(p->out, "%12.12s: %s\n","echo", azBool[p->echoOn!=0]);
4547  utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
4548  utf8_printf(p->out, "%12.12s: %s\n","explain",
4549  p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
4550  utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
4551  utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
4552  utf8_printf(p->out, "%12.12s: ", "nullvalue");
4553  output_c_string(p->out, p->nullValue);
4554  raw_printf(p->out, "\n");
4555  utf8_printf(p->out,"%12.12s: %s\n","output",
4556  strlen30(p->outfile) ? p->outfile : "stdout");
4557  utf8_printf(p->out,"%12.12s: ", "colseparator");
4559  raw_printf(p->out, "\n");
4560  utf8_printf(p->out,"%12.12s: ", "rowseparator");
4562  raw_printf(p->out, "\n");
4563  utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
4564  utf8_printf(p->out, "%12.12s: ", "width");
4565  for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
4566  raw_printf(p->out, "%d ", p->colWidth[i]);
4567  }
4568  raw_printf(p->out, "\n");
4569  utf8_printf(p->out, "%12.12s: %s\n", "filename",
4570  p->zDbFilename ? p->zDbFilename : "");
4571  }else
4572 
4573  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
4574  if( nArg==2 ){
4575  p->statsOn = booleanValue(azArg[1]);
4576  }else if( nArg==1 ){
4577  display_stats(p->db, p, 0);
4578  }else{
4579  raw_printf(stderr, "Usage: .stats ?on|off?\n");
4580  rc = 1;
4581  }
4582  }else
4583 
4584  if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
4585  sqlite3_stmt *pStmt;
4586  char **azResult;
4587  int nRow, nAlloc;
4588  char *zSql = 0;
4589  int ii;
4590  open_db(p, 0);
4591  rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
4592  if( rc ) return shellDatabaseError(p->db);
4593 
4594  /* Create an SQL statement to query for the list of tables in the
4595  ** main and all attached databases where the table name matches the
4596  ** LIKE pattern bound to variable "?1". */
4597  zSql = sqlite3_mprintf(
4598  "SELECT name FROM sqlite_master"
4599  " WHERE type IN ('table','view')"
4600  " AND name NOT LIKE 'sqlite_%%'"
4601  " AND name LIKE ?1");
4602  while( zSql && sqlite3_step(pStmt)==SQLITE_ROW ){
4603  const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
4604  if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue;
4605  if( strcmp(zDbName,"temp")==0 ){
4606  zSql = sqlite3_mprintf(
4607  "%z UNION ALL "
4608  "SELECT 'temp.' || name FROM sqlite_temp_master"
4609  " WHERE type IN ('table','view')"
4610  " AND name NOT LIKE 'sqlite_%%'"
4611  " AND name LIKE ?1", zSql);
4612  }else{
4613  zSql = sqlite3_mprintf(
4614  "%z UNION ALL "
4615  "SELECT '%q.' || name FROM \"%w\".sqlite_master"
4616  " WHERE type IN ('table','view')"
4617  " AND name NOT LIKE 'sqlite_%%'"
4618  " AND name LIKE ?1", zSql, zDbName, zDbName);
4619  }
4620  }
4621  rc = sqlite3_finalize(pStmt);
4622  if( zSql && rc==SQLITE_OK ){
4623  zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
4624  if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4625  }
4626  sqlite3_free(zSql);
4627  if( !zSql ) return shellNomemError();
4628  if( rc ) return shellDatabaseError(p->db);
4629 
4630  /* Run the SQL statement prepared by the above block. Store the results
4631  ** as an array of nul-terminated strings in azResult[]. */
4632  nRow = nAlloc = 0;
4633  azResult = 0;
4634  if( nArg>1 ){
4635  sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
4636  }else{
4637  sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
4638  }
4639  while( sqlite3_step(pStmt)==SQLITE_ROW ){
4640  if( nRow>=nAlloc ){
4641  char **azNew;
4642  int n2 = nAlloc*2 + 10;
4643  azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
4644  if( azNew==0 ){
4645  rc = shellNomemError();
4646  break;
4647  }
4648  nAlloc = n2;
4649  azResult = azNew;
4650  }
4651  azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
4652  if( 0==azResult[nRow] ){
4653  rc = shellNomemError();
4654  break;
4655  }
4656  nRow++;
4657  }
4658  if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
4659  rc = shellDatabaseError(p->db);
4660  }
4661 
4662  /* Pretty-print the contents of array azResult[] to the output */
4663  if( rc==0 && nRow>0 ){
4664  int len, maxlen = 0;
4665  int i, j;
4666  int nPrintCol, nPrintRow;
4667  for(i=0; i<nRow; i++){
4668  len = strlen30(azResult[i]);
4669  if( len>maxlen ) maxlen = len;
4670  }
4671  nPrintCol = 80/(maxlen+2);
4672  if( nPrintCol<1 ) nPrintCol = 1;
4673  nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
4674  for(i=0; i<nPrintRow; i++){
4675  for(j=i; j<nRow; j+=nPrintRow){
4676  char *zSp = j<nPrintRow ? "" : " ";
4677  utf8_printf(p->out, "%s%-*s", zSp, maxlen,
4678  azResult[j] ? azResult[j]:"");
4679  }
4680  raw_printf(p->out, "\n");
4681  }
4682  }
4683 
4684  for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
4685  sqlite3_free(azResult);
4686  }else
4687 
4688  /* Begin redirecting output to the file "testcase-out.txt" */
4689  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
4690  output_reset(p);
4691  p->out = output_file_open("testcase-out.txt");
4692  if( p->out==0 ){
4693  utf8_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
4694  }
4695  if( nArg>=2 ){
4696  sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
4697  }else{
4698  sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
4699  }
4700  }else
4701 
4702  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
4703  static const struct {
4704  const char *zCtrlName; /* Name of a test-control option */
4705  int ctrlCode; /* Integer code for that option */
4706  } aCtrl[] = {
4707  { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
4708  { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
4709  { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
4710  { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
4711  { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
4712  { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
4713  { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
4714  { "assert", SQLITE_TESTCTRL_ASSERT },
4715  { "always", SQLITE_TESTCTRL_ALWAYS },
4716  { "reserve", SQLITE_TESTCTRL_RESERVE },
4717  { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
4718  { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
4719  { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
4720  { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
4721  { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
4722  { "imposter", SQLITE_TESTCTRL_IMPOSTER },
4723  };
4724  int testctrl = -1;
4725  int rc2 = 0;
4726  int i, n2;
4727  open_db(p, 0);
4728 
4729  /* convert testctrl text option to value. allow any unique prefix
4730  ** of the option name, or a numerical value. */
4731  n2 = strlen30(azArg[1]);
4732  for(i=0; i<ArraySize(aCtrl); i++){
4733  if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
4734  if( testctrl<0 ){
4735  testctrl = aCtrl[i].ctrlCode;
4736  }else{
4737  utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
4738  testctrl = -1;
4739  break;
4740  }
4741  }
4742  }
4743  if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
4744  if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
4745  utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
4746  }else{
4747  switch(testctrl){
4748 
4749  /* sqlite3_test_control(int, db, int) */
4752  if( nArg==3 ){
4753  int opt = (int)strtol(azArg[2], 0, 0);
4754  rc2 = sqlite3_test_control(testctrl, p->db, opt);
4755  raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
4756  } else {
4757  utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
4758  azArg[1]);
4759  }
4760  break;
4761 
4762  /* sqlite3_test_control(int) */
4767  if( nArg==2 ){
4768  rc2 = sqlite3_test_control(testctrl);
4769  raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
4770  } else {
4771  utf8_printf(stderr,"Error: testctrl %s takes no options\n",
4772  azArg[1]);
4773  }
4774  break;
4775 
4776  /* sqlite3_test_control(int, uint) */
4778  if( nArg==3 ){
4779  unsigned int opt = (unsigned int)integerValue(azArg[2]);
4780  rc2 = sqlite3_test_control(testctrl, opt);
4781  raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
4782  } else {
4783  utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
4784  " int option\n", azArg[1]);
4785  }
4786  break;
4787 
4788  /* sqlite3_test_control(int, int) */
4792  if( nArg==3 ){
4793  int opt = booleanValue(azArg[2]);
4794  rc2 = sqlite3_test_control(testctrl, opt);
4795  raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
4796  } else {
4797  utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
4798  azArg[1]);
4799  }
4800  break;
4801 
4802  /* sqlite3_test_control(int, char *) */
4803 #ifdef SQLITE_N_KEYWORD
4805  if( nArg==3 ){
4806  const char *opt = azArg[2];
4807  rc2 = sqlite3_test_control(testctrl, opt);
4808  raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
4809  } else {
4810  utf8_printf(stderr,
4811  "Error: testctrl %s takes a single char * option\n",
4812  azArg[1]);
4813  }
4814  break;
4815 #endif
4816 
4818  if( nArg==5 ){
4819  rc2 = sqlite3_test_control(testctrl, p->db,
4820  azArg[2],
4821  integerValue(azArg[3]),
4822  integerValue(azArg[4]));
4823  raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
4824  }else{
4825  raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
4826  }
4827  break;
4828 
4833  default:
4834  utf8_printf(stderr,
4835  "Error: CLI support for testctrl %s not implemented\n",
4836  azArg[1]);
4837  break;
4838  }
4839  }
4840  }else
4841 
4842  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
4843  open_db(p, 0);
4844  sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
4845  }else
4846 
4847  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
4848  if( nArg==2 ){
4849  enableTimer = booleanValue(azArg[1]);
4850  if( enableTimer && !HAS_TIMER ){
4851  raw_printf(stderr, "Error: timer not available on this system.\n");
4852  enableTimer = 0;
4853  }
4854  }else{
4855  raw_printf(stderr, "Usage: .timer on|off\n");
4856  rc = 1;
4857  }
4858  }else
4859 
4860  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
4861  open_db(p, 0);
4862  if( nArg!=2 ){
4863  raw_printf(stderr, "Usage: .trace FILE|off\n");
4864  rc = 1;
4865  goto meta_command_exit;
4866  }
4868  p->traceOut = output_file_open(azArg[1]);
4869 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
4870  if( p->traceOut==0 ){
4871  sqlite3_trace_v2(p->db, 0, 0, 0);
4872  }else{
4874  }
4875 #endif
4876  }else
4877 
4878 #if SQLITE_USER_AUTHENTICATION
4879  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
4880  if( nArg<2 ){
4881  raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
4882  rc = 1;
4883  goto meta_command_exit;
4884  }
4885  open_db(p, 0);
4886  if( strcmp(azArg[1],"login")==0 ){
4887  if( nArg!=4 ){
4888  raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
4889  rc = 1;
4890  goto meta_command_exit;
4891  }
4892  rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
4893  (int)strlen(azArg[3]));
4894  if( rc ){
4895  utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
4896  rc = 1;
4897  }
4898  }else if( strcmp(azArg[1],"add")==0 ){
4899  if( nArg!=5 ){
4900  raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
4901  rc = 1;
4902  goto meta_command_exit;
4903  }
4904  rc = sqlite3_user_add(p->db, azArg[2],
4905  azArg[3], (int)strlen(azArg[3]),
4906  booleanValue(azArg[4]));
4907  if( rc ){
4908  raw_printf(stderr, "User-Add failed: %d\n", rc);
4909  rc = 1;
4910  }
4911  }else if( strcmp(azArg[1],"edit")==0 ){
4912  if( nArg!=5 ){
4913  raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
4914  rc = 1;
4915  goto meta_command_exit;
4916  }
4917  rc = sqlite3_user_change(p->db, azArg[2],
4918  azArg[3], (int)strlen(azArg[3]),
4919  booleanValue(azArg[4]));
4920  if( rc ){
4921  raw_printf(stderr, "User-Edit failed: %d\n", rc);
4922  rc = 1;
4923  }
4924  }else if( strcmp(azArg[1],"delete")==0 ){
4925  if( nArg!=3 ){
4926  raw_printf(stderr, "Usage: .user delete USER\n");
4927  rc = 1;
4928  goto meta_command_exit;
4929  }
4930  rc = sqlite3_user_delete(p->db, azArg[2]);
4931  if( rc ){
4932  raw_printf(stderr, "User-Delete failed: %d\n", rc);
4933  rc = 1;
4934  }
4935  }else{
4936  raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
4937  rc = 1;
4938  goto meta_command_exit;
4939  }
4940  }else
4941 #endif /* SQLITE_USER_AUTHENTICATION */
4942 
4943  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
4944  utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
4946  }else
4947 
4948  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
4949  const char *zDbName = nArg==2 ? azArg[1] : "main";
4950  sqlite3_vfs *pVfs;
4951  if( p->db ){
4952  sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
4953  if( pVfs ){
4954  utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
4955  raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
4956  raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
4957  raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
4958  }
4959  }
4960  }else
4961 
4962  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
4963  sqlite3_vfs *pVfs;
4964  sqlite3_vfs *pCurrent = 0;
4965  if( p->db ){
4966  sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
4967  }
4968  for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
4969  utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
4970  pVfs==pCurrent ? " <--- CURRENT" : "");
4971  raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
4972  raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
4973  raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
4974  if( pVfs->pNext ){
4975  raw_printf(p->out, "-----------------------------------\n");
4976  }
4977  }
4978  }else
4979 
4980  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
4981  const char *zDbName = nArg==2 ? azArg[1] : "main";
4982  char *zVfsName = 0;
4983  if( p->db ){
4984  sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
4985  if( zVfsName ){
4986  utf8_printf(p->out, "%s\n", zVfsName);
4987  sqlite3_free(zVfsName);
4988  }
4989  }
4990  }else
4991 
4992 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
4993  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
4994  sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
4995  }else
4996 #endif
4997 
4998  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
4999  int j;
5000  assert( nArg<=ArraySize(azArg) );
5001  for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
5002  p->colWidth[j-1] = (int)integerValue(azArg[j]);
5003  }
5004  }else
5005 
5006  {
5007  utf8_printf(stderr, "Error: unknown command or invalid arguments: "
5008  " \"%s\". Enter \".help\" for help\n", azArg[0]);
5009  rc = 1;
5010  }
5011 
5012 meta_command_exit:
5013  if( p->outCount ){
5014  p->outCount--;
5015  if( p->outCount==0 ) output_reset(p);
5016  }
5017  return rc;
5018 }
5019 
5020 /*
5021 ** Return TRUE if a semicolon occurs anywhere in the first N characters
5022 ** of string z[].
5023 */
5024 static int line_contains_semicolon(const char *z, int N){
5025  int i;
5026  for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
5027  return 0;
5028 }
5029 
5030 /*
5031 ** Test to see if a line consists entirely of whitespace.
5032 */
5033 static int _all_whitespace(const char *z){
5034  for(; *z; z++){
5035  if( IsSpace(z[0]) ) continue;
5036  if( *z=='/' && z[1]=='*' ){
5037  z += 2;
5038  while( *z && (*z!='*' || z[1]!='/') ){ z++; }
5039  if( *z==0 ) return 0;
5040  z++;
5041  continue;
5042  }
5043  if( *z=='-' && z[1]=='-' ){
5044  z += 2;
5045  while( *z && *z!='\n' ){ z++; }
5046  if( *z==0 ) return 1;
5047  continue;
5048  }
5049  return 0;
5050  }
5051  return 1;
5052 }
5053 
5054 /*
5055 ** Return TRUE if the line typed in is an SQL command terminator other
5056 ** than a semi-colon. The SQL Server style "go" command is understood
5057 ** as is the Oracle "/".
5058 */
5059 static int line_is_command_terminator(const char *zLine){
5060  while( IsSpace(zLine[0]) ){ zLine++; };
5061  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
5062  return 1; /* Oracle */
5063  }
5064  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
5065  && _all_whitespace(&zLine[2]) ){
5066  return 1; /* SQL Server */
5067  }
5068  return 0;
5069 }
5070 
5071 /*
5072 ** Return true if zSql is a complete SQL statement. Return false if it
5073 ** ends in the middle of a string literal or C-style comment.
5074 */
5075 static int line_is_complete(char *zSql, int nSql){
5076  int rc;
5077  if( zSql==0 ) return 1;
5078  zSql[nSql] = ';';
5079  zSql[nSql+1] = 0;
5080  rc = sqlite3_complete(zSql);
5081  zSql[nSql] = 0;
5082  return rc;
5083 }
5084 
5085 /*
5086 ** Read input from *in and process it. If *in==0 then input
5087 ** is interactive - the user is typing it it. Otherwise, input
5088 ** is coming from a file or device. A prompt is issued and history
5089 ** is saved only if input is interactive. An interrupt signal will
5090 ** cause this routine to exit immediately, unless input is interactive.
5091 **
5092 ** Return the number of errors.
5093 */
5094 static int process_input(ShellState *p, FILE *in){
5095  char *zLine = 0; /* A single input line */
5096  char *zSql = 0; /* Accumulated SQL text */
5097  int nLine; /* Length of current line */
5098  int nSql = 0; /* Bytes of zSql[] used */
5099  int nAlloc = 0; /* Allocated zSql[] space */
5100  int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
5101  char *zErrMsg; /* Error message returned */
5102  int rc; /* Error code */
5103  int errCnt = 0; /* Number of errors seen */
5104  int lineno = 0; /* Current line number */
5105  int startline = 0; /* Line number for start of current input */
5106 
5107  while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
5108  fflush(p->out);
5109  zLine = one_input_line(in, zLine, nSql>0);
5110  if( zLine==0 ){
5111  /* End of input */
5112  if( in==0 && stdin_is_interactive ) printf("\n");
5113  break;
5114  }
5115  if( seenInterrupt ){
5116  if( in!=0 ) break;
5117  seenInterrupt = 0;
5118  }
5119  lineno++;
5120  if( nSql==0 && _all_whitespace(zLine) ){
5121  if( p->echoOn ) printf("%s\n", zLine);
5122  continue;
5123  }
5124  if( zLine && zLine[0]=='.' && nSql==0 ){
5125  if( p->echoOn ) printf("%s\n", zLine);
5126  rc = do_meta_command(zLine, p);
5127  if( rc==2 ){ /* exit requested */
5128  break;
5129  }else if( rc ){
5130  errCnt++;
5131  }
5132  continue;
5133  }
5134  if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
5135  memcpy(zLine,";",2);
5136  }
5137  nLine = strlen30(zLine);
5138  if( nSql+nLine+2>=nAlloc ){
5139  nAlloc = nSql+nLine+100;
5140  zSql = realloc(zSql, nAlloc);
5141  if( zSql==0 ){
5142  raw_printf(stderr, "Error: out of memory\n");
5143  exit(1);
5144  }
5145  }
5146  nSqlPrior = nSql;
5147  if( nSql==0 ){
5148  int i;
5149  for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
5150  assert( nAlloc>0 && zSql!=0 );
5151  memcpy(zSql, zLine+i, nLine+1-i);
5152  startline = lineno;
5153  nSql = nLine-i;
5154  }else{
5155  zSql[nSql++] = '\n';
5156  memcpy(zSql+nSql, zLine, nLine+1);
5157  nSql += nLine;
5158  }
5159  if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
5160  && sqlite3_complete(zSql) ){
5161  p->cnt = 0;
5162  open_db(p, 0);
5163  if( p->backslashOn ) resolve_backslashes(zSql);
5164  BEGIN_TIMER;
5165  rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
5166  END_TIMER;
5167  if( rc || zErrMsg ){
5168  char zPrefix[100];
5169  if( in!=0 || !stdin_is_interactive ){
5170  sqlite3_snprintf(sizeof(zPrefix), zPrefix,
5171  "Error: near line %d:", startline);
5172  }else{
5173  sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
5174  }
5175  if( zErrMsg!=0 ){
5176  utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
5177  sqlite3_free(zErrMsg);
5178  zErrMsg = 0;
5179  }else{
5180  utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
5181  }
5182  errCnt++;
5183  }else if( p->countChanges ){
5184  raw_printf(p->out, "changes: %3d total_changes: %d\n",
5186  }
5187  nSql = 0;
5188  if( p->outCount ){
5189  output_reset(p);
5190  p->outCount = 0;
5191  }
5192  }else if( nSql && _all_whitespace(zSql) ){
5193  if( p->echoOn ) printf("%s\n", zSql);
5194  nSql = 0;
5195  }
5196  }
5197  if( nSql ){
5198  if( !_all_whitespace(zSql) ){
5199  utf8_printf(stderr, "Error: incomplete SQL: %s\n", zSql);
5200  errCnt++;
5201  }
5202  }
5203  free(zSql);
5204  free(zLine);
5205  return errCnt>0;
5206 }
5207 
5208 /*
5209 ** Return a pathname which is the user's home directory. A
5210 ** 0 return indicates an error of some kind.
5211 */
5212 static char *find_home_dir(int clearFlag){
5213  static char *home_dir = NULL;
5214  if( clearFlag ){
5215  free(home_dir);
5216  home_dir = 0;
5217  return 0;
5218  }
5219  if( home_dir ) return home_dir;
5220 
5221 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
5222  && !defined(__RTP__) && !defined(_WRS_KERNEL)
5223  {
5224  struct passwd *pwent;
5225  uid_t uid = getuid();
5226  if( (pwent=getpwuid(uid)) != NULL) {
5227  home_dir = pwent->pw_dir;
5228  }
5229  }
5230 #endif
5231 
5232 #if defined(_WIN32_WCE)
5233  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
5234  */
5235  home_dir = "/";
5236 #else
5237 
5238 #if defined(_WIN32) || defined(WIN32)
5239  if (!home_dir) {
5240  home_dir = getenv("USERPROFILE");
5241  }
5242 #endif
5243 
5244  if (!home_dir) {
5245  home_dir = getenv("HOME");
5246  }
5247 
5248 #if defined(_WIN32) || defined(WIN32)
5249  if (!home_dir) {
5250  char *zDrive, *zPath;
5251  int n;
5252  zDrive = getenv("HOMEDRIVE");
5253  zPath = getenv("HOMEPATH");
5254  if( zDrive && zPath ){
5255  n = strlen30(zDrive) + strlen30(zPath) + 1;
5256  home_dir = malloc( n );
5257  if( home_dir==0 ) return 0;
5258  sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
5259  return home_dir;
5260  }
5261  home_dir = "c:\\";
5262  }
5263 #endif
5264 
5265 #endif /* !_WIN32_WCE */
5266 
5267  if( home_dir ){
5268  int n = strlen30(home_dir) + 1;
5269  char *z = malloc( n );
5270  if( z ) memcpy(z, home_dir, n);
5271  home_dir = z;
5272  }
5273 
5274  return home_dir;
5275 }
5276 
5277 /*
5278 ** Read input from the file given by sqliterc_override. Or if that
5279 ** parameter is NULL, take input from ~/.sqliterc
5280 **
5281 ** Returns the number of errors.
5282 */
5283 static void process_sqliterc(
5284  ShellState *p, /* Configuration data */
5285  const char *sqliterc_override /* Name of config file. NULL to use default */
5286 ){
5287  char *home_dir = NULL;
5288  const char *sqliterc = sqliterc_override;
5289  char *zBuf = 0;
5290  FILE *in = NULL;
5291 
5292  if (sqliterc == NULL) {
5293  home_dir = find_home_dir(0);
5294  if( home_dir==0 ){
5295  raw_printf(stderr, "-- warning: cannot find home directory;"
5296  " cannot read ~/.sqliterc\n");
5297  return;
5298  }
5300  zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
5301  sqliterc = zBuf;
5302  }
5303  in = fopen(sqliterc,"rb");
5304  if( in ){
5305  if( stdin_is_interactive ){
5306  utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
5307  }
5308  process_input(p,in);
5309  fclose(in);
5310  }
5311  sqlite3_free(zBuf);
5312 }
5313 
5314 /*
5315 ** Show available command line options
5316 */
5317 static const char zOptions[] =
5318  " -ascii set output mode to 'ascii'\n"
5319  " -bail stop after hitting an error\n"
5320  " -batch force batch I/O\n"
5321  " -column set output mode to 'column'\n"
5322  " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
5323  " -csv set output mode to 'csv'\n"
5324  " -echo print commands before execution\n"
5325  " -init FILENAME read/process named file\n"
5326  " -[no]header turn headers on or off\n"
5327 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
5328  " -heap SIZE Size of heap for memsys3 or memsys5\n"
5329 #endif
5330  " -help show this message\n"
5331  " -html set output mode to HTML\n"
5332  " -interactive force interactive I/O\n"
5333  " -line set output mode to 'line'\n"
5334  " -list set output mode to 'list'\n"
5335  " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
5336  " -mmap N default mmap size set to N\n"
5337 #ifdef SQLITE_ENABLE_MULTIPLEX
5338  " -multiplex enable the multiplexor VFS\n"
5339 #endif
5340  " -newline SEP set output row separator. Default: '\\n'\n"
5341  " -nullvalue TEXT set text string for NULL values. Default ''\n"
5342  " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
5343  " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
5344  " -separator SEP set output column separator. Default: '|'\n"
5345  " -stats print memory stats before each finalize\n"
5346  " -version show SQLite version\n"
5347  " -vfs NAME use NAME as the default VFS\n"
5348 #ifdef SQLITE_ENABLE_VFSTRACE
5349  " -vfstrace enable tracing of all VFS calls\n"
5350 #endif
5351 ;
5352 static void usage(int showDetail){
5353  utf8_printf(stderr,
5354  "Usage: %s [OPTIONS] FILENAME [SQL]\n"
5355  "FILENAME is the name of an SQLite database. A new database is created\n"
5356  "if the file does not previously exist.\n", Argv0);
5357  if( showDetail ){
5358  utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
5359  }else{
5360  raw_printf(stderr, "Use the -help option for additional information\n");
5361  }
5362  exit(1);
5363 }
5364 
5365 /*
5366 ** Initialize the state information in data
5367 */
5368 static void main_init(ShellState *data) {
5369  memset(data, 0, sizeof(*data));
5370  data->normalMode = data->cMode = data->mode = MODE_List;
5371  data->autoExplain = 1;
5372  memcpy(data->colSeparator,SEP_Column, 2);
5373  memcpy(data->rowSeparator,SEP_Row, 2);
5374  data->showHeader = 0;
5375  data->shellFlgs = SHFLG_Lookaside;
5379  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
5380  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
5381 }
5382 
5383 /*
5384 ** Output text to the console in a font that attracts extra attention.
5385 */
5386 #ifdef _WIN32
5387 static void printBold(const char *zText){
5388  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
5389  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
5390  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
5391  SetConsoleTextAttribute(out,
5392  FOREGROUND_RED|FOREGROUND_INTENSITY
5393  );
5394  printf("%s", zText);
5395  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
5396 }
5397 #else
5398 static void printBold(const char *zText){
5399  printf("\033[1m%s\033[0m", zText);
5400 }
5401 #endif
5402 
5403 /*
5404 ** Get the argument to an --option. Throw an error and die if no argument
5405 ** is available.
5406 */
5407 static char *cmdline_option_value(int argc, char **argv, int i){
5408  if( i==argc ){
5409  utf8_printf(stderr, "%s: Error: missing argument to %s\n",
5410  argv[0], argv[argc-1]);
5411  exit(1);
5412  }
5413  return argv[i];
5414 }
5415 
5416 #ifndef SQLITE_SHELL_IS_UTF8
5417 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
5418 # define SQLITE_SHELL_IS_UTF8 (0)
5419 # else
5420 # define SQLITE_SHELL_IS_UTF8 (1)
5421 # endif
5422 #endif
5423 
5424 #if SQLITE_SHELL_IS_UTF8
5425 int SQLITE_CDECL main(int argc, char **argv){
5426 #else
5427 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
5428  char **argv;
5429 #endif
5430  char *zErrMsg = 0;
5431  ShellState data;
5432  const char *zInitFile = 0;
5433  int i;
5434  int rc = 0;
5435  int warnInmemoryDb = 0;
5436  int readStdin = 1;
5437  int nCmd = 0;
5438  char **azCmd = 0;
5439 
5440  setBinaryMode(stdin, 0);
5441  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
5442  stdin_is_interactive = isatty(0);
5443  stdout_is_console = isatty(1);
5444 
5445 #if USE_SYSTEM_SQLITE+0!=1
5446  if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
5447  utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
5449  exit(1);
5450  }
5451 #endif
5452  main_init(&data);
5453 #if !SQLITE_SHELL_IS_UTF8
5455  argv = sqlite3_malloc64(sizeof(argv[0])*argc);
5456  if( argv==0 ){
5457  raw_printf(stderr, "out of memory\n");
5458  exit(1);
5459  }
5460  for(i=0; i<argc; i++){
5461  argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
5462  if( argv[i]==0 ){
5463  raw_printf(stderr, "out of memory\n");
5464  exit(1);
5465  }
5466  }
5467 #endif
5468  assert( argc>=1 && argv && argv[0] );
5469  Argv0 = argv[0];
5470 
5471  /* Make sure we have a valid signal handler early, before anything
5472  ** else is done.
5473  */
5474 #ifdef SIGINT
5475  signal(SIGINT, interrupt_handler);
5476 #endif
5477 
5478 #ifdef SQLITE_SHELL_DBNAME_PROC
5479  {
5480  /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
5481  ** of a C-function that will provide the name of the database file. Use
5482  ** this compile-time option to embed this shell program in larger
5483  ** applications. */
5484  extern void SQLITE_SHELL_DBNAME_PROC(const char**);
5485  SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
5486  warnInmemoryDb = 0;
5487  }
5488 #endif
5489 
5490  /* Do an initial pass through the command-line argument to locate
5491  ** the name of the database file, the name of the initialization file,
5492  ** the size of the alternative malloc heap,
5493  ** and the first command to execute.
5494  */
5495  for(i=1; i<argc; i++){
5496  char *z;
5497  z = argv[i];
5498  if( z[0]!='-' ){
5499  if( data.zDbFilename==0 ){
5500  data.zDbFilename = z;
5501  }else{
5502  /* Excesss arguments are interpreted as SQL (or dot-commands) and
5503  ** mean that nothing is read from stdin */
5504  readStdin = 0;
5505  nCmd++;
5506  azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
5507  if( azCmd==0 ){
5508  raw_printf(stderr, "out of memory\n");
5509  exit(1);
5510  }
5511  azCmd[nCmd-1] = z;
5512  }
5513  }
5514  if( z[1]=='-' ) z++;
5515  if( strcmp(z,"-separator")==0
5516  || strcmp(z,"-nullvalue")==0
5517  || strcmp(z,"-newline")==0
5518  || strcmp(z,"-cmd")==0
5519  ){
5520  (void)cmdline_option_value(argc, argv, ++i);
5521  }else if( strcmp(z,"-init")==0 ){
5522  zInitFile = cmdline_option_value(argc, argv, ++i);
5523  }else if( strcmp(z,"-batch")==0 ){
5524  /* Need to check for batch mode here to so we can avoid printing
5525  ** informational messages (like from process_sqliterc) before
5526  ** we do the actual processing of arguments later in a second pass.
5527  */
5528  stdin_is_interactive = 0;
5529  }else if( strcmp(z,"-heap")==0 ){
5530 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
5531  const char *zSize;
5532  sqlite3_int64 szHeap;
5533 
5534  zSize = cmdline_option_value(argc, argv, ++i);
5535  szHeap = integerValue(zSize);
5536  if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
5537  sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
5538 #else
5539  (void)cmdline_option_value(argc, argv, ++i);
5540 #endif
5541  }else if( strcmp(z,"-scratch")==0 ){
5542  int n, sz;
5543  sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
5544  if( sz>400000 ) sz = 400000;
5545  if( sz<2500 ) sz = 2500;
5546  n = (int)integerValue(cmdline_option_value(argc,argv,++i));
5547  if( n>10 ) n = 10;
5548  if( n<1 ) n = 1;
5549  sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
5550  data.shellFlgs |= SHFLG_Scratch;
5551  }else if( strcmp(z,"-pagecache")==0 ){
5552  int n, sz;
5553  sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
5554  if( sz>70000 ) sz = 70000;
5555  if( sz<0 ) sz = 0;
5556  n = (int)integerValue(cmdline_option_value(argc,argv,++i));
5558  (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
5559  data.shellFlgs |= SHFLG_Pagecache;
5560  }else if( strcmp(z,"-lookaside")==0 ){
5561  int n, sz;
5562  sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
5563  if( sz<0 ) sz = 0;
5564  n = (int)integerValue(cmdline_option_value(argc,argv,++i));
5565  if( n<0 ) n = 0;
5567  if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
5568 #ifdef SQLITE_ENABLE_VFSTRACE
5569  }else if( strcmp(z,"-vfstrace")==0 ){
5570  extern int vfstrace_register(
5571  const char *zTraceName,
5572  const char *zOldVfsName,
5573  int (*xOut)(const char*,void*),
5574  void *pOutArg,
5575  int makeDefault
5576  );
5577  vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
5578 #endif
5579 #ifdef SQLITE_ENABLE_MULTIPLEX
5580  }else if( strcmp(z,"-multiplex")==0 ){
5581  extern int sqlite3_multiple_initialize(const char*,int);
5582  sqlite3_multiplex_initialize(0, 1);
5583 #endif
5584  }else if( strcmp(z,"-mmap")==0 ){
5585  sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
5587  }else if( strcmp(z,"-vfs")==0 ){
5588  sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
5589  if( pVfs ){
5590  sqlite3_vfs_register(pVfs, 1);
5591  }else{
5592  utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
5593  exit(1);
5594  }
5595  }
5596  }
5597  if( data.zDbFilename==0 ){
5598 #ifndef SQLITE_OMIT_MEMORYDB
5599  data.zDbFilename = ":memory:";
5600  warnInmemoryDb = argc==1;
5601 #else
5602  utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
5603  return 1;
5604 #endif
5605  }
5606  data.out = stdout;
5607 
5608  /* Go ahead and open the database file if it already exists. If the
5609  ** file does not exist, delay opening it. This prevents empty database
5610  ** files from being created if a user mistypes the database name argument
5611  ** to the sqlite command-line tool.
5612  */
5613  if( access(data.zDbFilename, 0)==0 ){
5614  open_db(&data, 0);
5615  }
5616 
5617  /* Process the initialization file if there is one. If no -init option
5618  ** is given on the command line, look for a file named ~/.sqliterc and
5619  ** try to process it.
5620  */
5621  process_sqliterc(&data,zInitFile);
5622 
5623  /* Make a second pass through the command-line argument and set
5624  ** options. This second pass is delayed until after the initialization
5625  ** file is processed so that the command-line arguments will override
5626  ** settings in the initialization file.
5627  */
5628  for(i=1; i<argc; i++){
5629  char *z = argv[i];
5630  if( z[0]!='-' ) continue;
5631  if( z[1]=='-' ){ z++; }
5632  if( strcmp(z,"-init")==0 ){
5633  i++;
5634  }else if( strcmp(z,"-html")==0 ){
5635  data.mode = MODE_Html;
5636  }else if( strcmp(z,"-list")==0 ){
5637  data.mode = MODE_List;
5638  }else if( strcmp(z,"-line")==0 ){
5639  data.mode = MODE_Line;
5640  }else if( strcmp(z,"-column")==0 ){
5641  data.mode = MODE_Column;
5642  }else if( strcmp(z,"-csv")==0 ){
5643  data.mode = MODE_Csv;
5644  memcpy(data.colSeparator,",",2);
5645  }else if( strcmp(z,"-ascii")==0 ){
5646  data.mode = MODE_Ascii;
5647  sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
5648  SEP_Unit);
5649  sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
5650  SEP_Record);
5651  }else if( strcmp(z,"-separator")==0 ){
5652  sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
5653  "%s",cmdline_option_value(argc,argv,++i));
5654  }else if( strcmp(z,"-newline")==0 ){
5655  sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
5656  "%s",cmdline_option_value(argc,argv,++i));
5657  }else if( strcmp(z,"-nullvalue")==0 ){
5658  sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
5659  "%s",cmdline_option_value(argc,argv,++i));
5660  }else if( strcmp(z,"-header")==0 ){
5661  data.showHeader = 1;
5662  }else if( strcmp(z,"-noheader")==0 ){
5663  data.showHeader = 0;
5664  }else if( strcmp(z,"-echo")==0 ){
5665  data.echoOn = 1;
5666  }else if( strcmp(z,"-eqp")==0 ){
5667  data.autoEQP = 1;
5668  }else if( strcmp(z,"-eqpfull")==0 ){
5669  data.autoEQP = 2;
5670  }else if( strcmp(z,"-stats")==0 ){
5671  data.statsOn = 1;
5672  }else if( strcmp(z,"-scanstats")==0 ){
5673  data.scanstatsOn = 1;
5674  }else if( strcmp(z,"-backslash")==0 ){
5675  /* Undocumented command-line option: -backslash
5676  ** Causes C-style backslash escapes to be evaluated in SQL statements
5677  ** prior to sending the SQL into SQLite. Useful for injecting
5678  ** crazy bytes in the middle of SQL statements for testing and debugging.
5679  */
5680  data.backslashOn = 1;
5681  }else if( strcmp(z,"-bail")==0 ){
5682  bail_on_error = 1;
5683  }else if( strcmp(z,"-version")==0 ){
5684  printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
5685  return 0;
5686  }else if( strcmp(z,"-interactive")==0 ){
5687  stdin_is_interactive = 1;
5688  }else if( strcmp(z,"-batch")==0 ){
5689  stdin_is_interactive = 0;
5690  }else if( strcmp(z,"-heap")==0 ){
5691  i++;
5692  }else if( strcmp(z,"-scratch")==0 ){
5693  i+=2;
5694  }else if( strcmp(z,"-pagecache")==0 ){
5695  i+=2;
5696  }else if( strcmp(z,"-lookaside")==0 ){
5697  i+=2;
5698  }else if( strcmp(z,"-mmap")==0 ){
5699  i++;
5700  }else if( strcmp(z,"-vfs")==0 ){
5701  i++;
5702 #ifdef SQLITE_ENABLE_VFSTRACE
5703  }else if( strcmp(z,"-vfstrace")==0 ){
5704  i++;
5705 #endif
5706 #ifdef SQLITE_ENABLE_MULTIPLEX
5707  }else if( strcmp(z,"-multiplex")==0 ){
5708  i++;
5709 #endif
5710  }else if( strcmp(z,"-help")==0 ){
5711  usage(1);
5712  }else if( strcmp(z,"-cmd")==0 ){
5713  /* Run commands that follow -cmd first and separately from commands
5714  ** that simply appear on the command-line. This seems goofy. It would
5715  ** be better if all commands ran in the order that they appear. But
5716  ** we retain the goofy behavior for historical compatibility. */
5717  if( i==argc-1 ) break;
5718  z = cmdline_option_value(argc,argv,++i);
5719  if( z[0]=='.' ){
5720  rc = do_meta_command(z, &data);
5721  if( rc && bail_on_error ) return rc==2 ? 0 : rc;
5722  }else{
5723  open_db(&data, 0);
5724  rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
5725  if( zErrMsg!=0 ){
5726  utf8_printf(stderr,"Error: %s\n", zErrMsg);
5727  if( bail_on_error ) return rc!=0 ? rc : 1;
5728  }else if( rc!=0 ){
5729  utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
5730  if( bail_on_error ) return rc;
5731  }
5732  }
5733  }else{
5734  utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
5735  raw_printf(stderr,"Use -help for a list of options.\n");
5736  return 1;
5737  }
5738  data.cMode = data.mode;
5739  }
5740 
5741  if( !readStdin ){
5742  /* Run all arguments that do not begin with '-' as if they were separate
5743  ** command-line inputs, except for the argToSkip argument which contains
5744  ** the database filename.
5745  */
5746  for(i=0; i<nCmd; i++){
5747  if( azCmd[i][0]=='.' ){
5748  rc = do_meta_command(azCmd[i], &data);
5749  if( rc ) return rc==2 ? 0 : rc;
5750  }else{
5751  open_db(&data, 0);
5752  rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
5753  if( zErrMsg!=0 ){
5754  utf8_printf(stderr,"Error: %s\n", zErrMsg);
5755  return rc!=0 ? rc : 1;
5756  }else if( rc!=0 ){
5757  utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
5758  return rc;
5759  }
5760  }
5761  }
5762  free(azCmd);
5763  }else{
5764  /* Run commands received from standard input
5765  */
5766  if( stdin_is_interactive ){
5767  char *zHome;
5768  char *zHistory = 0;
5769  int nHistory;
5770  printf(
5771  "SQLite version %s %.19s\n" /*extra-version-info*/
5772  "Enter \".help\" for usage hints.\n",
5774  );
5775  if( warnInmemoryDb ){
5776  printf("Connected to a ");
5777  printBold("transient in-memory database");
5778  printf(".\nUse \".open FILENAME\" to reopen on a "
5779  "persistent database.\n");
5780  }
5781  zHome = find_home_dir(0);
5782  if( zHome ){
5783  nHistory = strlen30(zHome) + 20;
5784  if( (zHistory = malloc(nHistory))!=0 ){
5785  sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
5786  }
5787  }
5788  if( zHistory ){ shell_read_history(zHistory); }
5789  rc = process_input(&data, 0);
5790  if( zHistory ){
5791  shell_stifle_history(100);
5792  shell_write_history(zHistory);
5793  free(zHistory);
5794  }
5795  }else{
5796  rc = process_input(&data, stdin);
5797  }
5798  }
5799  set_table_name(&data, 0);
5800  if( data.db ){
5801  session_close_all(&data);
5802  sqlite3_close(data.db);
5803  }
5804  sqlite3_free(data.zFreeOnClose);
5805  find_home_dir(1);
5806 #if !SQLITE_SHELL_IS_UTF8
5807  for(i=0; i<argc; i++) sqlite3_free(argv[i]);
5808  sqlite3_free(argv);
5809 #endif
5810  return rc;
5811 }
static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p)
Definition: shell.c:2642
#define UNUSED_PARAMETER(x)
Definition: shell.c:326
#define sqlite3_total_changes
Definition: sqlite3ext.h:415
int nIndent
Definition: shell.c:647
char outfile[FILENAME_MAX]
Definition: shell.c:640
#define SQLITE_ABORT
Definition: sqlite3.c:679
#define SQLITE_LOCKED
Definition: sqlite3.c:681
const char * zFile
Definition: shell.c:2605
static char zHelp[]
Definition: shell.c:2138
#define SQLITE_DBSTATUS_CACHE_HIT
Definition: sqlite3.c:7259
static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol)
Definition: shell.c:2003
#define sqlite3_step
Definition: sqlite3ext.h:412
int(* xRead)(sqlite3_file *, void *, int iAmt, sqlite3_int64 iOfst)
Definition: sqlite3.c:1008
#define SEP_Space
Definition: shell.c:698
static int shellDatabaseError(sqlite3 *db)
Definition: shell.c:3079
#define SQLITE_STMTSTATUS_AUTOINDEX
Definition: sqlite3.c:7332
static int shellAuth(void *pClientData, int op, const char *zA1, const char *zA2, const char *zA3, const char *zA4)
Definition: shell.c:905
#define SQLITE_STATUS_PAGECACHE_SIZE
Definition: sqlite3.c:7121
#define SQLITE_TEXT
Definition: sqlite3.c:4394
#define SQLITE_LIMIT_ATTACHED
Definition: sqlite3.c:3680
#define SQLITE_CORRUPT
Definition: sqlite3.c:686
int(* xCurrentTime)(sqlite3_vfs *, double *)
Definition: sqlite3.c:1504
int cColSep
Definition: shell.c:2612
static FILE * output_file_open(const char *zFile)
Definition: shell.c:2553
#define sqlite3_set_authorizer
Definition: sqlite3ext.h:409
const char * zDbFilename
Definition: shell.c:641
#define SEP_Column
Definition: shell.c:695
#define SQLITE_DBSTATUS_CACHE_WRITE
Definition: sqlite3.c:7261
#define sqlite3_errcode
Definition: sqlite3ext.h:364
const char * zVfs
Definition: shell.c:643
static int hexDigitValue(char c)
Definition: shell.c:2465
int cTerm
Definition: shell.c:2611
static int shellNomemError(void)
Definition: shell.c:3088
#define sqlite3_get_autocommit
Definition: sqlite3ext.h:374
#define SQLITE_DBSTATUS_LOOKASIDE_HIT
Definition: sqlite3.c:7256
static const char zOptions[]
Definition: shell.c:5317
int colWidth[100]
Definition: shell.c:636
#define SQLITE_NOMEM
Definition: sqlite3.c:682
static int sql_trace_callback(unsigned mType, void *pArg, void *pP, void *pX)
Definition: shell.c:2573
#define SQLITE_API
Definition: sqlite3.c:312
static void main_init(ShellState *data)
Definition: shell.c:5368
static char * find_home_dir(int clearFlag)
Definition: shell.c:5212
#define sqlite3_stricmp
Definition: sqlite3ext.h:507
#define IsDigit(X)
Definition: shell.c:136
static void display_scanstats(sqlite3 *db, ShellState *pArg)
Definition: shell.c:1594
#define SQLITE_TESTCTRL_ISKEYWORD
Definition: sqlite3.c:6983
#define sqlite3_malloc
Definition: sqlite3ext.h:384
#define SQLITE_SCANSTAT_NLOOP
Definition: sqlite3.c:8308
static char * Argv0
Definition: shell.c:363
f
int backslashOn
Definition: shell.c:619
#define sqlite3_status
Definition: sqlite3ext.h:474
#define sqlite3_open
Definition: sqlite3ext.h:386
#define shell_read_history(X)
Definition: shell.c:93
#define SQLITE_STATUS_MALLOC_SIZE
Definition: sqlite3.c:7119
#define SQLITE_STMTSTATUS_SORT
Definition: sqlite3.c:7331
static void disable_debug_trace_modes(void)
Definition: shell.c:1771
int mode
Definition: shell.c:601
#define MODE_Line
Definition: shell.c:665
int szOsFile
Definition: sqlite3.c:1488
static void open_db(ShellState *p, int keepAlive)
Definition: shell.c:2376
#define sqlite3_backup_finish
Definition: sqlite3ext.h:475
#define sqlite3_value_text
Definition: sqlite3ext.h:429
int nErr
Definition: shell.c:624
static const char * zShellStatic
Definition: shell.c:466
#define SEP_Record
Definition: shell.c:702
int mode
Definition: shell.c:625
#define sqlite3_backup_init
Definition: sqlite3ext.h:476
#define sqlite3_column_name
Definition: sqlite3ext.h:341
int SQLITE_CDECL main(int argc, char **argv)
Definition: shell.c:5425
SQLITE_API int sqlite3_config(int,...)
Definition: sqlite3.c:138205
#define sqlite3_errmsg
Definition: sqlite3ext.h:365
static void exec_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt, int(*xCallback)(void *, int, char **, char **, int *))
Definition: shell.c:1793
#define SQLITE_TESTCTRL_ASSERT
Definition: sqlite3.c:6979
static unsigned int get2byteInt(unsigned char *a)
Definition: shell.c:2985
#define sqlite3_strlike
Definition: sqlite3ext.h:536
#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
Definition: sqlite3.c:7257
#define SQLITE_CONFIG_PAGECACHE
Definition: sqlite3.c:2134
int outCount
Definition: shell.c:620
static const char needCsvQuote[]
Definition: shell.c:832
static void writefileFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: shell.c:2300
#define SQLITE_ROW
Definition: sqlite3.c:704
#define SQLITE_DBSTATUS_STMT_USED
Definition: sqlite3.c:7255
int pclose(FILE *)
#define SQLITE_TESTCTRL_RESERVE
Definition: sqlite3.c:6981
#define SQLITE_BLOB
Definition: sqlite3.c:4389
#define MODE_Insert
Definition: shell.c:670
#define SQLITE_SOURCE_ID
Definition: sqlite3.c:386
#define sqlite3_result_int64
Definition: sqlite3ext.h:401
#define SQLITE_LIMIT_VARIABLE_NUMBER
Definition: sqlite3.c:3682
static int line_is_complete(char *zSql, int nSql)
Definition: shell.c:5075
int cMode
Definition: shell.c:626
#define SQLITE_DONE
Definition: sqlite3.c:705
static void output_reset(ShellState *p)
Definition: shell.c:2956
#define SQLITE_UTF8
Definition: sqlite3.c:4756
int cRowSep
Definition: shell.c:2613
int valid
Definition: shell.c:600
#define MODE_Html
Definition: shell.c:669
static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType)
Definition: shell.c:952
int normalMode
Definition: shell.c:627
static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql)
Definition: shell.c:1671
#define MODE_Column
Definition: shell.c:666
#define sqlite3_realloc64
Definition: sqlite3ext.h:521
#define sqlite3_create_function
Definition: sqlite3ext.h:356
int autoEQP
Definition: shell.c:615
#define SQLITE_INTEGER
Definition: sqlite3.c:4387
static int stdout_is_console
Definition: shell.c:345
int mxPathname
Definition: sqlite3.c:1489
#define session_close_all(X)
Definition: shell.c:2354
static char * readFile(const char *zName)
Definition: shell.c:2253
#define sqlite3_column_int64
Definition: sqlite3ext.h:340
#define SQLITE_TESTCTRL_PRNG_SAVE
Definition: sqlite3.c:6972
#define sqlite3_exec
Definition: sqlite3ext.h:367
static double timeDiff(struct timeval *pStart, struct timeval *pEnd)
Definition: shell.c:216
char rowSeparator[20]
Definition: shell.c:635
#define BEGIN_TIMER
Definition: shell.c:236
sqlite3 * db
Definition: shell.c:612
#define setBinaryMode(X, Y)
Definition: shell.c:165
static volatile int seenInterrupt
Definition: shell.c:357
static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p)
Definition: shell.c:2716
#define SQLITE_STATUS_SCRATCH_OVERFLOW
Definition: sqlite3.c:7118
int * aiIndent
Definition: shell.c:646
#define IsSpace(X)
Definition: shell.c:135
#define SQLITE_LIMIT_COLUMN
Definition: sqlite3.c:3675
sqlite3_vfs * pNext
Definition: sqlite3.c:1490
int actualWidth[100]
Definition: shell.c:637
static void explain_data_delete(ShellState *p)
Definition: shell.c:1753
#define SQLITE_DBSTATUS_LOOKASIDE_USED
Definition: sqlite3.c:7252
#define sqlite3_finalize
Definition: sqlite3ext.h:371
static void set_table_name(ShellState *p, const char *zName)
Definition: shell.c:1273
#define SQLITE_CONFIG_SCRATCH
Definition: sqlite3.c:2133
SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff)
Definition: sqlite3.c:110893
int nAlloc
Definition: shell.c:2609
#define sqlite3_column_int
Definition: sqlite3ext.h:339
int countChanges
Definition: shell.c:618
#define sqlite3_malloc64
Definition: sqlite3ext.h:519
#define MODE_Pretty
Definition: shell.c:675
#define SQLITE_TESTCTRL_LAST
Definition: sqlite3.c:6994
int shellDeleteFile(const char *zFilename)
Definition: shell.c:3205
static int optionMatch(const char *zStr, const char *zOpt)
Definition: shell.c:3195
#define SQLITE_CONFIG_HEAP
Definition: sqlite3.c:2135
int writableSchema
Definition: shell.c:628
#define SEP_Unit
Definition: shell.c:701
#define sqlite3_column_text
Definition: sqlite3ext.h:347
static void output_quoted_string(FILE *out, const char *z)
Definition: shell.c:733
#define SQLITE_LIMIT_COMPOUND_SELECT
Definition: sqlite3.c:3677
int showHeader
Definition: shell.c:602
static unsigned int get4byteInt(unsigned char *a)
Definition: shell.c:2988
#define sqlite3_reset
Definition: sqlite3ext.h:395
static int isNumber(const char *z, int *realnum)
Definition: shell.c:434
#define SQLITE_TESTCTRL_PRNG_RESTORE
Definition: sqlite3.c:6973
#define SEP_Tab
Definition: shell.c:697
char zTestcase[30]
Definition: shell.c:633
static int line_contains_semicolon(const char *z, int N)
Definition: shell.c:5024
#define SQLITE_LIMIT_LENGTH
Definition: sqlite3.c:3673
#define MODE_Tcl
Definition: shell.c:671
#define sqlite3_mprintf
Definition: sqlite3ext.h:385
#define SQLITE_BUSY
Definition: sqlite3.c:680
struct sqlite3_stmt sqlite3_stmt
Definition: sqlite3.c:3573
#define SQLITE_TESTCTRL_BYTEORDER
Definition: sqlite3.c:6990
static char * save_err_msg(sqlite3 *db)
Definition: shell.c:1412
#define SQLITE_CDECL
Definition: sqlite3.c:315
static int strlen30(const char *z)
Definition: shell.c:484
#define SQLITE_CONFIG_URI
Definition: sqlite3.c:2144
#define sqlite3_snprintf
Definition: sqlite3ext.h:411
#define sqlite3_vmprintf
Definition: sqlite3ext.h:434
#define SQLITE_STATUS_PARSER_STACK
Definition: sqlite3.c:7120
#define SQLITE_TESTCTRL_SCRATCHMALLOC
Definition: sqlite3.c:6984
#define SEP_Row
Definition: shell.c:696
#define END_TIMER
Definition: shell.c:237
char * z
Definition: shell.c:2607
char colSeparator[20]
Definition: shell.c:634
#define sqlite3_vfs_find
Definition: sqlite3ext.h:461
#define sqlite3_bind_int64
Definition: sqlite3ext.h:316
int isatty(int)
#define SQLITE_CONFIG_LOOKASIDE
Definition: sqlite3.c:2140
static void endTimer(void)
Definition: shell.c:224
static struct rusage sBegin
Definition: shell.c:202
static int shell_exec(sqlite3 *db, const char *zSql, int(*xCallback)(void *, int, char **, char **, int *), ShellState *pArg, char **pzErrMsg)
Definition: shell.c:1867
#define SQLITE_FCNTL_VFSNAME
Definition: sqlite3.c:1281
#define SQLITE_LIMIT_WORKER_THREADS
Definition: sqlite3.c:3684
sqlite_int64 sqlite3_int64
Definition: sqlite3.c:530
#define SQLITE_STATUS_SCRATCH_USED
Definition: sqlite3.c:7117
#define sqlite3_bind_double
Definition: sqlite3ext.h:314
static void tryToCloneSchema(ShellState *p, sqlite3 *newDb, const char *zWhere, void(*xForEach)(ShellState *, sqlite3 *, const char *))
Definition: shell.c:2856
int scanstatsOn
Definition: shell.c:617
static void resolve_backslashes(char *z)
Definition: shell.c:2417
#define sqlite3_limit
Definition: sqlite3ext.h:471
static sqlite3 * globalDb
Definition: shell.c:352
int iIndent
Definition: shell.c:648
#define sqlite3_sql
Definition: sqlite3ext.h:473
#define sqlite3_libversion
Definition: sqlite3ext.h:382
static char * cmdline_option_value(int argc, char **argv, int i)
Definition: shell.c:5407
#define SQLITE_CONFIG_LOG
Definition: sqlite3.c:2143
#define SQLITE_STMTSTATUS_VM_STEP
Definition: sqlite3.c:7333
#define sqlite3_value_blob
Definition: sqlite3ext.h:422
SQLITE_API int sqlite3_initialize(void)
Definition: sqlite3.c:137985
#define HAS_TIMER
Definition: shell.c:238
static int testcase_glob(const char *zGlob, const char *z)
Definition: shell.c:3116
static void tryToCloneData(ShellState *p, sqlite3 *newDb, const char *zTable)
Definition: shell.c:2743
#define SHFLG_Scratch
Definition: shell.c:658
char * zFreeOnClose
Definition: shell.c:642
#define sqlite3_strnicmp
Definition: sqlite3ext.h:491
#define sqlite3_bind_null
Definition: sqlite3ext.h:317
#define sqlite3_result_text
Definition: sqlite3ext.h:403
#define SQLITE_DBSTATUS_CACHE_USED
Definition: sqlite3.c:7253
#define SQLITE_DBSTATUS_SCHEMA_USED
Definition: sqlite3.c:7254
#define SQLITE_TESTCTRL_BITVEC_TEST
Definition: sqlite3.c:6975
int iVersion
Definition: sqlite3.c:1487
#define SQLITE_SCANSTAT_NVISIT
Definition: sqlite3.c:8309
int nCheck
Definition: shell.c:630
static int line_is_command_terminator(const char *zLine)
Definition: shell.c:5059
static char mainPrompt[20]
Definition: shell.c:369
Definition: sqlite3.c:17871
int(* xCurrentTimeInt64)(sqlite3_vfs *, sqlite3_int64 *)
Definition: sqlite3.c:1510
#define SQLITE_CONFIG_MMAP_SIZE
Definition: sqlite3.c:2149
static void beginTimer(void)
Definition: shell.c:208
static int run_table_dump_query(ShellState *p, const char *zSelect, const char *zFirstRow)
Definition: shell.c:1362
TFSIMD_FORCE_INLINE const tfScalar & x() const
#define sqlite3_column_count
Definition: sqlite3ext.h:333
static int _all_whitespace(const char *z)
Definition: shell.c:5033
int n
Definition: shell.c:2608
static int stdin_is_interactive
Definition: shell.c:338
#define sqlite3_interrupt
Definition: sqlite3ext.h:380
#define SEP_Comma
Definition: shell.c:699
#define MODE_Csv
Definition: shell.c:672
#define sqlite3_close
Definition: sqlite3ext.h:327
#define sqlite3_column_type
Definition: sqlite3ext.h:349
#define sqlite3_bind_blob
Definition: sqlite3ext.h:313
#define sqlite3_column_double
Definition: sqlite3ext.h:338
#define shell_write_history(X)
Definition: shell.c:94
#define sqlite3_db_status
Definition: sqlite3ext.h:485
static char * one_input_line(FILE *in, char *zPrior, int isContinuation)
Definition: shell.c:561
#define MODE_Explain
Definition: shell.c:673
#define SQLITE_CONFIG_MULTITHREAD
Definition: sqlite3.c:2129
int nLine
Definition: shell.c:2610
static void output_file_close(FILE *f)
Definition: shell.c:2544
static char * appendText(char *zIn, char const *zAppend, char quote)
Definition: shell.c:1314
const struct sqlite3_io_methods * pMethods
Definition: sqlite3.c:911
static void import_append_char(ImportCtx *p, int c)
Definition: shell.c:2617
TFSIMD_FORCE_INLINE const tfScalar & z() const
int autoExplain
Definition: shell.c:614
#define SQLITE_STATUS_MALLOC_COUNT
Definition: sqlite3.c:7123
#define MODE_List
Definition: shell.c:667
FILE * popen(const char *, const char *)
char nullValue[20]
Definition: shell.c:638
int statsOn
Definition: shell.c:616
SQLITE_API int sqlite3_stmt_scanstatus(sqlite3_stmt *pStmt, int idx, int iScanStatusOp, void *pOut)
#define SQLITE_TESTCTRL_NEVER_CORRUPT
Definition: sqlite3.c:6988
#define sqlite3_free
Definition: sqlite3ext.h:372
static int process_input(ShellState *p, FILE *in)
Definition: shell.c:5094
#define sqlite3_strglob
Definition: sqlite3ext.h:525
FILE * out
Definition: shell.c:622
#define SQLITE_FCNTL_FILE_POINTER
Definition: sqlite3.c:1276
static void output_csv(ShellState *p, const char *z, int bSep)
Definition: shell.c:857
#define sqlite3_prepare_v2
Definition: sqlite3ext.h:437
#define shell_stifle_history(X)
Definition: shell.c:95
#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS
Definition: sqlite3.c:6977
long long int sqlite_int64
Definition: sqlite3.c:527
#define sqlite3_test_control
Definition: sqlite3ext.h:467
#define SQLITE_TRACE_STMT
Definition: sqlite3.c:3141
TFSIMD_FORCE_INLINE const tfScalar & w() const
#define SQLITE_TESTCTRL_PENDING_BYTE
Definition: sqlite3.c:6978
#define SQLITE_TESTCTRL_FIRST
Definition: sqlite3.c:6971
const char * zName
Definition: sqlite3.c:1491
static void shellLog(void *pArg, int iErrCode, const char *zMsg)
Definition: shell.c:712
char * zDestTable
Definition: shell.c:632
#define sqlite3_extended_errcode
Definition: sqlite3ext.h:486
#define ToLower(X)
Definition: shell.c:137
#define sqlite3_changes
Definition: sqlite3ext.h:326
#define SQLITE_FCNTL_VFS_POINTER
Definition: sqlite3.c:1295
static int run_schema_dump_query(ShellState *p, const char *zQuery)
Definition: shell.c:2104
#define MODE_Semi
Definition: shell.c:668
#define sqlite3_result_blob
Definition: sqlite3ext.h:396
unsigned shellFlgs
Definition: shell.c:631
static void readfileFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: shell.c:2279
#define SQLITE_STATUS_MEMORY_USED
Definition: sqlite3.c:7114
int echoOn
Definition: shell.c:613
static int booleanValue(char *zArg)
Definition: shell.c:2522
#define SQLITE_TRANSIENT
Definition: sqlite3.c:5029
#define sqlite3_load_extension
Definition: sqlite3ext.h:518
#define SQLITE_STATUS_SCRATCH_SIZE
Definition: sqlite3.c:7122
#define SQLITE_FLOAT
Definition: sqlite3.c:4388
#define sqlite3_vfs_register
Definition: sqlite3ext.h:462
int cnt
Definition: shell.c:621
#define SEP_CrLf
Definition: shell.c:700
#define SQLITE_SCANSTAT_EXPLAIN
Definition: sqlite3.c:8312
#define SQLITE_LIMIT_TRIGGER_DEPTH
Definition: sqlite3.c:3683
static int do_meta_command(char *zLine, ShellState *p)
Definition: shell.c:3223
#define sqlite3_busy_timeout
Definition: sqlite3ext.h:325
static const char * modeDescr[]
Definition: shell.c:677
static void process_sqliterc(ShellState *p, const char *sqliterc_override)
Definition: shell.c:5283
#define sqlite3_sourceid
Definition: sqlite3ext.h:489
#define raw_printf
Definition: shell.c:401
#define sqlite3_stmt_status
Definition: sqlite3ext.h:490
static void output_c_string(FILE *out, const char *z)
Definition: shell.c:765
static int str_in_array(const char *zStr, const char **azArray)
Definition: shell.c:1645
static void test_breakpoint(void)
Definition: shell.c:2595
static void shellstaticFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: shell.c:467
#define SQLITE_OK
Definition: sqlite3.c:674
static int db_int(ShellState *p, const char *zSql)
Definition: shell.c:2971
static void tryToClone(ShellState *p, const char *zNewDb)
Definition: shell.c:2931
#define sqlite3_complete
Definition: sqlite3ext.h:352
#define MODE_Ascii
Definition: shell.c:674
#define ArraySize(X)
Definition: shell.c:707
#define SQLITE_LIMIT_EXPR_DEPTH
Definition: sqlite3.c:3676
#define SQLITE_STATUS_PAGECACHE_USED
Definition: sqlite3.c:7115
#define SQLITE_TESTCTRL_ALWAYS
Definition: sqlite3.c:6980
#define sqlite3_sleep
Definition: sqlite3ext.h:459
#define sqlite3_column_bytes
Definition: sqlite3ext.h:331
static void output_hex_blob(FILE *out, const void *pBlob, int nBlob)
Definition: shell.c:722
#define sqlite3_backup_step
Definition: sqlite3ext.h:479
#define SQLITE_STATUS_PAGECACHE_OVERFLOW
Definition: sqlite3.c:7116
#define SHFLG_Lookaside
Definition: shell.c:660
#define SQLITE_TESTCTRL_PRNG_RESET
Definition: sqlite3.c:6974
#define utf8_printf
Definition: shell.c:393
#define sqlite3_file_control
Definition: sqlite3ext.h:447
static char continuePrompt[20]
Definition: shell.c:370
#define SQLITE_LIMIT_FUNCTION_ARG
Definition: sqlite3.c:3679
static void restore_debug_trace_modes(void)
Definition: shell.c:1781
#define SQLITE_STMTSTATUS_FULLSCAN_STEP
Definition: sqlite3.c:7330
static void printBold(const char *zText)
Definition: shell.c:5398
#define SQLITE_TESTCTRL_OPTIMIZATIONS
Definition: sqlite3.c:6982
#define sqlite3_bind_text
Definition: sqlite3ext.h:321
#define SQLITE_TESTCTRL_FAULT_INSTALL
Definition: sqlite3.c:6976
#define SQLITE_LIMIT_SQL_LENGTH
Definition: sqlite3.c:3674
static int bail_on_error
Definition: shell.c:332
#define SQLITE_SCANSTAT_SELECTID
Definition: sqlite3.c:8313
static sqlite3_int64 iBegin
Definition: shell.c:203
#define setTextMode(X, Y)
Definition: shell.c:166
static int enableTimer
Definition: shell.c:171
#define SQLITE_DBSTATUS_CACHE_MISS
Definition: sqlite3.c:7260
sqlite3_stmt * pStmt
Definition: shell.c:644
#define SHFLG_Pagecache
Definition: shell.c:659
#define SQLITE_NULL
Definition: sqlite3.c:4390
FILE * pLog
Definition: shell.c:645
static int display_stats(sqlite3 *db, ShellState *pArg, int bReset)
Definition: shell.c:1463
static sqlite3_int64 timeOfDay(void)
Definition: shell.c:174
#define SQLITE_TESTCTRL_IMPOSTER
Definition: sqlite3.c:6993
static void output_html_string(FILE *out, const char *z)
Definition: shell.c:797
#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
Definition: sqlite3.c:7258
static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg)
Definition: shell.c:2997
#define SQLITE_SCANSTAT_EST
Definition: sqlite3.c:8310
static void usage(int showDetail)
Definition: shell.c:5352
FILE * in
Definition: shell.c:2606
#define SQLITE_LIMIT_VDBE_OP
Definition: sqlite3.c:3678
static int callback(void *pArg, int nArg, char **azArg, char **azCol)
Definition: shell.c:1263
#define sqlite3_value_bytes
Definition: sqlite3ext.h:423
static char * local_getline(char *zLine, FILE *in)
Definition: shell.c:499
#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH
Definition: sqlite3.c:3681
FILE * traceOut
Definition: shell.c:623
static sqlite3_int64 integerValue(const char *zArg)
Definition: shell.c:2475
#define sqlite3_column_blob
Definition: sqlite3ext.h:330
int showHeader
Definition: shell.c:629
#define SQLITE_STATIC
Definition: sqlite3.c:5028
#define sqlite3_trace_v2
Definition: sqlite3ext.h:541


asr_psm
Author(s): Braun Kai, Gehrung Joachim, Heizmann Heinrich, Meißner Pascal
autogenerated on Fri Nov 15 2019 03:57:54