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