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