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** Warning pragmas copied from msvc.h in the core. 22*/ 23#if defined(_MSC_VER) 24#pragma warning(disable : 4054) 25#pragma warning(disable : 4055) 26#pragma warning(disable : 4100) 27#pragma warning(disable : 4127) 28#pragma warning(disable : 4130) 29#pragma warning(disable : 4152) 30#pragma warning(disable : 4189) 31#pragma warning(disable : 4206) 32#pragma warning(disable : 4210) 33#pragma warning(disable : 4232) 34#pragma warning(disable : 4244) 35#pragma warning(disable : 4305) 36#pragma warning(disable : 4306) 37#pragma warning(disable : 4702) 38#pragma warning(disable : 4706) 39#endif /* defined(_MSC_VER) */ 40 41/* 42** No support for loadable extensions in VxWorks. 43*/ 44#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION 45# define SQLITE_OMIT_LOAD_EXTENSION 1 46#endif 47 48/* 49** Enable large-file support for fopen() and friends on unix. 50*/ 51#ifndef SQLITE_DISABLE_LFS 52# define _LARGE_FILE 1 53# ifndef _FILE_OFFSET_BITS 54# define _FILE_OFFSET_BITS 64 55# endif 56# define _LARGEFILE_SOURCE 1 57#endif 58 59#include <stdlib.h> 60#include <string.h> 61#include <stdio.h> 62#include <assert.h> 63#include "sqlite3.h" 64typedef sqlite3_int64 i64; 65typedef sqlite3_uint64 u64; 66typedef unsigned char u8; 67#if SQLITE_USER_AUTHENTICATION 68# include "sqlite3userauth.h" 69#endif 70#include <ctype.h> 71#include <stdarg.h> 72 73#if !defined(_WIN32) && !defined(WIN32) 74# include <signal.h> 75# if !defined(__RTP__) && !defined(_WRS_KERNEL) 76# include <pwd.h> 77# endif 78#endif 79#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) 80# include <unistd.h> 81# include <dirent.h> 82# define GETPID getpid 83# if defined(__MINGW32__) 84# define DIRENT dirent 85# ifndef S_ISLNK 86# define S_ISLNK(mode) (0) 87# endif 88# endif 89#else 90# define GETPID (int)GetCurrentProcessId 91#endif 92#include <sys/types.h> 93#include <sys/stat.h> 94 95#if HAVE_READLINE 96# include <readline/readline.h> 97# include <readline/history.h> 98#endif 99 100#if HAVE_EDITLINE 101# include <editline/readline.h> 102#endif 103 104#if HAVE_EDITLINE || HAVE_READLINE 105 106# define shell_add_history(X) add_history(X) 107# define shell_read_history(X) read_history(X) 108# define shell_write_history(X) write_history(X) 109# define shell_stifle_history(X) stifle_history(X) 110# define shell_readline(X) readline(X) 111 112#elif HAVE_LINENOISE 113 114# include "linenoise.h" 115# define shell_add_history(X) linenoiseHistoryAdd(X) 116# define shell_read_history(X) linenoiseHistoryLoad(X) 117# define shell_write_history(X) linenoiseHistorySave(X) 118# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) 119# define shell_readline(X) linenoise(X) 120 121#else 122 123# define shell_read_history(X) 124# define shell_write_history(X) 125# define shell_stifle_history(X) 126 127# define SHELL_USE_LOCAL_GETLINE 1 128#endif 129 130 131#if defined(_WIN32) || defined(WIN32) 132# include <io.h> 133# include <fcntl.h> 134# define isatty(h) _isatty(h) 135# ifndef access 136# define access(f,m) _access((f),(m)) 137# endif 138# ifndef unlink 139# define unlink _unlink 140# endif 141# ifndef strdup 142# define strdup _strdup 143# endif 144# undef popen 145# define popen _popen 146# undef pclose 147# define pclose _pclose 148#else 149 /* Make sure isatty() has a prototype. */ 150 extern int isatty(int); 151 152# if !defined(__RTP__) && !defined(_WRS_KERNEL) 153 /* popen and pclose are not C89 functions and so are 154 ** sometimes omitted from the <stdio.h> header */ 155 extern FILE *popen(const char*,const char*); 156 extern int pclose(FILE*); 157# else 158# define SQLITE_OMIT_POPEN 1 159# endif 160#endif 161 162#if defined(_WIN32_WCE) 163/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() 164 * thus we always assume that we have a console. That can be 165 * overridden with the -batch command line option. 166 */ 167#define isatty(x) 1 168#endif 169 170/* ctype macros that work with signed characters */ 171#define IsSpace(X) isspace((unsigned char)X) 172#define IsDigit(X) isdigit((unsigned char)X) 173#define ToLower(X) (char)tolower((unsigned char)X) 174 175#if defined(_WIN32) || defined(WIN32) 176#include <windows.h> 177 178/* string conversion routines only needed on Win32 */ 179extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR); 180extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int); 181extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int); 182extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText); 183#endif 184 185/* On Windows, we normally run with output mode of TEXT so that \n characters 186** are automatically translated into \r\n. However, this behavior needs 187** to be disabled in some cases (ex: when generating CSV output and when 188** rendering quoted strings that contain \n characters). The following 189** routines take care of that. 190*/ 191#if defined(_WIN32) || defined(WIN32) 192static void setBinaryMode(FILE *file, int isOutput){ 193 if( isOutput ) fflush(file); 194 _setmode(_fileno(file), _O_BINARY); 195} 196static void setTextMode(FILE *file, int isOutput){ 197 if( isOutput ) fflush(file); 198 _setmode(_fileno(file), _O_TEXT); 199} 200#else 201# define setBinaryMode(X,Y) 202# define setTextMode(X,Y) 203#endif 204 205 206/* True if the timer is enabled */ 207static int enableTimer = 0; 208 209/* Return the current wall-clock time */ 210static sqlite3_int64 timeOfDay(void){ 211 static sqlite3_vfs *clockVfs = 0; 212 sqlite3_int64 t; 213 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); 214 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ 215 clockVfs->xCurrentTimeInt64(clockVfs, &t); 216 }else{ 217 double r; 218 clockVfs->xCurrentTime(clockVfs, &r); 219 t = (sqlite3_int64)(r*86400000.0); 220 } 221 return t; 222} 223 224#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) 225#include <sys/time.h> 226#include <sys/resource.h> 227 228/* VxWorks does not support getrusage() as far as we can determine */ 229#if defined(_WRS_KERNEL) || defined(__RTP__) 230struct rusage { 231 struct timeval ru_utime; /* user CPU time used */ 232 struct timeval ru_stime; /* system CPU time used */ 233}; 234#define getrusage(A,B) memset(B,0,sizeof(*B)) 235#endif 236 237/* Saved resource information for the beginning of an operation */ 238static struct rusage sBegin; /* CPU time at start */ 239static sqlite3_int64 iBegin; /* Wall-clock time at start */ 240 241/* 242** Begin timing an operation 243*/ 244static void beginTimer(void){ 245 if( enableTimer ){ 246 getrusage(RUSAGE_SELF, &sBegin); 247 iBegin = timeOfDay(); 248 } 249} 250 251/* Return the difference of two time_structs in seconds */ 252static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ 253 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + 254 (double)(pEnd->tv_sec - pStart->tv_sec); 255} 256 257/* 258** Print the timing results. 259*/ 260static void endTimer(void){ 261 if( enableTimer ){ 262 sqlite3_int64 iEnd = timeOfDay(); 263 struct rusage sEnd; 264 getrusage(RUSAGE_SELF, &sEnd); 265 printf("Run Time: real %.3f user %f sys %f\n", 266 (iEnd - iBegin)*0.001, 267 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), 268 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); 269 } 270} 271 272#define BEGIN_TIMER beginTimer() 273#define END_TIMER endTimer() 274#define HAS_TIMER 1 275 276#elif (defined(_WIN32) || defined(WIN32)) 277 278/* Saved resource information for the beginning of an operation */ 279static HANDLE hProcess; 280static FILETIME ftKernelBegin; 281static FILETIME ftUserBegin; 282static sqlite3_int64 ftWallBegin; 283typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, 284 LPFILETIME, LPFILETIME); 285static GETPROCTIMES getProcessTimesAddr = NULL; 286 287/* 288** Check to see if we have timer support. Return 1 if necessary 289** support found (or found previously). 290*/ 291static int hasTimer(void){ 292 if( getProcessTimesAddr ){ 293 return 1; 294 } else { 295 /* GetProcessTimes() isn't supported in WIN95 and some other Windows 296 ** versions. See if the version we are running on has it, and if it 297 ** does, save off a pointer to it and the current process handle. 298 */ 299 hProcess = GetCurrentProcess(); 300 if( hProcess ){ 301 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); 302 if( NULL != hinstLib ){ 303 getProcessTimesAddr = 304 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); 305 if( NULL != getProcessTimesAddr ){ 306 return 1; 307 } 308 FreeLibrary(hinstLib); 309 } 310 } 311 } 312 return 0; 313} 314 315/* 316** Begin timing an operation 317*/ 318static void beginTimer(void){ 319 if( enableTimer && getProcessTimesAddr ){ 320 FILETIME ftCreation, ftExit; 321 getProcessTimesAddr(hProcess,&ftCreation,&ftExit, 322 &ftKernelBegin,&ftUserBegin); 323 ftWallBegin = timeOfDay(); 324 } 325} 326 327/* Return the difference of two FILETIME structs in seconds */ 328static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ 329 sqlite_int64 i64Start = *((sqlite_int64 *) pStart); 330 sqlite_int64 i64End = *((sqlite_int64 *) pEnd); 331 return (double) ((i64End - i64Start) / 10000000.0); 332} 333 334/* 335** Print the timing results. 336*/ 337static void endTimer(void){ 338 if( enableTimer && getProcessTimesAddr){ 339 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; 340 sqlite3_int64 ftWallEnd = timeOfDay(); 341 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); 342 printf("Run Time: real %.3f user %f sys %f\n", 343 (ftWallEnd - ftWallBegin)*0.001, 344 timeDiff(&ftUserBegin, &ftUserEnd), 345 timeDiff(&ftKernelBegin, &ftKernelEnd)); 346 } 347} 348 349#define BEGIN_TIMER beginTimer() 350#define END_TIMER endTimer() 351#define HAS_TIMER hasTimer() 352 353#else 354#define BEGIN_TIMER 355#define END_TIMER 356#define HAS_TIMER 0 357#endif 358 359/* 360** Used to prevent warnings about unused parameters 361*/ 362#define UNUSED_PARAMETER(x) (void)(x) 363 364/* 365** Number of elements in an array 366*/ 367#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) 368 369/* 370** If the following flag is set, then command execution stops 371** at an error if we are not interactive. 372*/ 373static int bail_on_error = 0; 374 375/* 376** Threat stdin as an interactive input if the following variable 377** is true. Otherwise, assume stdin is connected to a file or pipe. 378*/ 379static int stdin_is_interactive = 1; 380 381/* 382** On Windows systems we have to know if standard output is a console 383** in order to translate UTF-8 into MBCS. The following variable is 384** true if translation is required. 385*/ 386static int stdout_is_console = 1; 387 388/* 389** The following is the open SQLite database. We make a pointer 390** to this database a static variable so that it can be accessed 391** by the SIGINT handler to interrupt database processing. 392*/ 393static sqlite3 *globalDb = 0; 394 395/* 396** True if an interrupt (Control-C) has been received. 397*/ 398static volatile int seenInterrupt = 0; 399 400/* 401** This is the name of our program. It is set in main(), used 402** in a number of other places, mostly for error messages. 403*/ 404static char *Argv0; 405 406/* 407** Prompt strings. Initialized in main. Settable with 408** .prompt main continue 409*/ 410static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ 411static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ 412 413/* 414** Render output like fprintf(). Except, if the output is going to the 415** console and if this is running on a Windows machine, translate the 416** output from UTF-8 into MBCS. 417*/ 418#if defined(_WIN32) || defined(WIN32) 419void utf8_printf(FILE *out, const char *zFormat, ...){ 420 va_list ap; 421 va_start(ap, zFormat); 422 if( stdout_is_console && (out==stdout || out==stderr) ){ 423 char *z1 = sqlite3_vmprintf(zFormat, ap); 424 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0); 425 sqlite3_free(z1); 426 fputs(z2, out); 427 sqlite3_free(z2); 428 }else{ 429 vfprintf(out, zFormat, ap); 430 } 431 va_end(ap); 432} 433#elif !defined(utf8_printf) 434# define utf8_printf fprintf 435#endif 436 437/* 438** Render output like fprintf(). This should not be used on anything that 439** includes string formatting (e.g. "%s"). 440*/ 441#if !defined(raw_printf) 442# define raw_printf fprintf 443#endif 444 445/* Indicate out-of-memory and exit. */ 446static void shell_out_of_memory(void){ 447 raw_printf(stderr,"Error: out of memory\n"); 448 exit(1); 449} 450 451/* 452** Write I/O traces to the following stream. 453*/ 454#ifdef SQLITE_ENABLE_IOTRACE 455static FILE *iotrace = 0; 456#endif 457 458/* 459** This routine works like printf in that its first argument is a 460** format string and subsequent arguments are values to be substituted 461** in place of % fields. The result of formatting this string 462** is written to iotrace. 463*/ 464#ifdef SQLITE_ENABLE_IOTRACE 465static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ 466 va_list ap; 467 char *z; 468 if( iotrace==0 ) return; 469 va_start(ap, zFormat); 470 z = sqlite3_vmprintf(zFormat, ap); 471 va_end(ap); 472 utf8_printf(iotrace, "%s", z); 473 sqlite3_free(z); 474} 475#endif 476 477/* 478** Output string zUtf to stream pOut as w characters. If w is negative, 479** then right-justify the text. W is the width in UTF-8 characters, not 480** in bytes. This is different from the %*.*s specification in printf 481** since with %*.*s the width is measured in bytes, not characters. 482*/ 483static void utf8_width_print(FILE *pOut, int w, const char *zUtf){ 484 int i; 485 int n; 486 int aw = w<0 ? -w : w; 487 char zBuf[1000]; 488 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3; 489 for(i=n=0; zUtf[i]; i++){ 490 if( (zUtf[i]&0xc0)!=0x80 ){ 491 n++; 492 if( n==aw ){ 493 do{ i++; }while( (zUtf[i]&0xc0)==0x80 ); 494 break; 495 } 496 } 497 } 498 if( n>=aw ){ 499 utf8_printf(pOut, "%.*s", i, zUtf); 500 }else if( w<0 ){ 501 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf); 502 }else{ 503 utf8_printf(pOut, "%s%*s", zUtf, aw-n, ""); 504 } 505} 506 507 508/* 509** Determines if a string is a number of not. 510*/ 511static int isNumber(const char *z, int *realnum){ 512 if( *z=='-' || *z=='+' ) z++; 513 if( !IsDigit(*z) ){ 514 return 0; 515 } 516 z++; 517 if( realnum ) *realnum = 0; 518 while( IsDigit(*z) ){ z++; } 519 if( *z=='.' ){ 520 z++; 521 if( !IsDigit(*z) ) return 0; 522 while( IsDigit(*z) ){ z++; } 523 if( realnum ) *realnum = 1; 524 } 525 if( *z=='e' || *z=='E' ){ 526 z++; 527 if( *z=='+' || *z=='-' ) z++; 528 if( !IsDigit(*z) ) return 0; 529 while( IsDigit(*z) ){ z++; } 530 if( realnum ) *realnum = 1; 531 } 532 return *z==0; 533} 534 535/* 536** Compute a string length that is limited to what can be stored in 537** lower 30 bits of a 32-bit signed integer. 538*/ 539static int strlen30(const char *z){ 540 const char *z2 = z; 541 while( *z2 ){ z2++; } 542 return 0x3fffffff & (int)(z2 - z); 543} 544 545/* 546** Return the length of a string in characters. Multibyte UTF8 characters 547** count as a single character. 548*/ 549static int strlenChar(const char *z){ 550 int n = 0; 551 while( *z ){ 552 if( (0xc0&*(z++))!=0x80 ) n++; 553 } 554 return n; 555} 556 557/* 558** This routine reads a line of text from FILE in, stores 559** the text in memory obtained from malloc() and returns a pointer 560** to the text. NULL is returned at end of file, or if malloc() 561** fails. 562** 563** If zLine is not NULL then it is a malloced buffer returned from 564** a previous call to this routine that may be reused. 565*/ 566static char *local_getline(char *zLine, FILE *in){ 567 int nLine = zLine==0 ? 0 : 100; 568 int n = 0; 569 570 while( 1 ){ 571 if( n+100>nLine ){ 572 nLine = nLine*2 + 100; 573 zLine = realloc(zLine, nLine); 574 if( zLine==0 ) shell_out_of_memory(); 575 } 576 if( fgets(&zLine[n], nLine - n, in)==0 ){ 577 if( n==0 ){ 578 free(zLine); 579 return 0; 580 } 581 zLine[n] = 0; 582 break; 583 } 584 while( zLine[n] ) n++; 585 if( n>0 && zLine[n-1]=='\n' ){ 586 n--; 587 if( n>0 && zLine[n-1]=='\r' ) n--; 588 zLine[n] = 0; 589 break; 590 } 591 } 592#if defined(_WIN32) || defined(WIN32) 593 /* For interactive input on Windows systems, translate the 594 ** multi-byte characterset characters into UTF-8. */ 595 if( stdin_is_interactive && in==stdin ){ 596 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0); 597 if( zTrans ){ 598 int nTrans = strlen30(zTrans)+1; 599 if( nTrans>nLine ){ 600 zLine = realloc(zLine, nTrans); 601 if( zLine==0 ) shell_out_of_memory(); 602 } 603 memcpy(zLine, zTrans, nTrans); 604 sqlite3_free(zTrans); 605 } 606 } 607#endif /* defined(_WIN32) || defined(WIN32) */ 608 return zLine; 609} 610 611/* 612** Retrieve a single line of input text. 613** 614** If in==0 then read from standard input and prompt before each line. 615** If isContinuation is true, then a continuation prompt is appropriate. 616** If isContinuation is zero, then the main prompt should be used. 617** 618** If zPrior is not NULL then it is a buffer from a prior call to this 619** routine that can be reused. 620** 621** The result is stored in space obtained from malloc() and must either 622** be freed by the caller or else passed back into this routine via the 623** zPrior argument for reuse. 624*/ 625static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ 626 char *zPrompt; 627 char *zResult; 628 if( in!=0 ){ 629 zResult = local_getline(zPrior, in); 630 }else{ 631 zPrompt = isContinuation ? continuePrompt : mainPrompt; 632#if SHELL_USE_LOCAL_GETLINE 633 printf("%s", zPrompt); 634 fflush(stdout); 635 zResult = local_getline(zPrior, stdin); 636#else 637 free(zPrior); 638 zResult = shell_readline(zPrompt); 639 if( zResult && *zResult ) shell_add_history(zResult); 640#endif 641 } 642 return zResult; 643} 644 645 646/* 647** Return the value of a hexadecimal digit. Return -1 if the input 648** is not a hex digit. 649*/ 650static int hexDigitValue(char c){ 651 if( c>='0' && c<='9' ) return c - '0'; 652 if( c>='a' && c<='f' ) return c - 'a' + 10; 653 if( c>='A' && c<='F' ) return c - 'A' + 10; 654 return -1; 655} 656 657/* 658** Interpret zArg as an integer value, possibly with suffixes. 659*/ 660static sqlite3_int64 integerValue(const char *zArg){ 661 sqlite3_int64 v = 0; 662 static const struct { char *zSuffix; int iMult; } aMult[] = { 663 { "KiB", 1024 }, 664 { "MiB", 1024*1024 }, 665 { "GiB", 1024*1024*1024 }, 666 { "KB", 1000 }, 667 { "MB", 1000000 }, 668 { "GB", 1000000000 }, 669 { "K", 1000 }, 670 { "M", 1000000 }, 671 { "G", 1000000000 }, 672 }; 673 int i; 674 int isNeg = 0; 675 if( zArg[0]=='-' ){ 676 isNeg = 1; 677 zArg++; 678 }else if( zArg[0]=='+' ){ 679 zArg++; 680 } 681 if( zArg[0]=='0' && zArg[1]=='x' ){ 682 int x; 683 zArg += 2; 684 while( (x = hexDigitValue(zArg[0]))>=0 ){ 685 v = (v<<4) + x; 686 zArg++; 687 } 688 }else{ 689 while( IsDigit(zArg[0]) ){ 690 v = v*10 + zArg[0] - '0'; 691 zArg++; 692 } 693 } 694 for(i=0; i<ArraySize(aMult); i++){ 695 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ 696 v *= aMult[i].iMult; 697 break; 698 } 699 } 700 return isNeg? -v : v; 701} 702 703/* 704** A variable length string to which one can append text. 705*/ 706typedef struct ShellText ShellText; 707struct ShellText { 708 char *z; 709 int n; 710 int nAlloc; 711}; 712 713/* 714** Initialize and destroy a ShellText object 715*/ 716static void initText(ShellText *p){ 717 memset(p, 0, sizeof(*p)); 718} 719static void freeText(ShellText *p){ 720 free(p->z); 721 initText(p); 722} 723 724/* zIn is either a pointer to a NULL-terminated string in memory obtained 725** from malloc(), or a NULL pointer. The string pointed to by zAppend is 726** added to zIn, and the result returned in memory obtained from malloc(). 727** zIn, if it was not NULL, is freed. 728** 729** If the third argument, quote, is not '\0', then it is used as a 730** quote character for zAppend. 731*/ 732static void appendText(ShellText *p, char const *zAppend, char quote){ 733 int len; 734 int i; 735 int nAppend = strlen30(zAppend); 736 737 len = nAppend+p->n+1; 738 if( quote ){ 739 len += 2; 740 for(i=0; i<nAppend; i++){ 741 if( zAppend[i]==quote ) len++; 742 } 743 } 744 745 if( p->n+len>=p->nAlloc ){ 746 p->nAlloc = p->nAlloc*2 + len + 20; 747 p->z = realloc(p->z, p->nAlloc); 748 if( p->z==0 ) shell_out_of_memory(); 749 } 750 751 if( quote ){ 752 char *zCsr = p->z+p->n; 753 *zCsr++ = quote; 754 for(i=0; i<nAppend; i++){ 755 *zCsr++ = zAppend[i]; 756 if( zAppend[i]==quote ) *zCsr++ = quote; 757 } 758 *zCsr++ = quote; 759 p->n = (int)(zCsr - p->z); 760 *zCsr = '\0'; 761 }else{ 762 memcpy(p->z+p->n, zAppend, nAppend); 763 p->n += nAppend; 764 p->z[p->n] = '\0'; 765 } 766} 767 768/* 769** Attempt to determine if identifier zName needs to be quoted, either 770** because it contains non-alphanumeric characters, or because it is an 771** SQLite keyword. Be conservative in this estimate: When in doubt assume 772** that quoting is required. 773** 774** Return '"' if quoting is required. Return 0 if no quoting is required. 775*/ 776static char quoteChar(const char *zName){ 777 int i; 778 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; 779 for(i=0; zName[i]; i++){ 780 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; 781 } 782 return sqlite3_keyword_check(zName, i) ? '"' : 0; 783} 784 785/* 786** Construct a fake object name and column list to describe the structure 787** of the view, virtual table, or table valued function zSchema.zName. 788*/ 789static char *shellFakeSchema( 790 sqlite3 *db, /* The database connection containing the vtab */ 791 const char *zSchema, /* Schema of the database holding the vtab */ 792 const char *zName /* The name of the virtual table */ 793){ 794 sqlite3_stmt *pStmt = 0; 795 char *zSql; 796 ShellText s; 797 char cQuote; 798 char *zDiv = "("; 799 int nRow = 0; 800 801 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", 802 zSchema ? zSchema : "main", zName); 803 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 804 sqlite3_free(zSql); 805 initText(&s); 806 if( zSchema ){ 807 cQuote = quoteChar(zSchema); 808 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; 809 appendText(&s, zSchema, cQuote); 810 appendText(&s, ".", 0); 811 } 812 cQuote = quoteChar(zName); 813 appendText(&s, zName, cQuote); 814 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 815 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); 816 nRow++; 817 appendText(&s, zDiv, 0); 818 zDiv = ","; 819 cQuote = quoteChar(zCol); 820 appendText(&s, zCol, cQuote); 821 } 822 appendText(&s, ")", 0); 823 sqlite3_finalize(pStmt); 824 if( nRow==0 ){ 825 freeText(&s); 826 s.z = 0; 827 } 828 return s.z; 829} 830 831/* 832** SQL function: shell_module_schema(X) 833** 834** Return a fake schema for the table-valued function or eponymous virtual 835** table X. 836*/ 837static void shellModuleSchema( 838 sqlite3_context *pCtx, 839 int nVal, 840 sqlite3_value **apVal 841){ 842 const char *zName = (const char*)sqlite3_value_text(apVal[0]); 843 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName); 844 UNUSED_PARAMETER(nVal); 845 if( zFake ){ 846 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), 847 -1, sqlite3_free); 848 free(zFake); 849 } 850} 851 852/* 853** SQL function: shell_add_schema(S,X) 854** 855** Add the schema name X to the CREATE statement in S and return the result. 856** Examples: 857** 858** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); 859** 860** Also works on 861** 862** CREATE INDEX 863** CREATE UNIQUE INDEX 864** CREATE VIEW 865** CREATE TRIGGER 866** CREATE VIRTUAL TABLE 867** 868** This UDF is used by the .schema command to insert the schema name of 869** attached databases into the middle of the sqlite_master.sql field. 870*/ 871static void shellAddSchemaName( 872 sqlite3_context *pCtx, 873 int nVal, 874 sqlite3_value **apVal 875){ 876 static const char *aPrefix[] = { 877 "TABLE", 878 "INDEX", 879 "UNIQUE INDEX", 880 "VIEW", 881 "TRIGGER", 882 "VIRTUAL TABLE" 883 }; 884 int i = 0; 885 const char *zIn = (const char*)sqlite3_value_text(apVal[0]); 886 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); 887 const char *zName = (const char*)sqlite3_value_text(apVal[2]); 888 sqlite3 *db = sqlite3_context_db_handle(pCtx); 889 UNUSED_PARAMETER(nVal); 890 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){ 891 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){ 892 int n = strlen30(aPrefix[i]); 893 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){ 894 char *z = 0; 895 char *zFake = 0; 896 if( zSchema ){ 897 char cQuote = quoteChar(zSchema); 898 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){ 899 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8); 900 }else{ 901 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8); 902 } 903 } 904 if( zName 905 && aPrefix[i][0]=='V' 906 && (zFake = shellFakeSchema(db, zSchema, zName))!=0 907 ){ 908 if( z==0 ){ 909 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake); 910 }else{ 911 z = sqlite3_mprintf("%z\n/* %s */", z, zFake); 912 } 913 free(zFake); 914 } 915 if( z ){ 916 sqlite3_result_text(pCtx, z, -1, sqlite3_free); 917 return; 918 } 919 } 920 } 921 } 922 sqlite3_result_value(pCtx, apVal[0]); 923} 924 925/* 926** The source code for several run-time loadable extensions is inserted 927** below by the ../tool/mkshellc.tcl script. Before processing that included 928** code, we need to override some macros to make the included program code 929** work here in the middle of this regular program. 930*/ 931#define SQLITE_EXTENSION_INIT1 932#define SQLITE_EXTENSION_INIT2(X) (void)(X) 933 934#if defined(_WIN32) && defined(_MSC_VER) 935INCLUDE test_windirent.h 936INCLUDE test_windirent.c 937#define dirent DIRENT 938#endif 939INCLUDE ../ext/misc/shathree.c 940INCLUDE ../ext/misc/fileio.c 941INCLUDE ../ext/misc/completion.c 942INCLUDE ../ext/misc/appendvfs.c 943INCLUDE ../ext/misc/memtrace.c 944#ifdef SQLITE_HAVE_ZLIB 945INCLUDE ../ext/misc/zipfile.c 946INCLUDE ../ext/misc/sqlar.c 947#endif 948INCLUDE ../ext/expert/sqlite3expert.h 949INCLUDE ../ext/expert/sqlite3expert.c 950 951#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 952INCLUDE ../ext/misc/dbdata.c 953#endif 954 955#if defined(SQLITE_ENABLE_SESSION) 956/* 957** State information for a single open session 958*/ 959typedef struct OpenSession OpenSession; 960struct OpenSession { 961 char *zName; /* Symbolic name for this session */ 962 int nFilter; /* Number of xFilter rejection GLOB patterns */ 963 char **azFilter; /* Array of xFilter rejection GLOB patterns */ 964 sqlite3_session *p; /* The open session */ 965}; 966#endif 967 968/* 969** Shell output mode information from before ".explain on", 970** saved so that it can be restored by ".explain off" 971*/ 972typedef struct SavedModeInfo SavedModeInfo; 973struct SavedModeInfo { 974 int valid; /* Is there legit data in here? */ 975 int mode; /* Mode prior to ".explain on" */ 976 int showHeader; /* The ".header" setting prior to ".explain on" */ 977 int colWidth[100]; /* Column widths prior to ".explain on" */ 978}; 979 980typedef struct ExpertInfo ExpertInfo; 981struct ExpertInfo { 982 sqlite3expert *pExpert; 983 int bVerbose; 984}; 985 986/* A single line in the EQP output */ 987typedef struct EQPGraphRow EQPGraphRow; 988struct EQPGraphRow { 989 int iEqpId; /* ID for this row */ 990 int iParentId; /* ID of the parent row */ 991 EQPGraphRow *pNext; /* Next row in sequence */ 992 char zText[1]; /* Text to display for this row */ 993}; 994 995/* All EQP output is collected into an instance of the following */ 996typedef struct EQPGraph EQPGraph; 997struct EQPGraph { 998 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */ 999 EQPGraphRow *pLast; /* Last element of the pRow list */ 1000 char zPrefix[100]; /* Graph prefix */ 1001}; 1002 1003/* 1004** State information about the database connection is contained in an 1005** instance of the following structure. 1006*/ 1007typedef struct ShellState ShellState; 1008struct ShellState { 1009 sqlite3 *db; /* The database */ 1010 u8 autoExplain; /* Automatically turn on .explain mode */ 1011 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ 1012 u8 autoEQPtest; /* autoEQP is in test mode */ 1013 u8 autoEQPtrace; /* autoEQP is in trace mode */ 1014 u8 statsOn; /* True to display memory stats before each finalize */ 1015 u8 scanstatsOn; /* True to display scan stats before each finalize */ 1016 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ 1017 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ 1018 u8 nEqpLevel; /* Depth of the EQP output graph */ 1019 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */ 1020 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */ 1021 int outCount; /* Revert to stdout when reaching zero */ 1022 int cnt; /* Number of records displayed so far */ 1023 int lineno; /* Line number of last line read from in */ 1024 FILE *in; /* Read commands from this stream */ 1025 FILE *out; /* Write results here */ 1026 FILE *traceOut; /* Output for sqlite3_trace() */ 1027 int nErr; /* Number of errors seen */ 1028 int mode; /* An output mode setting */ 1029 int modePrior; /* Saved mode */ 1030 int cMode; /* temporary output mode for the current query */ 1031 int normalMode; /* Output mode before ".explain on" */ 1032 int writableSchema; /* True if PRAGMA writable_schema=ON */ 1033 int showHeader; /* True to show column names in List or Column mode */ 1034 int nCheck; /* Number of ".check" commands run */ 1035 unsigned nProgress; /* Number of progress callbacks encountered */ 1036 unsigned mxProgress; /* Maximum progress callbacks before failing */ 1037 unsigned flgProgress; /* Flags for the progress callback */ 1038 unsigned shellFlgs; /* Various flags */ 1039 sqlite3_int64 szMax; /* --maxsize argument to .open */ 1040 char *zDestTable; /* Name of destination table when MODE_Insert */ 1041 char *zTempFile; /* Temporary file that might need deleting */ 1042 char zTestcase[30]; /* Name of current test case */ 1043 char colSeparator[20]; /* Column separator character for several modes */ 1044 char rowSeparator[20]; /* Row separator character for MODE_Ascii */ 1045 char colSepPrior[20]; /* Saved column separator */ 1046 char rowSepPrior[20]; /* Saved row separator */ 1047 int colWidth[100]; /* Requested width of each column when in column mode*/ 1048 int actualWidth[100]; /* Actual width of each column */ 1049 char nullValue[20]; /* The text to print when a NULL comes back from 1050 ** the database */ 1051 char outfile[FILENAME_MAX]; /* Filename for *out */ 1052 const char *zDbFilename; /* name of the database file */ 1053 char *zFreeOnClose; /* Filename to free when closing */ 1054 const char *zVfs; /* Name of VFS to use */ 1055 sqlite3_stmt *pStmt; /* Current statement if any. */ 1056 FILE *pLog; /* Write log output here */ 1057 int *aiIndent; /* Array of indents used in MODE_Explain */ 1058 int nIndent; /* Size of array aiIndent[] */ 1059 int iIndent; /* Index of current op in aiIndent[] */ 1060 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */ 1061#if defined(SQLITE_ENABLE_SESSION) 1062 int nSession; /* Number of active sessions */ 1063 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ 1064#endif 1065 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ 1066}; 1067 1068 1069/* Allowed values for ShellState.autoEQP 1070*/ 1071#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ 1072#define AUTOEQP_on 1 /* Automatic EQP is on */ 1073#define AUTOEQP_trigger 2 /* On and also show plans for triggers */ 1074#define AUTOEQP_full 3 /* Show full EXPLAIN */ 1075 1076/* Allowed values for ShellState.openMode 1077*/ 1078#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ 1079#define SHELL_OPEN_NORMAL 1 /* Normal database file */ 1080#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ 1081#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ 1082#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ 1083#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */ 1084#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */ 1085 1086/* Allowed values for ShellState.eTraceType 1087*/ 1088#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ 1089#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ 1090#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ 1091 1092/* Bits in the ShellState.flgProgress variable */ 1093#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ 1094#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres 1095 ** callback limit is reached, and for each 1096 ** top-level SQL statement */ 1097#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ 1098 1099/* 1100** These are the allowed shellFlgs values 1101*/ 1102#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ 1103#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ 1104#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ 1105#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ 1106#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ 1107#define SHFLG_CountChanges 0x00000020 /* .changes setting */ 1108#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */ 1109 1110/* 1111** Macros for testing and setting shellFlgs 1112*/ 1113#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) 1114#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) 1115#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) 1116 1117/* 1118** These are the allowed modes. 1119*/ 1120#define MODE_Line 0 /* One column per line. Blank line between records */ 1121#define MODE_Column 1 /* One record per line in neat columns */ 1122#define MODE_List 2 /* One record per line with a separator */ 1123#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ 1124#define MODE_Html 4 /* Generate an XHTML table */ 1125#define MODE_Insert 5 /* Generate SQL "insert" statements */ 1126#define MODE_Quote 6 /* Quote values as for SQL */ 1127#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ 1128#define MODE_Csv 8 /* Quote strings, numbers are plain */ 1129#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ 1130#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ 1131#define MODE_Pretty 11 /* Pretty-print schemas */ 1132#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */ 1133 1134static const char *modeDescr[] = { 1135 "line", 1136 "column", 1137 "list", 1138 "semi", 1139 "html", 1140 "insert", 1141 "quote", 1142 "tcl", 1143 "csv", 1144 "explain", 1145 "ascii", 1146 "prettyprint", 1147 "eqp" 1148}; 1149 1150/* 1151** These are the column/row/line separators used by the various 1152** import/export modes. 1153*/ 1154#define SEP_Column "|" 1155#define SEP_Row "\n" 1156#define SEP_Tab "\t" 1157#define SEP_Space " " 1158#define SEP_Comma "," 1159#define SEP_CrLf "\r\n" 1160#define SEP_Unit "\x1F" 1161#define SEP_Record "\x1E" 1162 1163/* 1164** A callback for the sqlite3_log() interface. 1165*/ 1166static void shellLog(void *pArg, int iErrCode, const char *zMsg){ 1167 ShellState *p = (ShellState*)pArg; 1168 if( p->pLog==0 ) return; 1169 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); 1170 fflush(p->pLog); 1171} 1172 1173/* 1174** SQL function: shell_putsnl(X) 1175** 1176** Write the text X to the screen (or whatever output is being directed) 1177** adding a newline at the end, and then return X. 1178*/ 1179static void shellPutsFunc( 1180 sqlite3_context *pCtx, 1181 int nVal, 1182 sqlite3_value **apVal 1183){ 1184 ShellState *p = (ShellState*)sqlite3_user_data(pCtx); 1185 (void)nVal; 1186 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); 1187 sqlite3_result_value(pCtx, apVal[0]); 1188} 1189 1190/* 1191** SQL function: edit(VALUE) 1192** edit(VALUE,EDITOR) 1193** 1194** These steps: 1195** 1196** (1) Write VALUE into a temporary file. 1197** (2) Run program EDITOR on that temporary file. 1198** (3) Read the temporary file back and return its content as the result. 1199** (4) Delete the temporary file 1200** 1201** If the EDITOR argument is omitted, use the value in the VISUAL 1202** environment variable. If still there is no EDITOR, through an error. 1203** 1204** Also throw an error if the EDITOR program returns a non-zero exit code. 1205*/ 1206#ifndef SQLITE_NOHAVE_SYSTEM 1207static void editFunc( 1208 sqlite3_context *context, 1209 int argc, 1210 sqlite3_value **argv 1211){ 1212 const char *zEditor; 1213 char *zTempFile = 0; 1214 sqlite3 *db; 1215 char *zCmd = 0; 1216 int bBin; 1217 int rc; 1218 int hasCRNL = 0; 1219 FILE *f = 0; 1220 sqlite3_int64 sz; 1221 sqlite3_int64 x; 1222 unsigned char *p = 0; 1223 1224 if( argc==2 ){ 1225 zEditor = (const char*)sqlite3_value_text(argv[1]); 1226 }else{ 1227 zEditor = getenv("VISUAL"); 1228 } 1229 if( zEditor==0 ){ 1230 sqlite3_result_error(context, "no editor for edit()", -1); 1231 return; 1232 } 1233 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 1234 sqlite3_result_error(context, "NULL input to edit()", -1); 1235 return; 1236 } 1237 db = sqlite3_context_db_handle(context); 1238 zTempFile = 0; 1239 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); 1240 if( zTempFile==0 ){ 1241 sqlite3_uint64 r = 0; 1242 sqlite3_randomness(sizeof(r), &r); 1243 zTempFile = sqlite3_mprintf("temp%llx", r); 1244 if( zTempFile==0 ){ 1245 sqlite3_result_error_nomem(context); 1246 return; 1247 } 1248 } 1249 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; 1250 /* When writing the file to be edited, do \n to \r\n conversions on systems 1251 ** that want \r\n line endings */ 1252 f = fopen(zTempFile, bBin ? "wb" : "w"); 1253 if( f==0 ){ 1254 sqlite3_result_error(context, "edit() cannot open temp file", -1); 1255 goto edit_func_end; 1256 } 1257 sz = sqlite3_value_bytes(argv[0]); 1258 if( bBin ){ 1259 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f); 1260 }else{ 1261 const char *z = (const char*)sqlite3_value_text(argv[0]); 1262 /* Remember whether or not the value originally contained \r\n */ 1263 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1; 1264 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f); 1265 } 1266 fclose(f); 1267 f = 0; 1268 if( x!=sz ){ 1269 sqlite3_result_error(context, "edit() could not write the whole file", -1); 1270 goto edit_func_end; 1271 } 1272 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); 1273 if( zCmd==0 ){ 1274 sqlite3_result_error_nomem(context); 1275 goto edit_func_end; 1276 } 1277 rc = system(zCmd); 1278 sqlite3_free(zCmd); 1279 if( rc ){ 1280 sqlite3_result_error(context, "EDITOR returned non-zero", -1); 1281 goto edit_func_end; 1282 } 1283 f = fopen(zTempFile, "rb"); 1284 if( f==0 ){ 1285 sqlite3_result_error(context, 1286 "edit() cannot reopen temp file after edit", -1); 1287 goto edit_func_end; 1288 } 1289 fseek(f, 0, SEEK_END); 1290 sz = ftell(f); 1291 rewind(f); 1292 p = sqlite3_malloc64( sz+(bBin==0) ); 1293 if( p==0 ){ 1294 sqlite3_result_error_nomem(context); 1295 goto edit_func_end; 1296 } 1297 x = fread(p, 1, sz, f); 1298 fclose(f); 1299 f = 0; 1300 if( x!=sz ){ 1301 sqlite3_result_error(context, "could not read back the whole file", -1); 1302 goto edit_func_end; 1303 } 1304 if( bBin ){ 1305 sqlite3_result_blob64(context, p, sz, sqlite3_free); 1306 }else{ 1307 sqlite3_int64 i, j; 1308 if( hasCRNL ){ 1309 /* If the original contains \r\n then do no conversions back to \n */ 1310 j = sz; 1311 }else{ 1312 /* If the file did not originally contain \r\n then convert any new 1313 ** \r\n back into \n */ 1314 for(i=j=0; i<sz; i++){ 1315 if( p[i]=='\r' && p[i+1]=='\n' ) i++; 1316 p[j++] = p[i]; 1317 } 1318 sz = j; 1319 p[sz] = 0; 1320 } 1321 sqlite3_result_text64(context, (const char*)p, sz, 1322 sqlite3_free, SQLITE_UTF8); 1323 } 1324 p = 0; 1325 1326edit_func_end: 1327 if( f ) fclose(f); 1328 unlink(zTempFile); 1329 sqlite3_free(zTempFile); 1330 sqlite3_free(p); 1331} 1332#endif /* SQLITE_NOHAVE_SYSTEM */ 1333 1334/* 1335** Save or restore the current output mode 1336*/ 1337static void outputModePush(ShellState *p){ 1338 p->modePrior = p->mode; 1339 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); 1340 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); 1341} 1342static void outputModePop(ShellState *p){ 1343 p->mode = p->modePrior; 1344 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); 1345 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); 1346} 1347 1348/* 1349** Output the given string as a hex-encoded blob (eg. X'1234' ) 1350*/ 1351static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ 1352 int i; 1353 char *zBlob = (char *)pBlob; 1354 raw_printf(out,"X'"); 1355 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); } 1356 raw_printf(out,"'"); 1357} 1358 1359/* 1360** Find a string that is not found anywhere in z[]. Return a pointer 1361** to that string. 1362** 1363** Try to use zA and zB first. If both of those are already found in z[] 1364** then make up some string and store it in the buffer zBuf. 1365*/ 1366static const char *unused_string( 1367 const char *z, /* Result must not appear anywhere in z */ 1368 const char *zA, const char *zB, /* Try these first */ 1369 char *zBuf /* Space to store a generated string */ 1370){ 1371 unsigned i = 0; 1372 if( strstr(z, zA)==0 ) return zA; 1373 if( strstr(z, zB)==0 ) return zB; 1374 do{ 1375 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); 1376 }while( strstr(z,zBuf)!=0 ); 1377 return zBuf; 1378} 1379 1380/* 1381** Output the given string as a quoted string using SQL quoting conventions. 1382** 1383** See also: output_quoted_escaped_string() 1384*/ 1385static void output_quoted_string(FILE *out, const char *z){ 1386 int i; 1387 char c; 1388 setBinaryMode(out, 1); 1389 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1390 if( c==0 ){ 1391 utf8_printf(out,"'%s'",z); 1392 }else{ 1393 raw_printf(out, "'"); 1394 while( *z ){ 1395 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1396 if( c=='\'' ) i++; 1397 if( i ){ 1398 utf8_printf(out, "%.*s", i, z); 1399 z += i; 1400 } 1401 if( c=='\'' ){ 1402 raw_printf(out, "'"); 1403 continue; 1404 } 1405 if( c==0 ){ 1406 break; 1407 } 1408 z++; 1409 } 1410 raw_printf(out, "'"); 1411 } 1412 setTextMode(out, 1); 1413} 1414 1415/* 1416** Output the given string as a quoted string using SQL quoting conventions. 1417** Additionallly , escape the "\n" and "\r" characters so that they do not 1418** get corrupted by end-of-line translation facilities in some operating 1419** systems. 1420** 1421** This is like output_quoted_string() but with the addition of the \r\n 1422** escape mechanism. 1423*/ 1424static void output_quoted_escaped_string(FILE *out, const char *z){ 1425 int i; 1426 char c; 1427 setBinaryMode(out, 1); 1428 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} 1429 if( c==0 ){ 1430 utf8_printf(out,"'%s'",z); 1431 }else{ 1432 const char *zNL = 0; 1433 const char *zCR = 0; 1434 int nNL = 0; 1435 int nCR = 0; 1436 char zBuf1[20], zBuf2[20]; 1437 for(i=0; z[i]; i++){ 1438 if( z[i]=='\n' ) nNL++; 1439 if( z[i]=='\r' ) nCR++; 1440 } 1441 if( nNL ){ 1442 raw_printf(out, "replace("); 1443 zNL = unused_string(z, "\\n", "\\012", zBuf1); 1444 } 1445 if( nCR ){ 1446 raw_printf(out, "replace("); 1447 zCR = unused_string(z, "\\r", "\\015", zBuf2); 1448 } 1449 raw_printf(out, "'"); 1450 while( *z ){ 1451 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} 1452 if( c=='\'' ) i++; 1453 if( i ){ 1454 utf8_printf(out, "%.*s", i, z); 1455 z += i; 1456 } 1457 if( c=='\'' ){ 1458 raw_printf(out, "'"); 1459 continue; 1460 } 1461 if( c==0 ){ 1462 break; 1463 } 1464 z++; 1465 if( c=='\n' ){ 1466 raw_printf(out, "%s", zNL); 1467 continue; 1468 } 1469 raw_printf(out, "%s", zCR); 1470 } 1471 raw_printf(out, "'"); 1472 if( nCR ){ 1473 raw_printf(out, ",'%s',char(13))", zCR); 1474 } 1475 if( nNL ){ 1476 raw_printf(out, ",'%s',char(10))", zNL); 1477 } 1478 } 1479 setTextMode(out, 1); 1480} 1481 1482/* 1483** Output the given string as a quoted according to C or TCL quoting rules. 1484*/ 1485static void output_c_string(FILE *out, const char *z){ 1486 unsigned int c; 1487 fputc('"', out); 1488 while( (c = *(z++))!=0 ){ 1489 if( c=='\\' ){ 1490 fputc(c, out); 1491 fputc(c, out); 1492 }else if( c=='"' ){ 1493 fputc('\\', out); 1494 fputc('"', out); 1495 }else if( c=='\t' ){ 1496 fputc('\\', out); 1497 fputc('t', out); 1498 }else if( c=='\n' ){ 1499 fputc('\\', out); 1500 fputc('n', out); 1501 }else if( c=='\r' ){ 1502 fputc('\\', out); 1503 fputc('r', out); 1504 }else if( !isprint(c&0xff) ){ 1505 raw_printf(out, "\\%03o", c&0xff); 1506 }else{ 1507 fputc(c, out); 1508 } 1509 } 1510 fputc('"', out); 1511} 1512 1513/* 1514** Output the given string with characters that are special to 1515** HTML escaped. 1516*/ 1517static void output_html_string(FILE *out, const char *z){ 1518 int i; 1519 if( z==0 ) z = ""; 1520 while( *z ){ 1521 for(i=0; z[i] 1522 && z[i]!='<' 1523 && z[i]!='&' 1524 && z[i]!='>' 1525 && z[i]!='\"' 1526 && z[i]!='\''; 1527 i++){} 1528 if( i>0 ){ 1529 utf8_printf(out,"%.*s",i,z); 1530 } 1531 if( z[i]=='<' ){ 1532 raw_printf(out,"<"); 1533 }else if( z[i]=='&' ){ 1534 raw_printf(out,"&"); 1535 }else if( z[i]=='>' ){ 1536 raw_printf(out,">"); 1537 }else if( z[i]=='\"' ){ 1538 raw_printf(out,"""); 1539 }else if( z[i]=='\'' ){ 1540 raw_printf(out,"'"); 1541 }else{ 1542 break; 1543 } 1544 z += i + 1; 1545 } 1546} 1547 1548/* 1549** If a field contains any character identified by a 1 in the following 1550** array, then the string must be quoted for CSV. 1551*/ 1552static const char needCsvQuote[] = { 1553 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1554 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1555 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1556 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1557 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1558 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1559 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1560 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1561 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1562 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1563 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1564 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1565 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1566 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1567 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1568 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1569}; 1570 1571/* 1572** Output a single term of CSV. Actually, p->colSeparator is used for 1573** the separator, which may or may not be a comma. p->nullValue is 1574** the null value. Strings are quoted if necessary. The separator 1575** is only issued if bSep is true. 1576*/ 1577static void output_csv(ShellState *p, const char *z, int bSep){ 1578 FILE *out = p->out; 1579 if( z==0 ){ 1580 utf8_printf(out,"%s",p->nullValue); 1581 }else{ 1582 int i; 1583 int nSep = strlen30(p->colSeparator); 1584 for(i=0; z[i]; i++){ 1585 if( needCsvQuote[((unsigned char*)z)[i]] 1586 || (z[i]==p->colSeparator[0] && 1587 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){ 1588 i = 0; 1589 break; 1590 } 1591 } 1592 if( i==0 ){ 1593 char *zQuoted = sqlite3_mprintf("\"%w\"", z); 1594 utf8_printf(out, "%s", zQuoted); 1595 sqlite3_free(zQuoted); 1596 }else{ 1597 utf8_printf(out, "%s", z); 1598 } 1599 } 1600 if( bSep ){ 1601 utf8_printf(p->out, "%s", p->colSeparator); 1602 } 1603} 1604 1605/* 1606** This routine runs when the user presses Ctrl-C 1607*/ 1608static void interrupt_handler(int NotUsed){ 1609 UNUSED_PARAMETER(NotUsed); 1610 seenInterrupt++; 1611 if( seenInterrupt>2 ) exit(1); 1612 if( globalDb ) sqlite3_interrupt(globalDb); 1613} 1614 1615#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 1616/* 1617** This routine runs for console events (e.g. Ctrl-C) on Win32 1618*/ 1619static BOOL WINAPI ConsoleCtrlHandler( 1620 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ 1621){ 1622 if( dwCtrlType==CTRL_C_EVENT ){ 1623 interrupt_handler(0); 1624 return TRUE; 1625 } 1626 return FALSE; 1627} 1628#endif 1629 1630#ifndef SQLITE_OMIT_AUTHORIZATION 1631/* 1632** When the ".auth ON" is set, the following authorizer callback is 1633** invoked. It always returns SQLITE_OK. 1634*/ 1635static int shellAuth( 1636 void *pClientData, 1637 int op, 1638 const char *zA1, 1639 const char *zA2, 1640 const char *zA3, 1641 const char *zA4 1642){ 1643 ShellState *p = (ShellState*)pClientData; 1644 static const char *azAction[] = { 0, 1645 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", 1646 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", 1647 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", 1648 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", 1649 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", 1650 "DROP_TRIGGER", "DROP_VIEW", "INSERT", 1651 "PRAGMA", "READ", "SELECT", 1652 "TRANSACTION", "UPDATE", "ATTACH", 1653 "DETACH", "ALTER_TABLE", "REINDEX", 1654 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", 1655 "FUNCTION", "SAVEPOINT", "RECURSIVE" 1656 }; 1657 int i; 1658 const char *az[4]; 1659 az[0] = zA1; 1660 az[1] = zA2; 1661 az[2] = zA3; 1662 az[3] = zA4; 1663 utf8_printf(p->out, "authorizer: %s", azAction[op]); 1664 for(i=0; i<4; i++){ 1665 raw_printf(p->out, " "); 1666 if( az[i] ){ 1667 output_c_string(p->out, az[i]); 1668 }else{ 1669 raw_printf(p->out, "NULL"); 1670 } 1671 } 1672 raw_printf(p->out, "\n"); 1673 return SQLITE_OK; 1674} 1675#endif 1676 1677/* 1678** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. 1679** 1680** This routine converts some CREATE TABLE statements for shadow tables 1681** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. 1682*/ 1683static void printSchemaLine(FILE *out, const char *z, const char *zTail){ 1684 if( z==0 ) return; 1685 if( zTail==0 ) return; 1686 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ 1687 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); 1688 }else{ 1689 utf8_printf(out, "%s%s", z, zTail); 1690 } 1691} 1692static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){ 1693 char c = z[n]; 1694 z[n] = 0; 1695 printSchemaLine(out, z, zTail); 1696 z[n] = c; 1697} 1698 1699/* 1700** Return true if string z[] has nothing but whitespace and comments to the 1701** end of the first line. 1702*/ 1703static int wsToEol(const char *z){ 1704 int i; 1705 for(i=0; z[i]; i++){ 1706 if( z[i]=='\n' ) return 1; 1707 if( IsSpace(z[i]) ) continue; 1708 if( z[i]=='-' && z[i+1]=='-' ) return 1; 1709 return 0; 1710 } 1711 return 1; 1712} 1713 1714/* 1715** Add a new entry to the EXPLAIN QUERY PLAN data 1716*/ 1717static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){ 1718 EQPGraphRow *pNew; 1719 int nText = strlen30(zText); 1720 if( p->autoEQPtest ){ 1721 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); 1722 } 1723 pNew = sqlite3_malloc64( sizeof(*pNew) + nText ); 1724 if( pNew==0 ) shell_out_of_memory(); 1725 pNew->iEqpId = iEqpId; 1726 pNew->iParentId = p2; 1727 memcpy(pNew->zText, zText, nText+1); 1728 pNew->pNext = 0; 1729 if( p->sGraph.pLast ){ 1730 p->sGraph.pLast->pNext = pNew; 1731 }else{ 1732 p->sGraph.pRow = pNew; 1733 } 1734 p->sGraph.pLast = pNew; 1735} 1736 1737/* 1738** Free and reset the EXPLAIN QUERY PLAN data that has been collected 1739** in p->sGraph. 1740*/ 1741static void eqp_reset(ShellState *p){ 1742 EQPGraphRow *pRow, *pNext; 1743 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ 1744 pNext = pRow->pNext; 1745 sqlite3_free(pRow); 1746 } 1747 memset(&p->sGraph, 0, sizeof(p->sGraph)); 1748} 1749 1750/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after 1751** pOld, or return the first such line if pOld is NULL 1752*/ 1753static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){ 1754 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; 1755 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; 1756 return pRow; 1757} 1758 1759/* Render a single level of the graph that has iEqpId as its parent. Called 1760** recursively to render sublevels. 1761*/ 1762static void eqp_render_level(ShellState *p, int iEqpId){ 1763 EQPGraphRow *pRow, *pNext; 1764 int n = strlen30(p->sGraph.zPrefix); 1765 char *z; 1766 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){ 1767 pNext = eqp_next_row(p, iEqpId, pRow); 1768 z = pRow->zText; 1769 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z); 1770 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){ 1771 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); 1772 eqp_render_level(p, pRow->iEqpId); 1773 p->sGraph.zPrefix[n] = 0; 1774 } 1775 } 1776} 1777 1778/* 1779** Display and reset the EXPLAIN QUERY PLAN data 1780*/ 1781static void eqp_render(ShellState *p){ 1782 EQPGraphRow *pRow = p->sGraph.pRow; 1783 if( pRow ){ 1784 if( pRow->zText[0]=='-' ){ 1785 if( pRow->pNext==0 ){ 1786 eqp_reset(p); 1787 return; 1788 } 1789 utf8_printf(p->out, "%s\n", pRow->zText+3); 1790 p->sGraph.pRow = pRow->pNext; 1791 sqlite3_free(pRow); 1792 }else{ 1793 utf8_printf(p->out, "QUERY PLAN\n"); 1794 } 1795 p->sGraph.zPrefix[0] = 0; 1796 eqp_render_level(p, 0); 1797 eqp_reset(p); 1798 } 1799} 1800 1801#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1802/* 1803** Progress handler callback. 1804*/ 1805static int progress_handler(void *pClientData) { 1806 ShellState *p = (ShellState*)pClientData; 1807 p->nProgress++; 1808 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ 1809 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress); 1810 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 1811 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; 1812 return 1; 1813 } 1814 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ 1815 raw_printf(p->out, "Progress %u\n", p->nProgress); 1816 } 1817 return 0; 1818} 1819#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 1820 1821/* 1822** This is the callback routine that the shell 1823** invokes for each row of a query result. 1824*/ 1825static int shell_callback( 1826 void *pArg, 1827 int nArg, /* Number of result columns */ 1828 char **azArg, /* Text of each result column */ 1829 char **azCol, /* Column names */ 1830 int *aiType /* Column types */ 1831){ 1832 int i; 1833 ShellState *p = (ShellState*)pArg; 1834 1835 if( azArg==0 ) return 0; 1836 switch( p->cMode ){ 1837 case MODE_Line: { 1838 int w = 5; 1839 if( azArg==0 ) break; 1840 for(i=0; i<nArg; i++){ 1841 int len = strlen30(azCol[i] ? azCol[i] : ""); 1842 if( len>w ) w = len; 1843 } 1844 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); 1845 for(i=0; i<nArg; i++){ 1846 utf8_printf(p->out,"%*s = %s%s", w, azCol[i], 1847 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); 1848 } 1849 break; 1850 } 1851 case MODE_Explain: 1852 case MODE_Column: { 1853 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13}; 1854 const int *colWidth; 1855 int showHdr; 1856 char *rowSep; 1857 if( p->cMode==MODE_Column ){ 1858 colWidth = p->colWidth; 1859 showHdr = p->showHeader; 1860 rowSep = p->rowSeparator; 1861 }else{ 1862 colWidth = aExplainWidths; 1863 showHdr = 1; 1864 rowSep = SEP_Row; 1865 } 1866 if( p->cnt++==0 ){ 1867 for(i=0; i<nArg; i++){ 1868 int w, n; 1869 if( i<ArraySize(p->colWidth) ){ 1870 w = colWidth[i]; 1871 }else{ 1872 w = 0; 1873 } 1874 if( w==0 ){ 1875 w = strlenChar(azCol[i] ? azCol[i] : ""); 1876 if( w<10 ) w = 10; 1877 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue); 1878 if( w<n ) w = n; 1879 } 1880 if( i<ArraySize(p->actualWidth) ){ 1881 p->actualWidth[i] = w; 1882 } 1883 if( showHdr ){ 1884 utf8_width_print(p->out, w, azCol[i]); 1885 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " "); 1886 } 1887 } 1888 if( showHdr ){ 1889 for(i=0; i<nArg; i++){ 1890 int w; 1891 if( i<ArraySize(p->actualWidth) ){ 1892 w = p->actualWidth[i]; 1893 if( w<0 ) w = -w; 1894 }else{ 1895 w = 10; 1896 } 1897 utf8_printf(p->out,"%-*.*s%s",w,w, 1898 "----------------------------------------------------------" 1899 "----------------------------------------------------------", 1900 i==nArg-1 ? rowSep : " "); 1901 } 1902 } 1903 } 1904 if( azArg==0 ) break; 1905 for(i=0; i<nArg; i++){ 1906 int w; 1907 if( i<ArraySize(p->actualWidth) ){ 1908 w = p->actualWidth[i]; 1909 }else{ 1910 w = 10; 1911 } 1912 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){ 1913 w = strlenChar(azArg[i]); 1914 } 1915 if( i==1 && p->aiIndent && p->pStmt ){ 1916 if( p->iIndent<p->nIndent ){ 1917 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); 1918 } 1919 p->iIndent++; 1920 } 1921 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue); 1922 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " "); 1923 } 1924 break; 1925 } 1926 case MODE_Semi: { /* .schema and .fullschema output */ 1927 printSchemaLine(p->out, azArg[0], ";\n"); 1928 break; 1929 } 1930 case MODE_Pretty: { /* .schema and .fullschema with --indent */ 1931 char *z; 1932 int j; 1933 int nParen = 0; 1934 char cEnd = 0; 1935 char c; 1936 int nLine = 0; 1937 assert( nArg==1 ); 1938 if( azArg[0]==0 ) break; 1939 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 1940 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 1941 ){ 1942 utf8_printf(p->out, "%s;\n", azArg[0]); 1943 break; 1944 } 1945 z = sqlite3_mprintf("%s", azArg[0]); 1946 j = 0; 1947 for(i=0; IsSpace(z[i]); i++){} 1948 for(; (c = z[i])!=0; i++){ 1949 if( IsSpace(c) ){ 1950 if( z[j-1]=='\r' ) z[j-1] = '\n'; 1951 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; 1952 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ 1953 j--; 1954 } 1955 z[j++] = c; 1956 } 1957 while( j>0 && IsSpace(z[j-1]) ){ j--; } 1958 z[j] = 0; 1959 if( strlen30(z)>=79 ){ 1960 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */ 1961 if( c==cEnd ){ 1962 cEnd = 0; 1963 }else if( c=='"' || c=='\'' || c=='`' ){ 1964 cEnd = c; 1965 }else if( c=='[' ){ 1966 cEnd = ']'; 1967 }else if( c=='-' && z[i+1]=='-' ){ 1968 cEnd = '\n'; 1969 }else if( c=='(' ){ 1970 nParen++; 1971 }else if( c==')' ){ 1972 nParen--; 1973 if( nLine>0 && nParen==0 && j>0 ){ 1974 printSchemaLineN(p->out, z, j, "\n"); 1975 j = 0; 1976 } 1977 } 1978 z[j++] = c; 1979 if( nParen==1 && cEnd==0 1980 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) 1981 ){ 1982 if( c=='\n' ) j--; 1983 printSchemaLineN(p->out, z, j, "\n "); 1984 j = 0; 1985 nLine++; 1986 while( IsSpace(z[i+1]) ){ i++; } 1987 } 1988 } 1989 z[j] = 0; 1990 } 1991 printSchemaLine(p->out, z, ";\n"); 1992 sqlite3_free(z); 1993 break; 1994 } 1995 case MODE_List: { 1996 if( p->cnt++==0 && p->showHeader ){ 1997 for(i=0; i<nArg; i++){ 1998 utf8_printf(p->out,"%s%s",azCol[i], 1999 i==nArg-1 ? p->rowSeparator : p->colSeparator); 2000 } 2001 } 2002 if( azArg==0 ) break; 2003 for(i=0; i<nArg; i++){ 2004 char *z = azArg[i]; 2005 if( z==0 ) z = p->nullValue; 2006 utf8_printf(p->out, "%s", z); 2007 if( i<nArg-1 ){ 2008 utf8_printf(p->out, "%s", p->colSeparator); 2009 }else{ 2010 utf8_printf(p->out, "%s", p->rowSeparator); 2011 } 2012 } 2013 break; 2014 } 2015 case MODE_Html: { 2016 if( p->cnt++==0 && p->showHeader ){ 2017 raw_printf(p->out,"<TR>"); 2018 for(i=0; i<nArg; i++){ 2019 raw_printf(p->out,"<TH>"); 2020 output_html_string(p->out, azCol[i]); 2021 raw_printf(p->out,"</TH>\n"); 2022 } 2023 raw_printf(p->out,"</TR>\n"); 2024 } 2025 if( azArg==0 ) break; 2026 raw_printf(p->out,"<TR>"); 2027 for(i=0; i<nArg; i++){ 2028 raw_printf(p->out,"<TD>"); 2029 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2030 raw_printf(p->out,"</TD>\n"); 2031 } 2032 raw_printf(p->out,"</TR>\n"); 2033 break; 2034 } 2035 case MODE_Tcl: { 2036 if( p->cnt++==0 && p->showHeader ){ 2037 for(i=0; i<nArg; i++){ 2038 output_c_string(p->out,azCol[i] ? azCol[i] : ""); 2039 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2040 } 2041 utf8_printf(p->out, "%s", p->rowSeparator); 2042 } 2043 if( azArg==0 ) break; 2044 for(i=0; i<nArg; i++){ 2045 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2046 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2047 } 2048 utf8_printf(p->out, "%s", p->rowSeparator); 2049 break; 2050 } 2051 case MODE_Csv: { 2052 setBinaryMode(p->out, 1); 2053 if( p->cnt++==0 && p->showHeader ){ 2054 for(i=0; i<nArg; i++){ 2055 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); 2056 } 2057 utf8_printf(p->out, "%s", p->rowSeparator); 2058 } 2059 if( nArg>0 ){ 2060 for(i=0; i<nArg; i++){ 2061 output_csv(p, azArg[i], i<nArg-1); 2062 } 2063 utf8_printf(p->out, "%s", p->rowSeparator); 2064 } 2065 setTextMode(p->out, 1); 2066 break; 2067 } 2068 case MODE_Insert: { 2069 if( azArg==0 ) break; 2070 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); 2071 if( p->showHeader ){ 2072 raw_printf(p->out,"("); 2073 for(i=0; i<nArg; i++){ 2074 if( i>0 ) raw_printf(p->out, ","); 2075 if( quoteChar(azCol[i]) ){ 2076 char *z = sqlite3_mprintf("\"%w\"", azCol[i]); 2077 utf8_printf(p->out, "%s", z); 2078 sqlite3_free(z); 2079 }else{ 2080 raw_printf(p->out, "%s", azCol[i]); 2081 } 2082 } 2083 raw_printf(p->out,")"); 2084 } 2085 p->cnt++; 2086 for(i=0; i<nArg; i++){ 2087 raw_printf(p->out, i>0 ? "," : " VALUES("); 2088 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2089 utf8_printf(p->out,"NULL"); 2090 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2091 if( ShellHasFlag(p, SHFLG_Newlines) ){ 2092 output_quoted_string(p->out, azArg[i]); 2093 }else{ 2094 output_quoted_escaped_string(p->out, azArg[i]); 2095 } 2096 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2097 utf8_printf(p->out,"%s", azArg[i]); 2098 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2099 char z[50]; 2100 double r = sqlite3_column_double(p->pStmt, i); 2101 sqlite3_uint64 ur; 2102 memcpy(&ur,&r,sizeof(r)); 2103 if( ur==0x7ff0000000000000LL ){ 2104 raw_printf(p->out, "1e999"); 2105 }else if( ur==0xfff0000000000000LL ){ 2106 raw_printf(p->out, "-1e999"); 2107 }else{ 2108 sqlite3_snprintf(50,z,"%!.20g", r); 2109 raw_printf(p->out, "%s", z); 2110 } 2111 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2112 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2113 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2114 output_hex_blob(p->out, pBlob, nBlob); 2115 }else if( isNumber(azArg[i], 0) ){ 2116 utf8_printf(p->out,"%s", azArg[i]); 2117 }else if( ShellHasFlag(p, SHFLG_Newlines) ){ 2118 output_quoted_string(p->out, azArg[i]); 2119 }else{ 2120 output_quoted_escaped_string(p->out, azArg[i]); 2121 } 2122 } 2123 raw_printf(p->out,");\n"); 2124 break; 2125 } 2126 case MODE_Quote: { 2127 if( azArg==0 ) break; 2128 if( p->cnt==0 && p->showHeader ){ 2129 for(i=0; i<nArg; i++){ 2130 if( i>0 ) raw_printf(p->out, ","); 2131 output_quoted_string(p->out, azCol[i]); 2132 } 2133 raw_printf(p->out,"\n"); 2134 } 2135 p->cnt++; 2136 for(i=0; i<nArg; i++){ 2137 if( i>0 ) raw_printf(p->out, ","); 2138 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2139 utf8_printf(p->out,"NULL"); 2140 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2141 output_quoted_string(p->out, azArg[i]); 2142 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2143 utf8_printf(p->out,"%s", azArg[i]); 2144 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2145 char z[50]; 2146 double r = sqlite3_column_double(p->pStmt, i); 2147 sqlite3_snprintf(50,z,"%!.20g", r); 2148 raw_printf(p->out, "%s", z); 2149 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2150 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2151 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2152 output_hex_blob(p->out, pBlob, nBlob); 2153 }else if( isNumber(azArg[i], 0) ){ 2154 utf8_printf(p->out,"%s", azArg[i]); 2155 }else{ 2156 output_quoted_string(p->out, azArg[i]); 2157 } 2158 } 2159 raw_printf(p->out,"\n"); 2160 break; 2161 } 2162 case MODE_Ascii: { 2163 if( p->cnt++==0 && p->showHeader ){ 2164 for(i=0; i<nArg; i++){ 2165 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2166 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); 2167 } 2168 utf8_printf(p->out, "%s", p->rowSeparator); 2169 } 2170 if( azArg==0 ) break; 2171 for(i=0; i<nArg; i++){ 2172 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2173 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); 2174 } 2175 utf8_printf(p->out, "%s", p->rowSeparator); 2176 break; 2177 } 2178 case MODE_EQP: { 2179 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]); 2180 break; 2181 } 2182 } 2183 return 0; 2184} 2185 2186/* 2187** This is the callback routine that the SQLite library 2188** invokes for each row of a query result. 2189*/ 2190static int callback(void *pArg, int nArg, char **azArg, char **azCol){ 2191 /* since we don't have type info, call the shell_callback with a NULL value */ 2192 return shell_callback(pArg, nArg, azArg, azCol, NULL); 2193} 2194 2195/* 2196** This is the callback routine from sqlite3_exec() that appends all 2197** output onto the end of a ShellText object. 2198*/ 2199static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ 2200 ShellText *p = (ShellText*)pArg; 2201 int i; 2202 UNUSED_PARAMETER(az); 2203 if( azArg==0 ) return 0; 2204 if( p->n ) appendText(p, "|", 0); 2205 for(i=0; i<nArg; i++){ 2206 if( i ) appendText(p, ",", 0); 2207 if( azArg[i] ) appendText(p, azArg[i], 0); 2208 } 2209 return 0; 2210} 2211 2212/* 2213** Generate an appropriate SELFTEST table in the main database. 2214*/ 2215static void createSelftestTable(ShellState *p){ 2216 char *zErrMsg = 0; 2217 sqlite3_exec(p->db, 2218 "SAVEPOINT selftest_init;\n" 2219 "CREATE TABLE IF NOT EXISTS selftest(\n" 2220 " tno INTEGER PRIMARY KEY,\n" /* Test number */ 2221 " op TEXT,\n" /* Operator: memo run */ 2222 " cmd TEXT,\n" /* Command text */ 2223 " ans TEXT\n" /* Desired answer */ 2224 ");" 2225 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" 2226 "INSERT INTO [_shell$self](rowid,op,cmd)\n" 2227 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" 2228 " 'memo','Tests generated by --init');\n" 2229 "INSERT INTO [_shell$self]\n" 2230 " SELECT 'run',\n" 2231 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " 2232 "FROM sqlite_master ORDER BY 2'',224))',\n" 2233 " hex(sha3_query('SELECT type,name,tbl_name,sql " 2234 "FROM sqlite_master ORDER BY 2',224));\n" 2235 "INSERT INTO [_shell$self]\n" 2236 " SELECT 'run'," 2237 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" 2238 " printf('%w',name) || '\" NOT INDEXED'',224))',\n" 2239 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" 2240 " FROM (\n" 2241 " SELECT name FROM sqlite_master\n" 2242 " WHERE type='table'\n" 2243 " AND name<>'selftest'\n" 2244 " AND coalesce(rootpage,0)>0\n" 2245 " )\n" 2246 " ORDER BY name;\n" 2247 "INSERT INTO [_shell$self]\n" 2248 " VALUES('run','PRAGMA integrity_check','ok');\n" 2249 "INSERT INTO selftest(tno,op,cmd,ans)" 2250 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" 2251 "DROP TABLE [_shell$self];" 2252 ,0,0,&zErrMsg); 2253 if( zErrMsg ){ 2254 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); 2255 sqlite3_free(zErrMsg); 2256 } 2257 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); 2258} 2259 2260 2261/* 2262** Set the destination table field of the ShellState structure to 2263** the name of the table given. Escape any quote characters in the 2264** table name. 2265*/ 2266static void set_table_name(ShellState *p, const char *zName){ 2267 int i, n; 2268 char cQuote; 2269 char *z; 2270 2271 if( p->zDestTable ){ 2272 free(p->zDestTable); 2273 p->zDestTable = 0; 2274 } 2275 if( zName==0 ) return; 2276 cQuote = quoteChar(zName); 2277 n = strlen30(zName); 2278 if( cQuote ) n += n+2; 2279 z = p->zDestTable = malloc( n+1 ); 2280 if( z==0 ) shell_out_of_memory(); 2281 n = 0; 2282 if( cQuote ) z[n++] = cQuote; 2283 for(i=0; zName[i]; i++){ 2284 z[n++] = zName[i]; 2285 if( zName[i]==cQuote ) z[n++] = cQuote; 2286 } 2287 if( cQuote ) z[n++] = cQuote; 2288 z[n] = 0; 2289} 2290 2291 2292/* 2293** Execute a query statement that will generate SQL output. Print 2294** the result columns, comma-separated, on a line and then add a 2295** semicolon terminator to the end of that line. 2296** 2297** If the number of columns is 1 and that column contains text "--" 2298** then write the semicolon on a separate line. That way, if a 2299** "--" comment occurs at the end of the statement, the comment 2300** won't consume the semicolon terminator. 2301*/ 2302static int run_table_dump_query( 2303 ShellState *p, /* Query context */ 2304 const char *zSelect, /* SELECT statement to extract content */ 2305 const char *zFirstRow /* Print before first row, if not NULL */ 2306){ 2307 sqlite3_stmt *pSelect; 2308 int rc; 2309 int nResult; 2310 int i; 2311 const char *z; 2312 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); 2313 if( rc!=SQLITE_OK || !pSelect ){ 2314 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2315 sqlite3_errmsg(p->db)); 2316 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2317 return rc; 2318 } 2319 rc = sqlite3_step(pSelect); 2320 nResult = sqlite3_column_count(pSelect); 2321 while( rc==SQLITE_ROW ){ 2322 if( zFirstRow ){ 2323 utf8_printf(p->out, "%s", zFirstRow); 2324 zFirstRow = 0; 2325 } 2326 z = (const char*)sqlite3_column_text(pSelect, 0); 2327 utf8_printf(p->out, "%s", z); 2328 for(i=1; i<nResult; i++){ 2329 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); 2330 } 2331 if( z==0 ) z = ""; 2332 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; 2333 if( z[0] ){ 2334 raw_printf(p->out, "\n;\n"); 2335 }else{ 2336 raw_printf(p->out, ";\n"); 2337 } 2338 rc = sqlite3_step(pSelect); 2339 } 2340 rc = sqlite3_finalize(pSelect); 2341 if( rc!=SQLITE_OK ){ 2342 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2343 sqlite3_errmsg(p->db)); 2344 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2345 } 2346 return rc; 2347} 2348 2349/* 2350** Allocate space and save off current error string. 2351*/ 2352static char *save_err_msg( 2353 sqlite3 *db /* Database to query */ 2354){ 2355 int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); 2356 char *zErrMsg = sqlite3_malloc64(nErrMsg); 2357 if( zErrMsg ){ 2358 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); 2359 } 2360 return zErrMsg; 2361} 2362 2363#ifdef __linux__ 2364/* 2365** Attempt to display I/O stats on Linux using /proc/PID/io 2366*/ 2367static void displayLinuxIoStats(FILE *out){ 2368 FILE *in; 2369 char z[200]; 2370 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); 2371 in = fopen(z, "rb"); 2372 if( in==0 ) return; 2373 while( fgets(z, sizeof(z), in)!=0 ){ 2374 static const struct { 2375 const char *zPattern; 2376 const char *zDesc; 2377 } aTrans[] = { 2378 { "rchar: ", "Bytes received by read():" }, 2379 { "wchar: ", "Bytes sent to write():" }, 2380 { "syscr: ", "Read() system calls:" }, 2381 { "syscw: ", "Write() system calls:" }, 2382 { "read_bytes: ", "Bytes read from storage:" }, 2383 { "write_bytes: ", "Bytes written to storage:" }, 2384 { "cancelled_write_bytes: ", "Cancelled write bytes:" }, 2385 }; 2386 int i; 2387 for(i=0; i<ArraySize(aTrans); i++){ 2388 int n = strlen30(aTrans[i].zPattern); 2389 if( strncmp(aTrans[i].zPattern, z, n)==0 ){ 2390 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); 2391 break; 2392 } 2393 } 2394 } 2395 fclose(in); 2396} 2397#endif 2398 2399/* 2400** Display a single line of status using 64-bit values. 2401*/ 2402static void displayStatLine( 2403 ShellState *p, /* The shell context */ 2404 char *zLabel, /* Label for this one line */ 2405 char *zFormat, /* Format for the result */ 2406 int iStatusCtrl, /* Which status to display */ 2407 int bReset /* True to reset the stats */ 2408){ 2409 sqlite3_int64 iCur = -1; 2410 sqlite3_int64 iHiwtr = -1; 2411 int i, nPercent; 2412 char zLine[200]; 2413 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset); 2414 for(i=0, nPercent=0; zFormat[i]; i++){ 2415 if( zFormat[i]=='%' ) nPercent++; 2416 } 2417 if( nPercent>1 ){ 2418 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); 2419 }else{ 2420 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); 2421 } 2422 raw_printf(p->out, "%-36s %s\n", zLabel, zLine); 2423} 2424 2425/* 2426** Display memory stats. 2427*/ 2428static int display_stats( 2429 sqlite3 *db, /* Database to query */ 2430 ShellState *pArg, /* Pointer to ShellState */ 2431 int bReset /* True to reset the stats */ 2432){ 2433 int iCur; 2434 int iHiwtr; 2435 FILE *out; 2436 if( pArg==0 || pArg->out==0 ) return 0; 2437 out = pArg->out; 2438 2439 if( pArg->pStmt && (pArg->statsOn & 2) ){ 2440 int nCol, i, x; 2441 sqlite3_stmt *pStmt = pArg->pStmt; 2442 char z[100]; 2443 nCol = sqlite3_column_count(pStmt); 2444 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol); 2445 for(i=0; i<nCol; i++){ 2446 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x); 2447 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); 2448#ifndef SQLITE_OMIT_DECLTYPE 2449 sqlite3_snprintf(30, z+x, "declared type:"); 2450 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); 2451#endif 2452#ifdef SQLITE_ENABLE_COLUMN_METADATA 2453 sqlite3_snprintf(30, z+x, "database name:"); 2454 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); 2455 sqlite3_snprintf(30, z+x, "table name:"); 2456 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); 2457 sqlite3_snprintf(30, z+x, "origin name:"); 2458 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); 2459#endif 2460 } 2461 } 2462 2463 displayStatLine(pArg, "Memory Used:", 2464 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); 2465 displayStatLine(pArg, "Number of Outstanding Allocations:", 2466 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); 2467 if( pArg->shellFlgs & SHFLG_Pagecache ){ 2468 displayStatLine(pArg, "Number of Pcache Pages Used:", 2469 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); 2470 } 2471 displayStatLine(pArg, "Number of Pcache Overflow Bytes:", 2472 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); 2473 displayStatLine(pArg, "Largest Allocation:", 2474 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); 2475 displayStatLine(pArg, "Largest Pcache Allocation:", 2476 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); 2477#ifdef YYTRACKMAXSTACKDEPTH 2478 displayStatLine(pArg, "Deepest Parser Stack:", 2479 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); 2480#endif 2481 2482 if( db ){ 2483 if( pArg->shellFlgs & SHFLG_Lookaside ){ 2484 iHiwtr = iCur = -1; 2485 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, 2486 &iCur, &iHiwtr, bReset); 2487 raw_printf(pArg->out, 2488 "Lookaside Slots Used: %d (max %d)\n", 2489 iCur, iHiwtr); 2490 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, 2491 &iCur, &iHiwtr, bReset); 2492 raw_printf(pArg->out, "Successful lookaside attempts: %d\n", 2493 iHiwtr); 2494 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, 2495 &iCur, &iHiwtr, bReset); 2496 raw_printf(pArg->out, "Lookaside failures due to size: %d\n", 2497 iHiwtr); 2498 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, 2499 &iCur, &iHiwtr, bReset); 2500 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", 2501 iHiwtr); 2502 } 2503 iHiwtr = iCur = -1; 2504 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); 2505 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", 2506 iCur); 2507 iHiwtr = iCur = -1; 2508 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); 2509 raw_printf(pArg->out, "Page cache hits: %d\n", iCur); 2510 iHiwtr = iCur = -1; 2511 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); 2512 raw_printf(pArg->out, "Page cache misses: %d\n", iCur); 2513 iHiwtr = iCur = -1; 2514 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); 2515 raw_printf(pArg->out, "Page cache writes: %d\n", iCur); 2516 iHiwtr = iCur = -1; 2517 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); 2518 raw_printf(pArg->out, "Page cache spills: %d\n", iCur); 2519 iHiwtr = iCur = -1; 2520 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); 2521 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", 2522 iCur); 2523 iHiwtr = iCur = -1; 2524 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); 2525 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", 2526 iCur); 2527 } 2528 2529 if( pArg->pStmt ){ 2530 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, 2531 bReset); 2532 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); 2533 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); 2534 raw_printf(pArg->out, "Sort Operations: %d\n", iCur); 2535 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); 2536 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); 2537 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2538 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); 2539 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset); 2540 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur); 2541 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); 2542 raw_printf(pArg->out, "Number of times run: %d\n", iCur); 2543 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); 2544 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur); 2545 } 2546 2547#ifdef __linux__ 2548 displayLinuxIoStats(pArg->out); 2549#endif 2550 2551 /* Do not remove this machine readable comment: extra-stats-output-here */ 2552 2553 return 0; 2554} 2555 2556/* 2557** Display scan stats. 2558*/ 2559static void display_scanstats( 2560 sqlite3 *db, /* Database to query */ 2561 ShellState *pArg /* Pointer to ShellState */ 2562){ 2563#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 2564 UNUSED_PARAMETER(db); 2565 UNUSED_PARAMETER(pArg); 2566#else 2567 int i, k, n, mx; 2568 raw_printf(pArg->out, "-------- scanstats --------\n"); 2569 mx = 0; 2570 for(k=0; k<=mx; k++){ 2571 double rEstLoop = 1.0; 2572 for(i=n=0; 1; i++){ 2573 sqlite3_stmt *p = pArg->pStmt; 2574 sqlite3_int64 nLoop, nVisit; 2575 double rEst; 2576 int iSid; 2577 const char *zExplain; 2578 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ 2579 break; 2580 } 2581 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); 2582 if( iSid>mx ) mx = iSid; 2583 if( iSid!=k ) continue; 2584 if( n==0 ){ 2585 rEstLoop = (double)nLoop; 2586 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); 2587 } 2588 n++; 2589 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); 2590 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); 2591 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); 2592 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); 2593 rEstLoop *= rEst; 2594 raw_printf(pArg->out, 2595 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", 2596 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst 2597 ); 2598 } 2599 } 2600 raw_printf(pArg->out, "---------------------------\n"); 2601#endif 2602} 2603 2604/* 2605** Parameter azArray points to a zero-terminated array of strings. zStr 2606** points to a single nul-terminated string. Return non-zero if zStr 2607** is equal, according to strcmp(), to any of the strings in the array. 2608** Otherwise, return zero. 2609*/ 2610static int str_in_array(const char *zStr, const char **azArray){ 2611 int i; 2612 for(i=0; azArray[i]; i++){ 2613 if( 0==strcmp(zStr, azArray[i]) ) return 1; 2614 } 2615 return 0; 2616} 2617 2618/* 2619** If compiled statement pSql appears to be an EXPLAIN statement, allocate 2620** and populate the ShellState.aiIndent[] array with the number of 2621** spaces each opcode should be indented before it is output. 2622** 2623** The indenting rules are: 2624** 2625** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent 2626** all opcodes that occur between the p2 jump destination and the opcode 2627** itself by 2 spaces. 2628** 2629** * For each "Goto", if the jump destination is earlier in the program 2630** and ends on one of: 2631** Yield SeekGt SeekLt RowSetRead Rewind 2632** or if the P1 parameter is one instead of zero, 2633** then indent all opcodes between the earlier instruction 2634** and "Goto" by 2 spaces. 2635*/ 2636static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ 2637 const char *zSql; /* The text of the SQL statement */ 2638 const char *z; /* Used to check if this is an EXPLAIN */ 2639 int *abYield = 0; /* True if op is an OP_Yield */ 2640 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ 2641 int iOp; /* Index of operation in p->aiIndent[] */ 2642 2643 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 }; 2644 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", 2645 "Rewind", 0 }; 2646 const char *azGoto[] = { "Goto", 0 }; 2647 2648 /* Try to figure out if this is really an EXPLAIN statement. If this 2649 ** cannot be verified, return early. */ 2650 if( sqlite3_column_count(pSql)!=8 ){ 2651 p->cMode = p->mode; 2652 return; 2653 } 2654 zSql = sqlite3_sql(pSql); 2655 if( zSql==0 ) return; 2656 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); 2657 if( sqlite3_strnicmp(z, "explain", 7) ){ 2658 p->cMode = p->mode; 2659 return; 2660 } 2661 2662 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ 2663 int i; 2664 int iAddr = sqlite3_column_int(pSql, 0); 2665 const char *zOp = (const char*)sqlite3_column_text(pSql, 1); 2666 2667 /* Set p2 to the P2 field of the current opcode. Then, assuming that 2668 ** p2 is an instruction address, set variable p2op to the index of that 2669 ** instruction in the aiIndent[] array. p2 and p2op may be different if 2670 ** the current instruction is part of a sub-program generated by an 2671 ** SQL trigger or foreign key. */ 2672 int p2 = sqlite3_column_int(pSql, 3); 2673 int p2op = (p2 + (iOp-iAddr)); 2674 2675 /* Grow the p->aiIndent array as required */ 2676 if( iOp>=nAlloc ){ 2677 if( iOp==0 ){ 2678 /* Do further verfication that this is explain output. Abort if 2679 ** it is not */ 2680 static const char *explainCols[] = { 2681 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; 2682 int jj; 2683 for(jj=0; jj<ArraySize(explainCols); jj++){ 2684 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){ 2685 p->cMode = p->mode; 2686 sqlite3_reset(pSql); 2687 return; 2688 } 2689 } 2690 } 2691 nAlloc += 100; 2692 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); 2693 if( p->aiIndent==0 ) shell_out_of_memory(); 2694 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); 2695 if( abYield==0 ) shell_out_of_memory(); 2696 } 2697 abYield[iOp] = str_in_array(zOp, azYield); 2698 p->aiIndent[iOp] = 0; 2699 p->nIndent = iOp+1; 2700 2701 if( str_in_array(zOp, azNext) ){ 2702 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2703 } 2704 if( str_in_array(zOp, azGoto) && p2op<p->nIndent 2705 && (abYield[p2op] || sqlite3_column_int(pSql, 2)) 2706 ){ 2707 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2708 } 2709 } 2710 2711 p->iIndent = 0; 2712 sqlite3_free(abYield); 2713 sqlite3_reset(pSql); 2714} 2715 2716/* 2717** Free the array allocated by explain_data_prepare(). 2718*/ 2719static void explain_data_delete(ShellState *p){ 2720 sqlite3_free(p->aiIndent); 2721 p->aiIndent = 0; 2722 p->nIndent = 0; 2723 p->iIndent = 0; 2724} 2725 2726/* 2727** Disable and restore .wheretrace and .selecttrace settings. 2728*/ 2729#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2730extern int sqlite3SelectTrace; 2731static int savedSelectTrace; 2732#endif 2733#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2734extern int sqlite3WhereTrace; 2735static int savedWhereTrace; 2736#endif 2737static void disable_debug_trace_modes(void){ 2738#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2739 savedSelectTrace = sqlite3SelectTrace; 2740 sqlite3SelectTrace = 0; 2741#endif 2742#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2743 savedWhereTrace = sqlite3WhereTrace; 2744 sqlite3WhereTrace = 0; 2745#endif 2746} 2747static void restore_debug_trace_modes(void){ 2748#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2749 sqlite3SelectTrace = savedSelectTrace; 2750#endif 2751#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2752 sqlite3WhereTrace = savedWhereTrace; 2753#endif 2754} 2755 2756/* Create the TEMP table used to store parameter bindings */ 2757static void bind_table_init(ShellState *p){ 2758 int wrSchema = 0; 2759 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); 2760 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 2761 sqlite3_exec(p->db, 2762 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n" 2763 " key TEXT PRIMARY KEY,\n" 2764 " value ANY\n" 2765 ") WITHOUT ROWID;", 2766 0, 0, 0); 2767 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); 2768} 2769 2770/* 2771** Bind parameters on a prepared statement. 2772** 2773** Parameter bindings are taken from a TEMP table of the form: 2774** 2775** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value) 2776** WITHOUT ROWID; 2777** 2778** No bindings occur if this table does not exist. The special character '$' 2779** is included in the table name to help prevent collisions with actual tables. 2780** The table must be in the TEMP schema. 2781*/ 2782static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ 2783 int nVar; 2784 int i; 2785 int rc; 2786 sqlite3_stmt *pQ = 0; 2787 2788 nVar = sqlite3_bind_parameter_count(pStmt); 2789 if( nVar==0 ) return; /* Nothing to do */ 2790 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", 2791 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ 2792 return; /* Parameter table does not exist */ 2793 } 2794 rc = sqlite3_prepare_v2(pArg->db, 2795 "SELECT value FROM temp.sqlite_parameters" 2796 " WHERE key=?1", -1, &pQ, 0); 2797 if( rc || pQ==0 ) return; 2798 for(i=1; i<=nVar; i++){ 2799 char zNum[30]; 2800 const char *zVar = sqlite3_bind_parameter_name(pStmt, i); 2801 if( zVar==0 ){ 2802 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); 2803 zVar = zNum; 2804 } 2805 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); 2806 if( sqlite3_step(pQ)==SQLITE_ROW ){ 2807 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); 2808 }else{ 2809 sqlite3_bind_null(pStmt, i); 2810 } 2811 sqlite3_reset(pQ); 2812 } 2813 sqlite3_finalize(pQ); 2814} 2815 2816/* 2817** Run a prepared statement 2818*/ 2819static void exec_prepared_stmt( 2820 ShellState *pArg, /* Pointer to ShellState */ 2821 sqlite3_stmt *pStmt /* Statment to run */ 2822){ 2823 int rc; 2824 2825 /* perform the first step. this will tell us if we 2826 ** have a result set or not and how wide it is. 2827 */ 2828 rc = sqlite3_step(pStmt); 2829 /* if we have a result set... */ 2830 if( SQLITE_ROW == rc ){ 2831 /* allocate space for col name ptr, value ptr, and type */ 2832 int nCol = sqlite3_column_count(pStmt); 2833 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); 2834 if( !pData ){ 2835 rc = SQLITE_NOMEM; 2836 }else{ 2837 char **azCols = (char **)pData; /* Names of result columns */ 2838 char **azVals = &azCols[nCol]; /* Results */ 2839 int *aiTypes = (int *)&azVals[nCol]; /* Result types */ 2840 int i, x; 2841 assert(sizeof(int) <= sizeof(char *)); 2842 /* save off ptrs to column names */ 2843 for(i=0; i<nCol; i++){ 2844 azCols[i] = (char *)sqlite3_column_name(pStmt, i); 2845 } 2846 do{ 2847 /* extract the data and data types */ 2848 for(i=0; i<nCol; i++){ 2849 aiTypes[i] = x = sqlite3_column_type(pStmt, i); 2850 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){ 2851 azVals[i] = ""; 2852 }else{ 2853 azVals[i] = (char*)sqlite3_column_text(pStmt, i); 2854 } 2855 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ 2856 rc = SQLITE_NOMEM; 2857 break; /* from for */ 2858 } 2859 } /* end for */ 2860 2861 /* if data and types extracted successfully... */ 2862 if( SQLITE_ROW == rc ){ 2863 /* call the supplied callback with the result row data */ 2864 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ 2865 rc = SQLITE_ABORT; 2866 }else{ 2867 rc = sqlite3_step(pStmt); 2868 } 2869 } 2870 } while( SQLITE_ROW == rc ); 2871 sqlite3_free(pData); 2872 } 2873 } 2874} 2875 2876#ifndef SQLITE_OMIT_VIRTUALTABLE 2877/* 2878** This function is called to process SQL if the previous shell command 2879** was ".expert". It passes the SQL in the second argument directly to 2880** the sqlite3expert object. 2881** 2882** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 2883** code. In this case, (*pzErr) may be set to point to a buffer containing 2884** an English language error message. It is the responsibility of the 2885** caller to eventually free this buffer using sqlite3_free(). 2886*/ 2887static int expertHandleSQL( 2888 ShellState *pState, 2889 const char *zSql, 2890 char **pzErr 2891){ 2892 assert( pState->expert.pExpert ); 2893 assert( pzErr==0 || *pzErr==0 ); 2894 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); 2895} 2896 2897/* 2898** This function is called either to silently clean up the object 2899** created by the ".expert" command (if bCancel==1), or to generate a 2900** report from it and then clean it up (if bCancel==0). 2901** 2902** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 2903** code. In this case, (*pzErr) may be set to point to a buffer containing 2904** an English language error message. It is the responsibility of the 2905** caller to eventually free this buffer using sqlite3_free(). 2906*/ 2907static int expertFinish( 2908 ShellState *pState, 2909 int bCancel, 2910 char **pzErr 2911){ 2912 int rc = SQLITE_OK; 2913 sqlite3expert *p = pState->expert.pExpert; 2914 assert( p ); 2915 assert( bCancel || pzErr==0 || *pzErr==0 ); 2916 if( bCancel==0 ){ 2917 FILE *out = pState->out; 2918 int bVerbose = pState->expert.bVerbose; 2919 2920 rc = sqlite3_expert_analyze(p, pzErr); 2921 if( rc==SQLITE_OK ){ 2922 int nQuery = sqlite3_expert_count(p); 2923 int i; 2924 2925 if( bVerbose ){ 2926 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); 2927 raw_printf(out, "-- Candidates -----------------------------\n"); 2928 raw_printf(out, "%s\n", zCand); 2929 } 2930 for(i=0; i<nQuery; i++){ 2931 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); 2932 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); 2933 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); 2934 if( zIdx==0 ) zIdx = "(no new indexes)\n"; 2935 if( bVerbose ){ 2936 raw_printf(out, "-- Query %d --------------------------------\n",i+1); 2937 raw_printf(out, "%s\n\n", zSql); 2938 } 2939 raw_printf(out, "%s\n", zIdx); 2940 raw_printf(out, "%s\n", zEQP); 2941 } 2942 } 2943 } 2944 sqlite3_expert_destroy(p); 2945 pState->expert.pExpert = 0; 2946 return rc; 2947} 2948 2949/* 2950** Implementation of ".expert" dot command. 2951*/ 2952static int expertDotCommand( 2953 ShellState *pState, /* Current shell tool state */ 2954 char **azArg, /* Array of arguments passed to dot command */ 2955 int nArg /* Number of entries in azArg[] */ 2956){ 2957 int rc = SQLITE_OK; 2958 char *zErr = 0; 2959 int i; 2960 int iSample = 0; 2961 2962 assert( pState->expert.pExpert==0 ); 2963 memset(&pState->expert, 0, sizeof(ExpertInfo)); 2964 2965 for(i=1; rc==SQLITE_OK && i<nArg; i++){ 2966 char *z = azArg[i]; 2967 int n; 2968 if( z[0]=='-' && z[1]=='-' ) z++; 2969 n = strlen30(z); 2970 if( n>=2 && 0==strncmp(z, "-verbose", n) ){ 2971 pState->expert.bVerbose = 1; 2972 } 2973 else if( n>=2 && 0==strncmp(z, "-sample", n) ){ 2974 if( i==(nArg-1) ){ 2975 raw_printf(stderr, "option requires an argument: %s\n", z); 2976 rc = SQLITE_ERROR; 2977 }else{ 2978 iSample = (int)integerValue(azArg[++i]); 2979 if( iSample<0 || iSample>100 ){ 2980 raw_printf(stderr, "value out of range: %s\n", azArg[i]); 2981 rc = SQLITE_ERROR; 2982 } 2983 } 2984 } 2985 else{ 2986 raw_printf(stderr, "unknown option: %s\n", z); 2987 rc = SQLITE_ERROR; 2988 } 2989 } 2990 2991 if( rc==SQLITE_OK ){ 2992 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); 2993 if( pState->expert.pExpert==0 ){ 2994 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr); 2995 rc = SQLITE_ERROR; 2996 }else{ 2997 sqlite3_expert_config( 2998 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample 2999 ); 3000 } 3001 } 3002 3003 return rc; 3004} 3005#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 3006 3007/* 3008** Execute a statement or set of statements. Print 3009** any result rows/columns depending on the current mode 3010** set via the supplied callback. 3011** 3012** This is very similar to SQLite's built-in sqlite3_exec() 3013** function except it takes a slightly different callback 3014** and callback data argument. 3015*/ 3016static int shell_exec( 3017 ShellState *pArg, /* Pointer to ShellState */ 3018 const char *zSql, /* SQL to be evaluated */ 3019 char **pzErrMsg /* Error msg written here */ 3020){ 3021 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ 3022 int rc = SQLITE_OK; /* Return Code */ 3023 int rc2; 3024 const char *zLeftover; /* Tail of unprocessed SQL */ 3025 sqlite3 *db = pArg->db; 3026 3027 if( pzErrMsg ){ 3028 *pzErrMsg = NULL; 3029 } 3030 3031#ifndef SQLITE_OMIT_VIRTUALTABLE 3032 if( pArg->expert.pExpert ){ 3033 rc = expertHandleSQL(pArg, zSql, pzErrMsg); 3034 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); 3035 } 3036#endif 3037 3038 while( zSql[0] && (SQLITE_OK == rc) ){ 3039 static const char *zStmtSql; 3040 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); 3041 if( SQLITE_OK != rc ){ 3042 if( pzErrMsg ){ 3043 *pzErrMsg = save_err_msg(db); 3044 } 3045 }else{ 3046 if( !pStmt ){ 3047 /* this happens for a comment or white-space */ 3048 zSql = zLeftover; 3049 while( IsSpace(zSql[0]) ) zSql++; 3050 continue; 3051 } 3052 zStmtSql = sqlite3_sql(pStmt); 3053 if( zStmtSql==0 ) zStmtSql = ""; 3054 while( IsSpace(zStmtSql[0]) ) zStmtSql++; 3055 3056 /* save off the prepared statment handle and reset row count */ 3057 if( pArg ){ 3058 pArg->pStmt = pStmt; 3059 pArg->cnt = 0; 3060 } 3061 3062 /* echo the sql statement if echo on */ 3063 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){ 3064 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); 3065 } 3066 3067 /* Show the EXPLAIN QUERY PLAN if .eqp is on */ 3068 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ 3069 sqlite3_stmt *pExplain; 3070 char *zEQP; 3071 int triggerEQP = 0; 3072 disable_debug_trace_modes(); 3073 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); 3074 if( pArg->autoEQP>=AUTOEQP_trigger ){ 3075 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0); 3076 } 3077 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); 3078 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3079 if( rc==SQLITE_OK ){ 3080 while( sqlite3_step(pExplain)==SQLITE_ROW ){ 3081 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3); 3082 int iEqpId = sqlite3_column_int(pExplain, 0); 3083 int iParentId = sqlite3_column_int(pExplain, 1); 3084 if( zEQPLine[0]=='-' ) eqp_render(pArg); 3085 eqp_append(pArg, iEqpId, iParentId, zEQPLine); 3086 } 3087 eqp_render(pArg); 3088 } 3089 sqlite3_finalize(pExplain); 3090 sqlite3_free(zEQP); 3091 if( pArg->autoEQP>=AUTOEQP_full ){ 3092 /* Also do an EXPLAIN for ".eqp full" mode */ 3093 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); 3094 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3095 if( rc==SQLITE_OK ){ 3096 pArg->cMode = MODE_Explain; 3097 explain_data_prepare(pArg, pExplain); 3098 exec_prepared_stmt(pArg, pExplain); 3099 explain_data_delete(pArg); 3100 } 3101 sqlite3_finalize(pExplain); 3102 sqlite3_free(zEQP); 3103 } 3104 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ 3105 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0); 3106 /* Reprepare pStmt before reactiving trace modes */ 3107 sqlite3_finalize(pStmt); 3108 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 3109 if( pArg ) pArg->pStmt = pStmt; 3110 } 3111 restore_debug_trace_modes(); 3112 } 3113 3114 if( pArg ){ 3115 pArg->cMode = pArg->mode; 3116 if( pArg->autoExplain ){ 3117 if( sqlite3_stmt_isexplain(pStmt)==1 ){ 3118 pArg->cMode = MODE_Explain; 3119 } 3120 if( sqlite3_stmt_isexplain(pStmt)==2 ){ 3121 pArg->cMode = MODE_EQP; 3122 } 3123 } 3124 3125 /* If the shell is currently in ".explain" mode, gather the extra 3126 ** data required to add indents to the output.*/ 3127 if( pArg->cMode==MODE_Explain ){ 3128 explain_data_prepare(pArg, pStmt); 3129 } 3130 } 3131 3132 bind_prepared_stmt(pArg, pStmt); 3133 exec_prepared_stmt(pArg, pStmt); 3134 explain_data_delete(pArg); 3135 eqp_render(pArg); 3136 3137 /* print usage stats if stats on */ 3138 if( pArg && pArg->statsOn ){ 3139 display_stats(db, pArg, 0); 3140 } 3141 3142 /* print loop-counters if required */ 3143 if( pArg && pArg->scanstatsOn ){ 3144 display_scanstats(db, pArg); 3145 } 3146 3147 /* Finalize the statement just executed. If this fails, save a 3148 ** copy of the error message. Otherwise, set zSql to point to the 3149 ** next statement to execute. */ 3150 rc2 = sqlite3_finalize(pStmt); 3151 if( rc!=SQLITE_NOMEM ) rc = rc2; 3152 if( rc==SQLITE_OK ){ 3153 zSql = zLeftover; 3154 while( IsSpace(zSql[0]) ) zSql++; 3155 }else if( pzErrMsg ){ 3156 *pzErrMsg = save_err_msg(db); 3157 } 3158 3159 /* clear saved stmt handle */ 3160 if( pArg ){ 3161 pArg->pStmt = NULL; 3162 } 3163 } 3164 } /* end while */ 3165 3166 return rc; 3167} 3168 3169/* 3170** Release memory previously allocated by tableColumnList(). 3171*/ 3172static void freeColumnList(char **azCol){ 3173 int i; 3174 for(i=1; azCol[i]; i++){ 3175 sqlite3_free(azCol[i]); 3176 } 3177 /* azCol[0] is a static string */ 3178 sqlite3_free(azCol); 3179} 3180 3181/* 3182** Return a list of pointers to strings which are the names of all 3183** columns in table zTab. The memory to hold the names is dynamically 3184** allocated and must be released by the caller using a subsequent call 3185** to freeColumnList(). 3186** 3187** The azCol[0] entry is usually NULL. However, if zTab contains a rowid 3188** value that needs to be preserved, then azCol[0] is filled in with the 3189** name of the rowid column. 3190** 3191** The first regular column in the table is azCol[1]. The list is terminated 3192** by an entry with azCol[i]==0. 3193*/ 3194static char **tableColumnList(ShellState *p, const char *zTab){ 3195 char **azCol = 0; 3196 sqlite3_stmt *pStmt; 3197 char *zSql; 3198 int nCol = 0; 3199 int nAlloc = 0; 3200 int nPK = 0; /* Number of PRIMARY KEY columns seen */ 3201 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ 3202 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); 3203 int rc; 3204 3205 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); 3206 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3207 sqlite3_free(zSql); 3208 if( rc ) return 0; 3209 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 3210 if( nCol>=nAlloc-2 ){ 3211 nAlloc = nAlloc*2 + nCol + 10; 3212 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); 3213 if( azCol==0 ) shell_out_of_memory(); 3214 } 3215 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); 3216 if( sqlite3_column_int(pStmt, 5) ){ 3217 nPK++; 3218 if( nPK==1 3219 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), 3220 "INTEGER")==0 3221 ){ 3222 isIPK = 1; 3223 }else{ 3224 isIPK = 0; 3225 } 3226 } 3227 } 3228 sqlite3_finalize(pStmt); 3229 if( azCol==0 ) return 0; 3230 azCol[0] = 0; 3231 azCol[nCol+1] = 0; 3232 3233 /* The decision of whether or not a rowid really needs to be preserved 3234 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table 3235 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve 3236 ** rowids on tables where the rowid is inaccessible because there are other 3237 ** columns in the table named "rowid", "_rowid_", and "oid". 3238 */ 3239 if( preserveRowid && isIPK ){ 3240 /* If a single PRIMARY KEY column with type INTEGER was seen, then it 3241 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID 3242 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are 3243 ** ROWID aliases. To distinguish these cases, check to see if 3244 ** there is a "pk" entry in "PRAGMA index_list". There will be 3245 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. 3246 */ 3247 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" 3248 " WHERE origin='pk'", zTab); 3249 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3250 sqlite3_free(zSql); 3251 if( rc ){ 3252 freeColumnList(azCol); 3253 return 0; 3254 } 3255 rc = sqlite3_step(pStmt); 3256 sqlite3_finalize(pStmt); 3257 preserveRowid = rc==SQLITE_ROW; 3258 } 3259 if( preserveRowid ){ 3260 /* Only preserve the rowid if we can find a name to use for the 3261 ** rowid */ 3262 static char *azRowid[] = { "rowid", "_rowid_", "oid" }; 3263 int i, j; 3264 for(j=0; j<3; j++){ 3265 for(i=1; i<=nCol; i++){ 3266 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; 3267 } 3268 if( i>nCol ){ 3269 /* At this point, we know that azRowid[j] is not the name of any 3270 ** ordinary column in the table. Verify that azRowid[j] is a valid 3271 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID 3272 ** tables will fail this last check */ 3273 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); 3274 if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; 3275 break; 3276 } 3277 } 3278 } 3279 return azCol; 3280} 3281 3282/* 3283** Toggle the reverse_unordered_selects setting. 3284*/ 3285static void toggleSelectOrder(sqlite3 *db){ 3286 sqlite3_stmt *pStmt = 0; 3287 int iSetting = 0; 3288 char zStmt[100]; 3289 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); 3290 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 3291 iSetting = sqlite3_column_int(pStmt, 0); 3292 } 3293 sqlite3_finalize(pStmt); 3294 sqlite3_snprintf(sizeof(zStmt), zStmt, 3295 "PRAGMA reverse_unordered_selects(%d)", !iSetting); 3296 sqlite3_exec(db, zStmt, 0, 0, 0); 3297} 3298 3299/* 3300** This is a different callback routine used for dumping the database. 3301** Each row received by this callback consists of a table name, 3302** the table type ("index" or "table") and SQL to create the table. 3303** This routine should print text sufficient to recreate the table. 3304*/ 3305static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ 3306 int rc; 3307 const char *zTable; 3308 const char *zType; 3309 const char *zSql; 3310 ShellState *p = (ShellState *)pArg; 3311 3312 UNUSED_PARAMETER(azNotUsed); 3313 if( nArg!=3 || azArg==0 ) return 0; 3314 zTable = azArg[0]; 3315 zType = azArg[1]; 3316 zSql = azArg[2]; 3317 3318 if( strcmp(zTable, "sqlite_sequence")==0 ){ 3319 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n"); 3320 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ 3321 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 3322 }else if( strncmp(zTable, "sqlite_", 7)==0 ){ 3323 return 0; 3324 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ 3325 char *zIns; 3326 if( !p->writableSchema ){ 3327 raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); 3328 p->writableSchema = 1; 3329 } 3330 zIns = sqlite3_mprintf( 3331 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" 3332 "VALUES('table','%q','%q',0,'%q');", 3333 zTable, zTable, zSql); 3334 utf8_printf(p->out, "%s\n", zIns); 3335 sqlite3_free(zIns); 3336 return 0; 3337 }else{ 3338 printSchemaLine(p->out, zSql, ";\n"); 3339 } 3340 3341 if( strcmp(zType, "table")==0 ){ 3342 ShellText sSelect; 3343 ShellText sTable; 3344 char **azCol; 3345 int i; 3346 char *savedDestTable; 3347 int savedMode; 3348 3349 azCol = tableColumnList(p, zTable); 3350 if( azCol==0 ){ 3351 p->nErr++; 3352 return 0; 3353 } 3354 3355 /* Always quote the table name, even if it appears to be pure ascii, 3356 ** in case it is a keyword. Ex: INSERT INTO "table" ... */ 3357 initText(&sTable); 3358 appendText(&sTable, zTable, quoteChar(zTable)); 3359 /* If preserving the rowid, add a column list after the table name. 3360 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" 3361 ** instead of the usual "INSERT INTO tab VALUES(...)". 3362 */ 3363 if( azCol[0] ){ 3364 appendText(&sTable, "(", 0); 3365 appendText(&sTable, azCol[0], 0); 3366 for(i=1; azCol[i]; i++){ 3367 appendText(&sTable, ",", 0); 3368 appendText(&sTable, azCol[i], quoteChar(azCol[i])); 3369 } 3370 appendText(&sTable, ")", 0); 3371 } 3372 3373 /* Build an appropriate SELECT statement */ 3374 initText(&sSelect); 3375 appendText(&sSelect, "SELECT ", 0); 3376 if( azCol[0] ){ 3377 appendText(&sSelect, azCol[0], 0); 3378 appendText(&sSelect, ",", 0); 3379 } 3380 for(i=1; azCol[i]; i++){ 3381 appendText(&sSelect, azCol[i], quoteChar(azCol[i])); 3382 if( azCol[i+1] ){ 3383 appendText(&sSelect, ",", 0); 3384 } 3385 } 3386 freeColumnList(azCol); 3387 appendText(&sSelect, " FROM ", 0); 3388 appendText(&sSelect, zTable, quoteChar(zTable)); 3389 3390 savedDestTable = p->zDestTable; 3391 savedMode = p->mode; 3392 p->zDestTable = sTable.z; 3393 p->mode = p->cMode = MODE_Insert; 3394 rc = shell_exec(p, sSelect.z, 0); 3395 if( (rc&0xff)==SQLITE_CORRUPT ){ 3396 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3397 toggleSelectOrder(p->db); 3398 shell_exec(p, sSelect.z, 0); 3399 toggleSelectOrder(p->db); 3400 } 3401 p->zDestTable = savedDestTable; 3402 p->mode = savedMode; 3403 freeText(&sTable); 3404 freeText(&sSelect); 3405 if( rc ) p->nErr++; 3406 } 3407 return 0; 3408} 3409 3410/* 3411** Run zQuery. Use dump_callback() as the callback routine so that 3412** the contents of the query are output as SQL statements. 3413** 3414** If we get a SQLITE_CORRUPT error, rerun the query after appending 3415** "ORDER BY rowid DESC" to the end. 3416*/ 3417static int run_schema_dump_query( 3418 ShellState *p, 3419 const char *zQuery 3420){ 3421 int rc; 3422 char *zErr = 0; 3423 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); 3424 if( rc==SQLITE_CORRUPT ){ 3425 char *zQ2; 3426 int len = strlen30(zQuery); 3427 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3428 if( zErr ){ 3429 utf8_printf(p->out, "/****** %s ******/\n", zErr); 3430 sqlite3_free(zErr); 3431 zErr = 0; 3432 } 3433 zQ2 = malloc( len+100 ); 3434 if( zQ2==0 ) return rc; 3435 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); 3436 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); 3437 if( rc ){ 3438 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); 3439 }else{ 3440 rc = SQLITE_CORRUPT; 3441 } 3442 sqlite3_free(zErr); 3443 free(zQ2); 3444 } 3445 return rc; 3446} 3447 3448/* 3449** Text of help messages. 3450** 3451** The help text for each individual command begins with a line that starts 3452** with ".". Subsequent lines are supplimental information. 3453** 3454** There must be two or more spaces between the end of the command and the 3455** start of the description of what that command does. 3456*/ 3457static const char *(azHelp[]) = { 3458#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 3459 ".archive ... Manage SQL archives", 3460 " Each command must have exactly one of the following options:", 3461 " -c, --create Create a new archive", 3462 " -u, --update Add files or update files with changed mtime", 3463 " -i, --insert Like -u but always add even if mtime unchanged", 3464 " -t, --list List contents of archive", 3465 " -x, --extract Extract files from archive", 3466 " Optional arguments:", 3467 " -v, --verbose Print each filename as it is processed", 3468 " -f FILE, --file FILE Operate on archive FILE (default is current db)", 3469 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS", 3470 " -C DIR, --directory DIR Change to directory DIR to read/extract files", 3471 " -n, --dryrun Show the SQL that would have occurred", 3472 " Examples:", 3473 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar", 3474 " .ar -tf archive.sar # List members of archive.sar", 3475 " .ar -xvf archive.sar # Verbosely extract files from archive.sar", 3476 " See also:", 3477 " http://sqlite.org/cli.html#sqlar_archive_support", 3478#endif 3479#ifndef SQLITE_OMIT_AUTHORIZATION 3480 ".auth ON|OFF Show authorizer callbacks", 3481#endif 3482 ".backup ?DB? FILE Backup DB (default \"main\") to FILE", 3483 " --append Use the appendvfs", 3484 " --async Write to FILE without a journal and without fsync()", 3485 ".bail on|off Stop after hitting an error. Default OFF", 3486 ".binary on|off Turn binary output on or off. Default OFF", 3487 ".cd DIRECTORY Change the working directory to DIRECTORY", 3488 ".changes on|off Show number of rows changed by SQL", 3489 ".check GLOB Fail if output since .testcase does not match", 3490 ".clone NEWDB Clone data into NEWDB from the existing database", 3491 ".databases List names and files of attached databases", 3492 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options", 3493 ".dbinfo ?DB? Show status information about the database", 3494 ".dump ?TABLE? ... Render all database content as SQL", 3495 " Options:", 3496 " --preserve-rowids Include ROWID values in the output", 3497 " --newlines Allow unescaped newline characters in output", 3498 " TABLE is a LIKE pattern for the tables to dump", 3499 ".echo on|off Turn command echo on or off", 3500 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN", 3501 " Other Modes:", 3502#ifdef SQLITE_DEBUG 3503 " test Show raw EXPLAIN QUERY PLAN output", 3504 " trace Like \"full\" but also enable \"PRAGMA vdbe_trace\"", 3505#endif 3506 " trigger Like \"full\" but also show trigger bytecode", 3507 ".excel Display the output of next command in a spreadsheet", 3508 ".exit ?CODE? Exit this program with return-code CODE", 3509 ".expert EXPERIMENTAL. Suggest indexes for specified queries", 3510/* Because explain mode comes on automatically now, the ".explain" mode 3511** is removed from the help screen. It is still supported for legacy, however */ 3512/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/ 3513 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", 3514 ".headers on|off Turn display of headers on or off", 3515 ".help ?-all? ?PATTERN? Show help text for PATTERN", 3516 ".import FILE TABLE Import data from FILE into TABLE", 3517#ifndef SQLITE_OMIT_TEST_CONTROL 3518 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", 3519#endif 3520 ".indexes ?TABLE? Show names of indexes", 3521 " If TABLE is specified, only show indexes for", 3522 " tables matching TABLE using the LIKE operator.", 3523#ifdef SQLITE_ENABLE_IOTRACE 3524 ".iotrace FILE Enable I/O diagnostic logging to FILE", 3525#endif 3526 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", 3527 ".lint OPTIONS Report potential schema issues.", 3528 " Options:", 3529 " fkey-indexes Find missing foreign key indexes", 3530#ifndef SQLITE_OMIT_LOAD_EXTENSION 3531 ".load FILE ?ENTRY? Load an extension library", 3532#endif 3533 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout", 3534 ".mode MODE ?TABLE? Set output mode", 3535 " MODE is one of:", 3536 " ascii Columns/rows delimited by 0x1F and 0x1E", 3537 " csv Comma-separated values", 3538 " column Left-aligned columns. (See .width)", 3539 " html HTML <table> code", 3540 " insert SQL insert statements for TABLE", 3541 " line One value per line", 3542 " list Values delimited by \"|\"", 3543 " quote Escape answers as for SQL", 3544 " tabs Tab-separated values", 3545 " tcl TCL list elements", 3546 ".nullvalue STRING Use STRING in place of NULL values", 3547 ".once (-e|-x|FILE) Output for the next SQL command only to FILE", 3548 " If FILE begins with '|' then open as a pipe", 3549 " Other options:", 3550 " -e Invoke system text editor", 3551 " -x Open in a spreadsheet", 3552 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", 3553 " Options:", 3554 " --append Use appendvfs to append database to the end of FILE", 3555#ifdef SQLITE_ENABLE_DESERIALIZE 3556 " --deserialize Load into memory useing sqlite3_deserialize()", 3557 " --hexdb Load the output of \"dbtotxt\" as an in-memory database", 3558 " --maxsize N Maximum size for --hexdb or --deserialized database", 3559#endif 3560 " --new Initialize FILE to an empty database", 3561 " --readonly Open FILE readonly", 3562 " --zip FILE is a ZIP archive", 3563 ".output ?FILE? Send output to FILE or stdout if FILE is omitted", 3564 " If FILE begins with '|' then open it as a pipe.", 3565 ".parameter CMD ... Manage SQL parameter bindings", 3566 " clear Erase all bindings", 3567 " init Initialize the TEMP table that holds bindings", 3568 " list List the current parameter bindings", 3569 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", 3570 " PARAMETER should start with '$', ':', '@', or '?'", 3571 " unset PARAMETER Remove PARAMETER from the binding table", 3572 ".print STRING... Print literal STRING", 3573#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 3574 ".progress N Invoke progress handler after every N opcodes", 3575 " --limit N Interrupt after N progress callbacks", 3576 " --once Do no more than one progress interrupt", 3577 " --quiet|-q No output except at interrupts", 3578 " --reset Reset the count for each input and interrupt", 3579#endif 3580 ".prompt MAIN CONTINUE Replace the standard prompts", 3581 ".quit Exit this program", 3582 ".read FILE Read input from FILE", 3583#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 3584 ".recover Recover as much data as possible from corrupt db.", 3585#endif 3586 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", 3587 ".save FILE Write in-memory database into FILE", 3588 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off", 3589 ".schema ?PATTERN? Show the CREATE statements matching PATTERN", 3590 " Options:", 3591 " --indent Try to pretty-print the schema", 3592 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table", 3593 " Options:", 3594 " --init Create a new SELFTEST table", 3595 " -v Verbose output", 3596 ".separator COL ?ROW? Change the column and row separators", 3597#if defined(SQLITE_ENABLE_SESSION) 3598 ".session ?NAME? CMD ... Create or control sessions", 3599 " Subcommands:", 3600 " attach TABLE Attach TABLE", 3601 " changeset FILE Write a changeset into FILE", 3602 " close Close one session", 3603 " enable ?BOOLEAN? Set or query the enable bit", 3604 " filter GLOB... Reject tables matching GLOBs", 3605 " indirect ?BOOLEAN? Mark or query the indirect status", 3606 " isempty Query whether the session is empty", 3607 " list List currently open session names", 3608 " open DB NAME Open a new session on DB", 3609 " patchset FILE Write a patchset into FILE", 3610 " If ?NAME? is omitted, the first defined session is used.", 3611#endif 3612 ".sha3sum ... Compute a SHA3 hash of database content", 3613 " Options:", 3614 " --schema Also hash the sqlite_master table", 3615 " --sha3-224 Use the sha3-224 algorithm", 3616 " --sha3-256 Use the sha3-256 algorithm. This is the default.", 3617 " --sha3-384 Use the sha3-384 algorithm", 3618 " --sha3-512 Use the sha3-512 algorithm", 3619 " Any other argument is a LIKE pattern for tables to hash", 3620#ifndef SQLITE_NOHAVE_SYSTEM 3621 ".shell CMD ARGS... Run CMD ARGS... in a system shell", 3622#endif 3623 ".show Show the current values for various settings", 3624 ".stats ?on|off? Show stats or turn stats on or off", 3625#ifndef SQLITE_NOHAVE_SYSTEM 3626 ".system CMD ARGS... Run CMD ARGS... in a system shell", 3627#endif 3628 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", 3629 ".testcase NAME Begin redirecting output to 'testcase-out.txt'", 3630 ".timeout MS Try opening locked tables for MS milliseconds", 3631 ".timer on|off Turn SQL timer on or off", 3632#ifndef SQLITE_OMIT_TRACE 3633 ".trace ?OPTIONS? Output each SQL statement as it is run", 3634 " FILE Send output to FILE", 3635 " stdout Send output to stdout", 3636 " stderr Send output to stderr", 3637 " off Disable tracing", 3638 " --expanded Expand query parameters", 3639#ifdef SQLITE_ENABLE_NORMALIZE 3640 " --normalized Normal the SQL statements", 3641#endif 3642 " --plain Show SQL as it is input", 3643 " --stmt Trace statement execution (SQLITE_TRACE_STMT)", 3644 " --profile Profile statements (SQLITE_TRACE_PROFILE)", 3645 " --row Trace each row (SQLITE_TRACE_ROW)", 3646 " --close Trace connection close (SQLITE_TRACE_CLOSE)", 3647#endif /* SQLITE_OMIT_TRACE */ 3648 ".vfsinfo ?AUX? Information about the top-level VFS", 3649 ".vfslist List all available VFSes", 3650 ".vfsname ?AUX? Print the name of the VFS stack", 3651 ".width NUM1 NUM2 ... Set column widths for \"column\" mode", 3652 " Negative values right-justify", 3653}; 3654 3655/* 3656** Output help text. 3657** 3658** zPattern describes the set of commands for which help text is provided. 3659** If zPattern is NULL, then show all commands, but only give a one-line 3660** description of each. 3661** 3662** Return the number of matches. 3663*/ 3664static int showHelp(FILE *out, const char *zPattern){ 3665 int i = 0; 3666 int j = 0; 3667 int n = 0; 3668 char *zPat; 3669 if( zPattern==0 3670 || zPattern[0]=='0' 3671 || strcmp(zPattern,"-a")==0 3672 || strcmp(zPattern,"-all")==0 3673 ){ 3674 /* Show all commands, but only one line per command */ 3675 if( zPattern==0 ) zPattern = ""; 3676 for(i=0; i<ArraySize(azHelp); i++){ 3677 if( azHelp[i][0]=='.' || zPattern[0] ){ 3678 utf8_printf(out, "%s\n", azHelp[i]); 3679 n++; 3680 } 3681 } 3682 }else{ 3683 /* Look for commands that for which zPattern is an exact prefix */ 3684 zPat = sqlite3_mprintf(".%s*", zPattern); 3685 for(i=0; i<ArraySize(azHelp); i++){ 3686 if( sqlite3_strglob(zPat, azHelp[i])==0 ){ 3687 utf8_printf(out, "%s\n", azHelp[i]); 3688 j = i+1; 3689 n++; 3690 } 3691 } 3692 sqlite3_free(zPat); 3693 if( n ){ 3694 if( n==1 ){ 3695 /* when zPattern is a prefix of exactly one command, then include the 3696 ** details of that command, which should begin at offset j */ 3697 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){ 3698 utf8_printf(out, "%s\n", azHelp[j]); 3699 j++; 3700 } 3701 } 3702 return n; 3703 } 3704 /* Look for commands that contain zPattern anywhere. Show the complete 3705 ** text of all commands that match. */ 3706 zPat = sqlite3_mprintf("%%%s%%", zPattern); 3707 for(i=0; i<ArraySize(azHelp); i++){ 3708 if( azHelp[i][0]=='.' ) j = i; 3709 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){ 3710 utf8_printf(out, "%s\n", azHelp[j]); 3711 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){ 3712 j++; 3713 utf8_printf(out, "%s\n", azHelp[j]); 3714 } 3715 i = j; 3716 n++; 3717 } 3718 } 3719 sqlite3_free(zPat); 3720 } 3721 return n; 3722} 3723 3724/* Forward reference */ 3725static int process_input(ShellState *p); 3726 3727/* 3728** Read the content of file zName into memory obtained from sqlite3_malloc64() 3729** and return a pointer to the buffer. The caller is responsible for freeing 3730** the memory. 3731** 3732** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes 3733** read. 3734** 3735** For convenience, a nul-terminator byte is always appended to the data read 3736** from the file before the buffer is returned. This byte is not included in 3737** the final value of (*pnByte), if applicable. 3738** 3739** NULL is returned if any error is encountered. The final value of *pnByte 3740** is undefined in this case. 3741*/ 3742static char *readFile(const char *zName, int *pnByte){ 3743 FILE *in = fopen(zName, "rb"); 3744 long nIn; 3745 size_t nRead; 3746 char *pBuf; 3747 if( in==0 ) return 0; 3748 fseek(in, 0, SEEK_END); 3749 nIn = ftell(in); 3750 rewind(in); 3751 pBuf = sqlite3_malloc64( nIn+1 ); 3752 if( pBuf==0 ){ fclose(in); return 0; } 3753 nRead = fread(pBuf, nIn, 1, in); 3754 fclose(in); 3755 if( nRead!=1 ){ 3756 sqlite3_free(pBuf); 3757 return 0; 3758 } 3759 pBuf[nIn] = 0; 3760 if( pnByte ) *pnByte = nIn; 3761 return pBuf; 3762} 3763 3764#if defined(SQLITE_ENABLE_SESSION) 3765/* 3766** Close a single OpenSession object and release all of its associated 3767** resources. 3768*/ 3769static void session_close(OpenSession *pSession){ 3770 int i; 3771 sqlite3session_delete(pSession->p); 3772 sqlite3_free(pSession->zName); 3773 for(i=0; i<pSession->nFilter; i++){ 3774 sqlite3_free(pSession->azFilter[i]); 3775 } 3776 sqlite3_free(pSession->azFilter); 3777 memset(pSession, 0, sizeof(OpenSession)); 3778} 3779#endif 3780 3781/* 3782** Close all OpenSession objects and release all associated resources. 3783*/ 3784#if defined(SQLITE_ENABLE_SESSION) 3785static void session_close_all(ShellState *p){ 3786 int i; 3787 for(i=0; i<p->nSession; i++){ 3788 session_close(&p->aSession[i]); 3789 } 3790 p->nSession = 0; 3791} 3792#else 3793# define session_close_all(X) 3794#endif 3795 3796/* 3797** Implementation of the xFilter function for an open session. Omit 3798** any tables named by ".session filter" but let all other table through. 3799*/ 3800#if defined(SQLITE_ENABLE_SESSION) 3801static int session_filter(void *pCtx, const char *zTab){ 3802 OpenSession *pSession = (OpenSession*)pCtx; 3803 int i; 3804 for(i=0; i<pSession->nFilter; i++){ 3805 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; 3806 } 3807 return 1; 3808} 3809#endif 3810 3811/* 3812** Try to deduce the type of file for zName based on its content. Return 3813** one of the SHELL_OPEN_* constants. 3814** 3815** If the file does not exist or is empty but its name looks like a ZIP 3816** archive and the dfltZip flag is true, then assume it is a ZIP archive. 3817** Otherwise, assume an ordinary database regardless of the filename if 3818** the type cannot be determined from content. 3819*/ 3820int deduceDatabaseType(const char *zName, int dfltZip){ 3821 FILE *f = fopen(zName, "rb"); 3822 size_t n; 3823 int rc = SHELL_OPEN_UNSPEC; 3824 char zBuf[100]; 3825 if( f==0 ){ 3826 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 3827 return SHELL_OPEN_ZIPFILE; 3828 }else{ 3829 return SHELL_OPEN_NORMAL; 3830 } 3831 } 3832 n = fread(zBuf, 16, 1, f); 3833 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ 3834 fclose(f); 3835 return SHELL_OPEN_NORMAL; 3836 } 3837 fseek(f, -25, SEEK_END); 3838 n = fread(zBuf, 25, 1, f); 3839 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ 3840 rc = SHELL_OPEN_APPENDVFS; 3841 }else{ 3842 fseek(f, -22, SEEK_END); 3843 n = fread(zBuf, 22, 1, f); 3844 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 3845 && zBuf[3]==0x06 ){ 3846 rc = SHELL_OPEN_ZIPFILE; 3847 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 3848 rc = SHELL_OPEN_ZIPFILE; 3849 } 3850 } 3851 fclose(f); 3852 return rc; 3853} 3854 3855#ifdef SQLITE_ENABLE_DESERIALIZE 3856/* 3857** Reconstruct an in-memory database using the output from the "dbtotxt" 3858** program. Read content from the file in p->zDbFilename. If p->zDbFilename 3859** is 0, then read from standard input. 3860*/ 3861static unsigned char *readHexDb(ShellState *p, int *pnData){ 3862 unsigned char *a = 0; 3863 int nLine; 3864 int n = 0; 3865 int pgsz = 0; 3866 int iOffset = 0; 3867 int j, k; 3868 int rc; 3869 FILE *in; 3870 unsigned int x[16]; 3871 char zLine[1000]; 3872 if( p->zDbFilename ){ 3873 in = fopen(p->zDbFilename, "r"); 3874 if( in==0 ){ 3875 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename); 3876 return 0; 3877 } 3878 nLine = 0; 3879 }else{ 3880 in = p->in; 3881 nLine = p->lineno; 3882 if( in==0 ) in = stdin; 3883 } 3884 *pnData = 0; 3885 nLine++; 3886 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; 3887 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); 3888 if( rc!=2 ) goto readHexDb_error; 3889 if( n<0 ) goto readHexDb_error; 3890 a = sqlite3_malloc( n ? n : 1 ); 3891 if( a==0 ){ 3892 utf8_printf(stderr, "Out of memory!\n"); 3893 goto readHexDb_error; 3894 } 3895 memset(a, 0, n); 3896 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ 3897 utf8_printf(stderr, "invalid pagesize\n"); 3898 goto readHexDb_error; 3899 } 3900 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){ 3901 rc = sscanf(zLine, "| page %d offset %d", &j, &k); 3902 if( rc==2 ){ 3903 iOffset = k; 3904 continue; 3905 } 3906 if( strncmp(zLine, "| end ", 6)==0 ){ 3907 break; 3908 } 3909 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x", 3910 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], 3911 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); 3912 if( rc==17 ){ 3913 k = iOffset+j; 3914 if( k+16<=n ){ 3915 int ii; 3916 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff; 3917 } 3918 } 3919 } 3920 *pnData = n; 3921 if( in!=p->in ){ 3922 fclose(in); 3923 }else{ 3924 p->lineno = nLine; 3925 } 3926 return a; 3927 3928readHexDb_error: 3929 if( in!=p->in ){ 3930 fclose(in); 3931 }else{ 3932 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ 3933 nLine++; 3934 if(strncmp(zLine, "| end ", 6)==0 ) break; 3935 } 3936 p->lineno = nLine; 3937 } 3938 sqlite3_free(a); 3939 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine); 3940 return 0; 3941} 3942#endif /* SQLITE_ENABLE_DESERIALIZE */ 3943 3944/* 3945** Scalar function "shell_int32". The first argument to this function 3946** must be a blob. The second a non-negative integer. This function 3947** reads and returns a 32-bit big-endian integer from byte 3948** offset (4*<arg2>) of the blob. 3949*/ 3950static void shellInt32( 3951 sqlite3_context *context, 3952 int argc, 3953 sqlite3_value **argv 3954){ 3955 const unsigned char *pBlob; 3956 int nBlob; 3957 int iInt; 3958 3959 UNUSED_PARAMETER(argc); 3960 nBlob = sqlite3_value_bytes(argv[0]); 3961 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); 3962 iInt = sqlite3_value_int(argv[1]); 3963 3964 if( iInt>=0 && (iInt+1)*4<=nBlob ){ 3965 const unsigned char *a = &pBlob[iInt*4]; 3966 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24) 3967 + ((sqlite3_int64)a[1]<<16) 3968 + ((sqlite3_int64)a[2]<< 8) 3969 + ((sqlite3_int64)a[3]<< 0); 3970 sqlite3_result_int64(context, iVal); 3971 } 3972} 3973 3974/* 3975** Scalar function "shell_escape_crnl" used by the .recover command. 3976** The argument passed to this function is the output of built-in 3977** function quote(). If the first character of the input is "'", 3978** indicating that the value passed to quote() was a text value, 3979** then this function searches the input for "\n" and "\r" characters 3980** and adds a wrapper similar to the following: 3981** 3982** replace(replace(<input>, '\n', char(10), '\r', char(13)); 3983** 3984** Or, if the first character of the input is not "'", then a copy 3985** of the input is returned. 3986*/ 3987static void shellEscapeCrnl( 3988 sqlite3_context *context, 3989 int argc, 3990 sqlite3_value **argv 3991){ 3992 const char *zText = (const char*)sqlite3_value_text(argv[0]); 3993 UNUSED_PARAMETER(argc); 3994 if( zText[0]=='\'' ){ 3995 int nText = sqlite3_value_bytes(argv[0]); 3996 int i; 3997 char zBuf1[20]; 3998 char zBuf2[20]; 3999 const char *zNL = 0; 4000 const char *zCR = 0; 4001 int nCR = 0; 4002 int nNL = 0; 4003 4004 for(i=0; zText[i]; i++){ 4005 if( zNL==0 && zText[i]=='\n' ){ 4006 zNL = unused_string(zText, "\\n", "\\012", zBuf1); 4007 nNL = (int)strlen(zNL); 4008 } 4009 if( zCR==0 && zText[i]=='\r' ){ 4010 zCR = unused_string(zText, "\\r", "\\015", zBuf2); 4011 nCR = (int)strlen(zCR); 4012 } 4013 } 4014 4015 if( zNL || zCR ){ 4016 int iOut = 0; 4017 i64 nMax = (nNL > nCR) ? nNL : nCR; 4018 i64 nAlloc = nMax * nText + (nMax+64)*2; 4019 char *zOut = (char*)sqlite3_malloc64(nAlloc); 4020 if( zOut==0 ){ 4021 sqlite3_result_error_nomem(context); 4022 return; 4023 } 4024 4025 if( zNL && zCR ){ 4026 memcpy(&zOut[iOut], "replace(replace(", 16); 4027 iOut += 16; 4028 }else{ 4029 memcpy(&zOut[iOut], "replace(", 8); 4030 iOut += 8; 4031 } 4032 for(i=0; zText[i]; i++){ 4033 if( zText[i]=='\n' ){ 4034 memcpy(&zOut[iOut], zNL, nNL); 4035 iOut += nNL; 4036 }else if( zText[i]=='\r' ){ 4037 memcpy(&zOut[iOut], zCR, nCR); 4038 iOut += nCR; 4039 }else{ 4040 zOut[iOut] = zText[i]; 4041 iOut++; 4042 } 4043 } 4044 4045 if( zNL ){ 4046 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4047 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; 4048 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; 4049 } 4050 if( zCR ){ 4051 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4052 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; 4053 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; 4054 } 4055 4056 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); 4057 sqlite3_free(zOut); 4058 return; 4059 } 4060 } 4061 4062 sqlite3_result_value(context, argv[0]); 4063} 4064 4065/* Flags for open_db(). 4066** 4067** The default behavior of open_db() is to exit(1) if the database fails to 4068** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error 4069** but still returns without calling exit. 4070** 4071** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a 4072** ZIP archive if the file does not exist or is empty and its name matches 4073** the *.zip pattern. 4074*/ 4075#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ 4076#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ 4077 4078/* 4079** Make sure the database is open. If it is not, then open it. If 4080** the database fails to open, print an error message and exit. 4081*/ 4082static void open_db(ShellState *p, int openFlags){ 4083 if( p->db==0 ){ 4084 if( p->openMode==SHELL_OPEN_UNSPEC ){ 4085 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){ 4086 p->openMode = SHELL_OPEN_NORMAL; 4087 }else{ 4088 p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 4089 (openFlags & OPEN_DB_ZIPFILE)!=0); 4090 } 4091 } 4092 switch( p->openMode ){ 4093 case SHELL_OPEN_APPENDVFS: { 4094 sqlite3_open_v2(p->zDbFilename, &p->db, 4095 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs"); 4096 break; 4097 } 4098 case SHELL_OPEN_HEXDB: 4099 case SHELL_OPEN_DESERIALIZE: { 4100 sqlite3_open(0, &p->db); 4101 break; 4102 } 4103 case SHELL_OPEN_ZIPFILE: { 4104 sqlite3_open(":memory:", &p->db); 4105 break; 4106 } 4107 case SHELL_OPEN_READONLY: { 4108 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0); 4109 break; 4110 } 4111 case SHELL_OPEN_UNSPEC: 4112 case SHELL_OPEN_NORMAL: { 4113 sqlite3_open(p->zDbFilename, &p->db); 4114 break; 4115 } 4116 } 4117 globalDb = p->db; 4118 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ 4119 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", 4120 p->zDbFilename, sqlite3_errmsg(p->db)); 4121 if( openFlags & OPEN_DB_KEEPALIVE ){ 4122 sqlite3_open(":memory:", &p->db); 4123 return; 4124 } 4125 exit(1); 4126 } 4127#ifndef SQLITE_OMIT_LOAD_EXTENSION 4128 sqlite3_enable_load_extension(p->db, 1); 4129#endif 4130 sqlite3_fileio_init(p->db, 0, 0); 4131 sqlite3_shathree_init(p->db, 0, 0); 4132 sqlite3_completion_init(p->db, 0, 0); 4133#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 4134 sqlite3_dbdata_init(p->db, 0, 0); 4135#endif 4136#ifdef SQLITE_HAVE_ZLIB 4137 sqlite3_zipfile_init(p->db, 0, 0); 4138 sqlite3_sqlar_init(p->db, 0, 0); 4139#endif 4140 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, 4141 shellAddSchemaName, 0, 0); 4142 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, 4143 shellModuleSchema, 0, 0); 4144 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, 4145 shellPutsFunc, 0, 0); 4146 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0, 4147 shellEscapeCrnl, 0, 0); 4148 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0, 4149 shellInt32, 0, 0); 4150#ifndef SQLITE_NOHAVE_SYSTEM 4151 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, 4152 editFunc, 0, 0); 4153 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, 4154 editFunc, 0, 0); 4155#endif 4156 if( p->openMode==SHELL_OPEN_ZIPFILE ){ 4157 char *zSql = sqlite3_mprintf( 4158 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename); 4159 sqlite3_exec(p->db, zSql, 0, 0, 0); 4160 sqlite3_free(zSql); 4161 } 4162#ifdef SQLITE_ENABLE_DESERIALIZE 4163 else 4164 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ 4165 int rc; 4166 int nData = 0; 4167 unsigned char *aData; 4168 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ 4169 aData = (unsigned char*)readFile(p->zDbFilename, &nData); 4170 }else{ 4171 aData = readHexDb(p, &nData); 4172 if( aData==0 ){ 4173 return; 4174 } 4175 } 4176 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, 4177 SQLITE_DESERIALIZE_RESIZEABLE | 4178 SQLITE_DESERIALIZE_FREEONCLOSE); 4179 if( rc ){ 4180 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc); 4181 } 4182 if( p->szMax>0 ){ 4183 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); 4184 } 4185 } 4186#endif 4187 } 4188} 4189 4190/* 4191** Attempt to close the databaes connection. Report errors. 4192*/ 4193void close_db(sqlite3 *db){ 4194 int rc = sqlite3_close(db); 4195 if( rc ){ 4196 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n", 4197 rc, sqlite3_errmsg(db)); 4198 } 4199} 4200 4201#if HAVE_READLINE || HAVE_EDITLINE 4202/* 4203** Readline completion callbacks 4204*/ 4205static char *readline_completion_generator(const char *text, int state){ 4206 static sqlite3_stmt *pStmt = 0; 4207 char *zRet; 4208 if( state==0 ){ 4209 char *zSql; 4210 sqlite3_finalize(pStmt); 4211 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4212 " FROM completion(%Q) ORDER BY 1", text); 4213 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4214 sqlite3_free(zSql); 4215 } 4216 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 4217 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0)); 4218 }else{ 4219 sqlite3_finalize(pStmt); 4220 pStmt = 0; 4221 zRet = 0; 4222 } 4223 return zRet; 4224} 4225static char **readline_completion(const char *zText, int iStart, int iEnd){ 4226 rl_attempted_completion_over = 1; 4227 return rl_completion_matches(zText, readline_completion_generator); 4228} 4229 4230#elif HAVE_LINENOISE 4231/* 4232** Linenoise completion callback 4233*/ 4234static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ 4235 int nLine = strlen30(zLine); 4236 int i, iStart; 4237 sqlite3_stmt *pStmt = 0; 4238 char *zSql; 4239 char zBuf[1000]; 4240 4241 if( nLine>sizeof(zBuf)-30 ) return; 4242 if( zLine[0]=='.' || zLine[0]=='#') return; 4243 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} 4244 if( i==nLine-1 ) return; 4245 iStart = i+1; 4246 memcpy(zBuf, zLine, iStart); 4247 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4248 " FROM completion(%Q,%Q) ORDER BY 1", 4249 &zLine[iStart], zLine); 4250 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4251 sqlite3_free(zSql); 4252 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ 4253 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 4254 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); 4255 int nCompletion = sqlite3_column_bytes(pStmt, 0); 4256 if( iStart+nCompletion < sizeof(zBuf)-1 ){ 4257 memcpy(zBuf+iStart, zCompletion, nCompletion+1); 4258 linenoiseAddCompletion(lc, zBuf); 4259 } 4260 } 4261 sqlite3_finalize(pStmt); 4262} 4263#endif 4264 4265/* 4266** Do C-language style dequoting. 4267** 4268** \a -> alarm 4269** \b -> backspace 4270** \t -> tab 4271** \n -> newline 4272** \v -> vertical tab 4273** \f -> form feed 4274** \r -> carriage return 4275** \s -> space 4276** \" -> " 4277** \' -> ' 4278** \\ -> backslash 4279** \NNN -> ascii character NNN in octal 4280*/ 4281static void resolve_backslashes(char *z){ 4282 int i, j; 4283 char c; 4284 while( *z && *z!='\\' ) z++; 4285 for(i=j=0; (c = z[i])!=0; i++, j++){ 4286 if( c=='\\' && z[i+1]!=0 ){ 4287 c = z[++i]; 4288 if( c=='a' ){ 4289 c = '\a'; 4290 }else if( c=='b' ){ 4291 c = '\b'; 4292 }else if( c=='t' ){ 4293 c = '\t'; 4294 }else if( c=='n' ){ 4295 c = '\n'; 4296 }else if( c=='v' ){ 4297 c = '\v'; 4298 }else if( c=='f' ){ 4299 c = '\f'; 4300 }else if( c=='r' ){ 4301 c = '\r'; 4302 }else if( c=='"' ){ 4303 c = '"'; 4304 }else if( c=='\'' ){ 4305 c = '\''; 4306 }else if( c=='\\' ){ 4307 c = '\\'; 4308 }else if( c>='0' && c<='7' ){ 4309 c -= '0'; 4310 if( z[i+1]>='0' && z[i+1]<='7' ){ 4311 i++; 4312 c = (c<<3) + z[i] - '0'; 4313 if( z[i+1]>='0' && z[i+1]<='7' ){ 4314 i++; 4315 c = (c<<3) + z[i] - '0'; 4316 } 4317 } 4318 } 4319 } 4320 z[j] = c; 4321 } 4322 if( j<i ) z[j] = 0; 4323} 4324 4325/* 4326** Interpret zArg as either an integer or a boolean value. Return 1 or 0 4327** for TRUE and FALSE. Return the integer value if appropriate. 4328*/ 4329static int booleanValue(const char *zArg){ 4330 int i; 4331 if( zArg[0]=='0' && zArg[1]=='x' ){ 4332 for(i=2; hexDigitValue(zArg[i])>=0; i++){} 4333 }else{ 4334 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} 4335 } 4336 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); 4337 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ 4338 return 1; 4339 } 4340 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ 4341 return 0; 4342 } 4343 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", 4344 zArg); 4345 return 0; 4346} 4347 4348/* 4349** Set or clear a shell flag according to a boolean value. 4350*/ 4351static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ 4352 if( booleanValue(zArg) ){ 4353 ShellSetFlag(p, mFlag); 4354 }else{ 4355 ShellClearFlag(p, mFlag); 4356 } 4357} 4358 4359/* 4360** Close an output file, assuming it is not stderr or stdout 4361*/ 4362static void output_file_close(FILE *f){ 4363 if( f && f!=stdout && f!=stderr ) fclose(f); 4364} 4365 4366/* 4367** Try to open an output file. The names "stdout" and "stderr" are 4368** recognized and do the right thing. NULL is returned if the output 4369** filename is "off". 4370*/ 4371static FILE *output_file_open(const char *zFile, int bTextMode){ 4372 FILE *f; 4373 if( strcmp(zFile,"stdout")==0 ){ 4374 f = stdout; 4375 }else if( strcmp(zFile, "stderr")==0 ){ 4376 f = stderr; 4377 }else if( strcmp(zFile, "off")==0 ){ 4378 f = 0; 4379 }else{ 4380 f = fopen(zFile, bTextMode ? "w" : "wb"); 4381 if( f==0 ){ 4382 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 4383 } 4384 } 4385 return f; 4386} 4387 4388#ifndef SQLITE_OMIT_TRACE 4389/* 4390** A routine for handling output from sqlite3_trace(). 4391*/ 4392static int sql_trace_callback( 4393 unsigned mType, /* The trace type */ 4394 void *pArg, /* The ShellState pointer */ 4395 void *pP, /* Usually a pointer to sqlite_stmt */ 4396 void *pX /* Auxiliary output */ 4397){ 4398 ShellState *p = (ShellState*)pArg; 4399 sqlite3_stmt *pStmt; 4400 const char *zSql; 4401 int nSql; 4402 if( p->traceOut==0 ) return 0; 4403 if( mType==SQLITE_TRACE_CLOSE ){ 4404 utf8_printf(p->traceOut, "-- closing database connection\n"); 4405 return 0; 4406 } 4407 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){ 4408 zSql = (const char*)pX; 4409 }else{ 4410 pStmt = (sqlite3_stmt*)pP; 4411 switch( p->eTraceType ){ 4412 case SHELL_TRACE_EXPANDED: { 4413 zSql = sqlite3_expanded_sql(pStmt); 4414 break; 4415 } 4416#ifdef SQLITE_ENABLE_NORMALIZE 4417 case SHELL_TRACE_NORMALIZED: { 4418 zSql = sqlite3_normalized_sql(pStmt); 4419 break; 4420 } 4421#endif 4422 default: { 4423 zSql = sqlite3_sql(pStmt); 4424 break; 4425 } 4426 } 4427 } 4428 if( zSql==0 ) return 0; 4429 nSql = strlen30(zSql); 4430 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } 4431 switch( mType ){ 4432 case SQLITE_TRACE_ROW: 4433 case SQLITE_TRACE_STMT: { 4434 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql); 4435 break; 4436 } 4437 case SQLITE_TRACE_PROFILE: { 4438 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX; 4439 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec); 4440 break; 4441 } 4442 } 4443 return 0; 4444} 4445#endif 4446 4447/* 4448** A no-op routine that runs with the ".breakpoint" doc-command. This is 4449** a useful spot to set a debugger breakpoint. 4450*/ 4451static void test_breakpoint(void){ 4452 static int nCall = 0; 4453 nCall++; 4454} 4455 4456/* 4457** An object used to read a CSV and other files for import. 4458*/ 4459typedef struct ImportCtx ImportCtx; 4460struct ImportCtx { 4461 const char *zFile; /* Name of the input file */ 4462 FILE *in; /* Read the CSV text from this input stream */ 4463 char *z; /* Accumulated text for a field */ 4464 int n; /* Number of bytes in z */ 4465 int nAlloc; /* Space allocated for z[] */ 4466 int nLine; /* Current line number */ 4467 int bNotFirst; /* True if one or more bytes already read */ 4468 int cTerm; /* Character that terminated the most recent field */ 4469 int cColSep; /* The column separator character. (Usually ",") */ 4470 int cRowSep; /* The row separator character. (Usually "\n") */ 4471}; 4472 4473/* Append a single byte to z[] */ 4474static void import_append_char(ImportCtx *p, int c){ 4475 if( p->n+1>=p->nAlloc ){ 4476 p->nAlloc += p->nAlloc + 100; 4477 p->z = sqlite3_realloc64(p->z, p->nAlloc); 4478 if( p->z==0 ) shell_out_of_memory(); 4479 } 4480 p->z[p->n++] = (char)c; 4481} 4482 4483/* Read a single field of CSV text. Compatible with rfc4180 and extended 4484** with the option of having a separator other than ",". 4485** 4486** + Input comes from p->in. 4487** + Store results in p->z of length p->n. Space to hold p->z comes 4488** from sqlite3_malloc64(). 4489** + Use p->cSep as the column separator. The default is ",". 4490** + Use p->rSep as the row separator. The default is "\n". 4491** + Keep track of the line number in p->nLine. 4492** + Store the character that terminates the field in p->cTerm. Store 4493** EOF on end-of-file. 4494** + Report syntax errors on stderr 4495*/ 4496static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ 4497 int c; 4498 int cSep = p->cColSep; 4499 int rSep = p->cRowSep; 4500 p->n = 0; 4501 c = fgetc(p->in); 4502 if( c==EOF || seenInterrupt ){ 4503 p->cTerm = EOF; 4504 return 0; 4505 } 4506 if( c=='"' ){ 4507 int pc, ppc; 4508 int startLine = p->nLine; 4509 int cQuote = c; 4510 pc = ppc = 0; 4511 while( 1 ){ 4512 c = fgetc(p->in); 4513 if( c==rSep ) p->nLine++; 4514 if( c==cQuote ){ 4515 if( pc==cQuote ){ 4516 pc = 0; 4517 continue; 4518 } 4519 } 4520 if( (c==cSep && pc==cQuote) 4521 || (c==rSep && pc==cQuote) 4522 || (c==rSep && pc=='\r' && ppc==cQuote) 4523 || (c==EOF && pc==cQuote) 4524 ){ 4525 do{ p->n--; }while( p->z[p->n]!=cQuote ); 4526 p->cTerm = c; 4527 break; 4528 } 4529 if( pc==cQuote && c!='\r' ){ 4530 utf8_printf(stderr, "%s:%d: unescaped %c character\n", 4531 p->zFile, p->nLine, cQuote); 4532 } 4533 if( c==EOF ){ 4534 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", 4535 p->zFile, startLine, cQuote); 4536 p->cTerm = c; 4537 break; 4538 } 4539 import_append_char(p, c); 4540 ppc = pc; 4541 pc = c; 4542 } 4543 }else{ 4544 /* If this is the first field being parsed and it begins with the 4545 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ 4546 if( (c&0xff)==0xef && p->bNotFirst==0 ){ 4547 import_append_char(p, c); 4548 c = fgetc(p->in); 4549 if( (c&0xff)==0xbb ){ 4550 import_append_char(p, c); 4551 c = fgetc(p->in); 4552 if( (c&0xff)==0xbf ){ 4553 p->bNotFirst = 1; 4554 p->n = 0; 4555 return csv_read_one_field(p); 4556 } 4557 } 4558 } 4559 while( c!=EOF && c!=cSep && c!=rSep ){ 4560 import_append_char(p, c); 4561 c = fgetc(p->in); 4562 } 4563 if( c==rSep ){ 4564 p->nLine++; 4565 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; 4566 } 4567 p->cTerm = c; 4568 } 4569 if( p->z ) p->z[p->n] = 0; 4570 p->bNotFirst = 1; 4571 return p->z; 4572} 4573 4574/* Read a single field of ASCII delimited text. 4575** 4576** + Input comes from p->in. 4577** + Store results in p->z of length p->n. Space to hold p->z comes 4578** from sqlite3_malloc64(). 4579** + Use p->cSep as the column separator. The default is "\x1F". 4580** + Use p->rSep as the row separator. The default is "\x1E". 4581** + Keep track of the row number in p->nLine. 4582** + Store the character that terminates the field in p->cTerm. Store 4583** EOF on end-of-file. 4584** + Report syntax errors on stderr 4585*/ 4586static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ 4587 int c; 4588 int cSep = p->cColSep; 4589 int rSep = p->cRowSep; 4590 p->n = 0; 4591 c = fgetc(p->in); 4592 if( c==EOF || seenInterrupt ){ 4593 p->cTerm = EOF; 4594 return 0; 4595 } 4596 while( c!=EOF && c!=cSep && c!=rSep ){ 4597 import_append_char(p, c); 4598 c = fgetc(p->in); 4599 } 4600 if( c==rSep ){ 4601 p->nLine++; 4602 } 4603 p->cTerm = c; 4604 if( p->z ) p->z[p->n] = 0; 4605 return p->z; 4606} 4607 4608/* 4609** Try to transfer data for table zTable. If an error is seen while 4610** moving forward, try to go backwards. The backwards movement won't 4611** work for WITHOUT ROWID tables. 4612*/ 4613static void tryToCloneData( 4614 ShellState *p, 4615 sqlite3 *newDb, 4616 const char *zTable 4617){ 4618 sqlite3_stmt *pQuery = 0; 4619 sqlite3_stmt *pInsert = 0; 4620 char *zQuery = 0; 4621 char *zInsert = 0; 4622 int rc; 4623 int i, j, n; 4624 int nTable = strlen30(zTable); 4625 int k = 0; 4626 int cnt = 0; 4627 const int spinRate = 10000; 4628 4629 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); 4630 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4631 if( rc ){ 4632 utf8_printf(stderr, "Error %d: %s on [%s]\n", 4633 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4634 zQuery); 4635 goto end_data_xfer; 4636 } 4637 n = sqlite3_column_count(pQuery); 4638 zInsert = sqlite3_malloc64(200 + nTable + n*3); 4639 if( zInsert==0 ) shell_out_of_memory(); 4640 sqlite3_snprintf(200+nTable,zInsert, 4641 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); 4642 i = strlen30(zInsert); 4643 for(j=1; j<n; j++){ 4644 memcpy(zInsert+i, ",?", 2); 4645 i += 2; 4646 } 4647 memcpy(zInsert+i, ");", 3); 4648 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); 4649 if( rc ){ 4650 utf8_printf(stderr, "Error %d: %s on [%s]\n", 4651 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), 4652 zQuery); 4653 goto end_data_xfer; 4654 } 4655 for(k=0; k<2; k++){ 4656 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4657 for(i=0; i<n; i++){ 4658 switch( sqlite3_column_type(pQuery, i) ){ 4659 case SQLITE_NULL: { 4660 sqlite3_bind_null(pInsert, i+1); 4661 break; 4662 } 4663 case SQLITE_INTEGER: { 4664 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); 4665 break; 4666 } 4667 case SQLITE_FLOAT: { 4668 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); 4669 break; 4670 } 4671 case SQLITE_TEXT: { 4672 sqlite3_bind_text(pInsert, i+1, 4673 (const char*)sqlite3_column_text(pQuery,i), 4674 -1, SQLITE_STATIC); 4675 break; 4676 } 4677 case SQLITE_BLOB: { 4678 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), 4679 sqlite3_column_bytes(pQuery,i), 4680 SQLITE_STATIC); 4681 break; 4682 } 4683 } 4684 } /* End for */ 4685 rc = sqlite3_step(pInsert); 4686 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ 4687 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), 4688 sqlite3_errmsg(newDb)); 4689 } 4690 sqlite3_reset(pInsert); 4691 cnt++; 4692 if( (cnt%spinRate)==0 ){ 4693 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); 4694 fflush(stdout); 4695 } 4696 } /* End while */ 4697 if( rc==SQLITE_DONE ) break; 4698 sqlite3_finalize(pQuery); 4699 sqlite3_free(zQuery); 4700 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", 4701 zTable); 4702 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4703 if( rc ){ 4704 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); 4705 break; 4706 } 4707 } /* End for(k=0...) */ 4708 4709end_data_xfer: 4710 sqlite3_finalize(pQuery); 4711 sqlite3_finalize(pInsert); 4712 sqlite3_free(zQuery); 4713 sqlite3_free(zInsert); 4714} 4715 4716 4717/* 4718** Try to transfer all rows of the schema that match zWhere. For 4719** each row, invoke xForEach() on the object defined by that row. 4720** If an error is encountered while moving forward through the 4721** sqlite_master table, try again moving backwards. 4722*/ 4723static void tryToCloneSchema( 4724 ShellState *p, 4725 sqlite3 *newDb, 4726 const char *zWhere, 4727 void (*xForEach)(ShellState*,sqlite3*,const char*) 4728){ 4729 sqlite3_stmt *pQuery = 0; 4730 char *zQuery = 0; 4731 int rc; 4732 const unsigned char *zName; 4733 const unsigned char *zSql; 4734 char *zErrMsg = 0; 4735 4736 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" 4737 " WHERE %s", zWhere); 4738 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4739 if( rc ){ 4740 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 4741 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4742 zQuery); 4743 goto end_schema_xfer; 4744 } 4745 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4746 zName = sqlite3_column_text(pQuery, 0); 4747 zSql = sqlite3_column_text(pQuery, 1); 4748 printf("%s... ", zName); fflush(stdout); 4749 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 4750 if( zErrMsg ){ 4751 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 4752 sqlite3_free(zErrMsg); 4753 zErrMsg = 0; 4754 } 4755 if( xForEach ){ 4756 xForEach(p, newDb, (const char*)zName); 4757 } 4758 printf("done\n"); 4759 } 4760 if( rc!=SQLITE_DONE ){ 4761 sqlite3_finalize(pQuery); 4762 sqlite3_free(zQuery); 4763 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" 4764 " WHERE %s ORDER BY rowid DESC", zWhere); 4765 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4766 if( rc ){ 4767 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 4768 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4769 zQuery); 4770 goto end_schema_xfer; 4771 } 4772 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4773 zName = sqlite3_column_text(pQuery, 0); 4774 zSql = sqlite3_column_text(pQuery, 1); 4775 printf("%s... ", zName); fflush(stdout); 4776 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 4777 if( zErrMsg ){ 4778 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 4779 sqlite3_free(zErrMsg); 4780 zErrMsg = 0; 4781 } 4782 if( xForEach ){ 4783 xForEach(p, newDb, (const char*)zName); 4784 } 4785 printf("done\n"); 4786 } 4787 } 4788end_schema_xfer: 4789 sqlite3_finalize(pQuery); 4790 sqlite3_free(zQuery); 4791} 4792 4793/* 4794** Open a new database file named "zNewDb". Try to recover as much information 4795** as possible out of the main database (which might be corrupt) and write it 4796** into zNewDb. 4797*/ 4798static void tryToClone(ShellState *p, const char *zNewDb){ 4799 int rc; 4800 sqlite3 *newDb = 0; 4801 if( access(zNewDb,0)==0 ){ 4802 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); 4803 return; 4804 } 4805 rc = sqlite3_open(zNewDb, &newDb); 4806 if( rc ){ 4807 utf8_printf(stderr, "Cannot create output database: %s\n", 4808 sqlite3_errmsg(newDb)); 4809 }else{ 4810 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); 4811 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); 4812 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); 4813 tryToCloneSchema(p, newDb, "type!='table'", 0); 4814 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); 4815 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 4816 } 4817 close_db(newDb); 4818} 4819 4820/* 4821** Change the output file back to stdout. 4822** 4823** If the p->doXdgOpen flag is set, that means the output was being 4824** redirected to a temporary file named by p->zTempFile. In that case, 4825** launch start/open/xdg-open on that temporary file. 4826*/ 4827static void output_reset(ShellState *p){ 4828 if( p->outfile[0]=='|' ){ 4829#ifndef SQLITE_OMIT_POPEN 4830 pclose(p->out); 4831#endif 4832 }else{ 4833 output_file_close(p->out); 4834#ifndef SQLITE_NOHAVE_SYSTEM 4835 if( p->doXdgOpen ){ 4836 const char *zXdgOpenCmd = 4837#if defined(_WIN32) 4838 "start"; 4839#elif defined(__APPLE__) 4840 "open"; 4841#else 4842 "xdg-open"; 4843#endif 4844 char *zCmd; 4845 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); 4846 if( system(zCmd) ){ 4847 utf8_printf(stderr, "Failed: [%s]\n", zCmd); 4848 } 4849 sqlite3_free(zCmd); 4850 outputModePop(p); 4851 p->doXdgOpen = 0; 4852 } 4853#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 4854 } 4855 p->outfile[0] = 0; 4856 p->out = stdout; 4857} 4858 4859/* 4860** Run an SQL command and return the single integer result. 4861*/ 4862static int db_int(ShellState *p, const char *zSql){ 4863 sqlite3_stmt *pStmt; 4864 int res = 0; 4865 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 4866 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 4867 res = sqlite3_column_int(pStmt,0); 4868 } 4869 sqlite3_finalize(pStmt); 4870 return res; 4871} 4872 4873/* 4874** Convert a 2-byte or 4-byte big-endian integer into a native integer 4875*/ 4876static unsigned int get2byteInt(unsigned char *a){ 4877 return (a[0]<<8) + a[1]; 4878} 4879static unsigned int get4byteInt(unsigned char *a){ 4880 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; 4881} 4882 4883/* 4884** Implementation of the ".info" command. 4885** 4886** Return 1 on error, 2 to exit, and 0 otherwise. 4887*/ 4888static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ 4889 static const struct { const char *zName; int ofst; } aField[] = { 4890 { "file change counter:", 24 }, 4891 { "database page count:", 28 }, 4892 { "freelist page count:", 36 }, 4893 { "schema cookie:", 40 }, 4894 { "schema format:", 44 }, 4895 { "default cache size:", 48 }, 4896 { "autovacuum top root:", 52 }, 4897 { "incremental vacuum:", 64 }, 4898 { "text encoding:", 56 }, 4899 { "user version:", 60 }, 4900 { "application id:", 68 }, 4901 { "software version:", 96 }, 4902 }; 4903 static const struct { const char *zName; const char *zSql; } aQuery[] = { 4904 { "number of tables:", 4905 "SELECT count(*) FROM %s WHERE type='table'" }, 4906 { "number of indexes:", 4907 "SELECT count(*) FROM %s WHERE type='index'" }, 4908 { "number of triggers:", 4909 "SELECT count(*) FROM %s WHERE type='trigger'" }, 4910 { "number of views:", 4911 "SELECT count(*) FROM %s WHERE type='view'" }, 4912 { "schema size:", 4913 "SELECT total(length(sql)) FROM %s" }, 4914 }; 4915 int i, rc; 4916 unsigned iDataVersion; 4917 char *zSchemaTab; 4918 char *zDb = nArg>=2 ? azArg[1] : "main"; 4919 sqlite3_stmt *pStmt = 0; 4920 unsigned char aHdr[100]; 4921 open_db(p, 0); 4922 if( p->db==0 ) return 1; 4923 rc = sqlite3_prepare_v2(p->db, 4924 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", 4925 -1, &pStmt, 0); 4926 if( rc ){ 4927 if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){ 4928 utf8_printf(stderr, "the \".dbinfo\" command requires the " 4929 "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n"); 4930 }else{ 4931 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db)); 4932 } 4933 sqlite3_finalize(pStmt); 4934 return 1; 4935 } 4936 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); 4937 if( sqlite3_step(pStmt)==SQLITE_ROW 4938 && sqlite3_column_bytes(pStmt,0)>100 4939 ){ 4940 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); 4941 sqlite3_finalize(pStmt); 4942 }else{ 4943 raw_printf(stderr, "unable to read database header\n"); 4944 sqlite3_finalize(pStmt); 4945 return 1; 4946 } 4947 i = get2byteInt(aHdr+16); 4948 if( i==1 ) i = 65536; 4949 utf8_printf(p->out, "%-20s %d\n", "database page size:", i); 4950 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); 4951 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); 4952 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); 4953 for(i=0; i<ArraySize(aField); i++){ 4954 int ofst = aField[i].ofst; 4955 unsigned int val = get4byteInt(aHdr + ofst); 4956 utf8_printf(p->out, "%-20s %u", aField[i].zName, val); 4957 switch( ofst ){ 4958 case 56: { 4959 if( val==1 ) raw_printf(p->out, " (utf8)"); 4960 if( val==2 ) raw_printf(p->out, " (utf16le)"); 4961 if( val==3 ) raw_printf(p->out, " (utf16be)"); 4962 } 4963 } 4964 raw_printf(p->out, "\n"); 4965 } 4966 if( zDb==0 ){ 4967 zSchemaTab = sqlite3_mprintf("main.sqlite_master"); 4968 }else if( strcmp(zDb,"temp")==0 ){ 4969 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master"); 4970 }else{ 4971 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb); 4972 } 4973 for(i=0; i<ArraySize(aQuery); i++){ 4974 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); 4975 int val = db_int(p, zSql); 4976 sqlite3_free(zSql); 4977 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); 4978 } 4979 sqlite3_free(zSchemaTab); 4980 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); 4981 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion); 4982 return 0; 4983} 4984 4985/* 4986** Print the current sqlite3_errmsg() value to stderr and return 1. 4987*/ 4988static int shellDatabaseError(sqlite3 *db){ 4989 const char *zErr = sqlite3_errmsg(db); 4990 utf8_printf(stderr, "Error: %s\n", zErr); 4991 return 1; 4992} 4993 4994/* 4995** Compare the pattern in zGlob[] against the text in z[]. Return TRUE 4996** if they match and FALSE (0) if they do not match. 4997** 4998** Globbing rules: 4999** 5000** '*' Matches any sequence of zero or more characters. 5001** 5002** '?' Matches exactly one character. 5003** 5004** [...] Matches one character from the enclosed list of 5005** characters. 5006** 5007** [^...] Matches one character not in the enclosed list. 5008** 5009** '#' Matches any sequence of one or more digits with an 5010** optional + or - sign in front 5011** 5012** ' ' Any span of whitespace matches any other span of 5013** whitespace. 5014** 5015** Extra whitespace at the end of z[] is ignored. 5016*/ 5017static int testcase_glob(const char *zGlob, const char *z){ 5018 int c, c2; 5019 int invert; 5020 int seen; 5021 5022 while( (c = (*(zGlob++)))!=0 ){ 5023 if( IsSpace(c) ){ 5024 if( !IsSpace(*z) ) return 0; 5025 while( IsSpace(*zGlob) ) zGlob++; 5026 while( IsSpace(*z) ) z++; 5027 }else if( c=='*' ){ 5028 while( (c=(*(zGlob++))) == '*' || c=='?' ){ 5029 if( c=='?' && (*(z++))==0 ) return 0; 5030 } 5031 if( c==0 ){ 5032 return 1; 5033 }else if( c=='[' ){ 5034 while( *z && testcase_glob(zGlob-1,z)==0 ){ 5035 z++; 5036 } 5037 return (*z)!=0; 5038 } 5039 while( (c2 = (*(z++)))!=0 ){ 5040 while( c2!=c ){ 5041 c2 = *(z++); 5042 if( c2==0 ) return 0; 5043 } 5044 if( testcase_glob(zGlob,z) ) return 1; 5045 } 5046 return 0; 5047 }else if( c=='?' ){ 5048 if( (*(z++))==0 ) return 0; 5049 }else if( c=='[' ){ 5050 int prior_c = 0; 5051 seen = 0; 5052 invert = 0; 5053 c = *(z++); 5054 if( c==0 ) return 0; 5055 c2 = *(zGlob++); 5056 if( c2=='^' ){ 5057 invert = 1; 5058 c2 = *(zGlob++); 5059 } 5060 if( c2==']' ){ 5061 if( c==']' ) seen = 1; 5062 c2 = *(zGlob++); 5063 } 5064 while( c2 && c2!=']' ){ 5065 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ 5066 c2 = *(zGlob++); 5067 if( c>=prior_c && c<=c2 ) seen = 1; 5068 prior_c = 0; 5069 }else{ 5070 if( c==c2 ){ 5071 seen = 1; 5072 } 5073 prior_c = c2; 5074 } 5075 c2 = *(zGlob++); 5076 } 5077 if( c2==0 || (seen ^ invert)==0 ) return 0; 5078 }else if( c=='#' ){ 5079 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; 5080 if( !IsDigit(z[0]) ) return 0; 5081 z++; 5082 while( IsDigit(z[0]) ){ z++; } 5083 }else{ 5084 if( c!=(*(z++)) ) return 0; 5085 } 5086 } 5087 while( IsSpace(*z) ){ z++; } 5088 return *z==0; 5089} 5090 5091 5092/* 5093** Compare the string as a command-line option with either one or two 5094** initial "-" characters. 5095*/ 5096static int optionMatch(const char *zStr, const char *zOpt){ 5097 if( zStr[0]!='-' ) return 0; 5098 zStr++; 5099 if( zStr[0]=='-' ) zStr++; 5100 return strcmp(zStr, zOpt)==0; 5101} 5102 5103/* 5104** Delete a file. 5105*/ 5106int shellDeleteFile(const char *zFilename){ 5107 int rc; 5108#ifdef _WIN32 5109 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); 5110 rc = _wunlink(z); 5111 sqlite3_free(z); 5112#else 5113 rc = unlink(zFilename); 5114#endif 5115 return rc; 5116} 5117 5118/* 5119** Try to delete the temporary file (if there is one) and free the 5120** memory used to hold the name of the temp file. 5121*/ 5122static void clearTempFile(ShellState *p){ 5123 if( p->zTempFile==0 ) return; 5124 if( p->doXdgOpen ) return; 5125 if( shellDeleteFile(p->zTempFile) ) return; 5126 sqlite3_free(p->zTempFile); 5127 p->zTempFile = 0; 5128} 5129 5130/* 5131** Create a new temp file name with the given suffix. 5132*/ 5133static void newTempFile(ShellState *p, const char *zSuffix){ 5134 clearTempFile(p); 5135 sqlite3_free(p->zTempFile); 5136 p->zTempFile = 0; 5137 if( p->db ){ 5138 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); 5139 } 5140 if( p->zTempFile==0 ){ 5141 sqlite3_uint64 r; 5142 sqlite3_randomness(sizeof(r), &r); 5143 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix); 5144 }else{ 5145 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); 5146 } 5147 if( p->zTempFile==0 ){ 5148 raw_printf(stderr, "out of memory\n"); 5149 exit(1); 5150 } 5151} 5152 5153 5154/* 5155** The implementation of SQL scalar function fkey_collate_clause(), used 5156** by the ".lint fkey-indexes" command. This scalar function is always 5157** called with four arguments - the parent table name, the parent column name, 5158** the child table name and the child column name. 5159** 5160** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') 5161** 5162** If either of the named tables or columns do not exist, this function 5163** returns an empty string. An empty string is also returned if both tables 5164** and columns exist but have the same default collation sequence. Or, 5165** if both exist but the default collation sequences are different, this 5166** function returns the string " COLLATE <parent-collation>", where 5167** <parent-collation> is the default collation sequence of the parent column. 5168*/ 5169static void shellFkeyCollateClause( 5170 sqlite3_context *pCtx, 5171 int nVal, 5172 sqlite3_value **apVal 5173){ 5174 sqlite3 *db = sqlite3_context_db_handle(pCtx); 5175 const char *zParent; 5176 const char *zParentCol; 5177 const char *zParentSeq; 5178 const char *zChild; 5179 const char *zChildCol; 5180 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ 5181 int rc; 5182 5183 assert( nVal==4 ); 5184 zParent = (const char*)sqlite3_value_text(apVal[0]); 5185 zParentCol = (const char*)sqlite3_value_text(apVal[1]); 5186 zChild = (const char*)sqlite3_value_text(apVal[2]); 5187 zChildCol = (const char*)sqlite3_value_text(apVal[3]); 5188 5189 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); 5190 rc = sqlite3_table_column_metadata( 5191 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 5192 ); 5193 if( rc==SQLITE_OK ){ 5194 rc = sqlite3_table_column_metadata( 5195 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 5196 ); 5197 } 5198 5199 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ 5200 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); 5201 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); 5202 sqlite3_free(z); 5203 } 5204} 5205 5206 5207/* 5208** The implementation of dot-command ".lint fkey-indexes". 5209*/ 5210static int lintFkeyIndexes( 5211 ShellState *pState, /* Current shell tool state */ 5212 char **azArg, /* Array of arguments passed to dot command */ 5213 int nArg /* Number of entries in azArg[] */ 5214){ 5215 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ 5216 FILE *out = pState->out; /* Stream to write non-error output to */ 5217 int bVerbose = 0; /* If -verbose is present */ 5218 int bGroupByParent = 0; /* If -groupbyparent is present */ 5219 int i; /* To iterate through azArg[] */ 5220 const char *zIndent = ""; /* How much to indent CREATE INDEX by */ 5221 int rc; /* Return code */ 5222 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ 5223 5224 /* 5225 ** This SELECT statement returns one row for each foreign key constraint 5226 ** in the schema of the main database. The column values are: 5227 ** 5228 ** 0. The text of an SQL statement similar to: 5229 ** 5230 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" 5231 ** 5232 ** This SELECT is similar to the one that the foreign keys implementation 5233 ** needs to run internally on child tables. If there is an index that can 5234 ** be used to optimize this query, then it can also be used by the FK 5235 ** implementation to optimize DELETE or UPDATE statements on the parent 5236 ** table. 5237 ** 5238 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by 5239 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema 5240 ** contains an index that can be used to optimize the query. 5241 ** 5242 ** 2. Human readable text that describes the child table and columns. e.g. 5243 ** 5244 ** "child_table(child_key1, child_key2)" 5245 ** 5246 ** 3. Human readable text that describes the parent table and columns. e.g. 5247 ** 5248 ** "parent_table(parent_key1, parent_key2)" 5249 ** 5250 ** 4. A full CREATE INDEX statement for an index that could be used to 5251 ** optimize DELETE or UPDATE statements on the parent table. e.g. 5252 ** 5253 ** "CREATE INDEX child_table_child_key ON child_table(child_key)" 5254 ** 5255 ** 5. The name of the parent table. 5256 ** 5257 ** These six values are used by the C logic below to generate the report. 5258 */ 5259 const char *zSql = 5260 "SELECT " 5261 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" 5262 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " 5263 " || fkey_collate_clause(" 5264 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" 5265 ", " 5266 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('" 5267 " || group_concat('*=?', ' AND ') || ')'" 5268 ", " 5269 " s.name || '(' || group_concat(f.[from], ', ') || ')'" 5270 ", " 5271 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" 5272 ", " 5273 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" 5274 " || ' ON ' || quote(s.name) || '('" 5275 " || group_concat(quote(f.[from]) ||" 5276 " fkey_collate_clause(" 5277 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" 5278 " || ');'" 5279 ", " 5280 " f.[table] " 5281 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f " 5282 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " 5283 "GROUP BY s.name, f.id " 5284 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" 5285 ; 5286 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)"; 5287 5288 for(i=2; i<nArg; i++){ 5289 int n = strlen30(azArg[i]); 5290 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ 5291 bVerbose = 1; 5292 } 5293 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ 5294 bGroupByParent = 1; 5295 zIndent = " "; 5296 } 5297 else{ 5298 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", 5299 azArg[0], azArg[1] 5300 ); 5301 return SQLITE_ERROR; 5302 } 5303 } 5304 5305 /* Register the fkey_collate_clause() SQL function */ 5306 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, 5307 0, shellFkeyCollateClause, 0, 0 5308 ); 5309 5310 5311 if( rc==SQLITE_OK ){ 5312 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); 5313 } 5314 if( rc==SQLITE_OK ){ 5315 sqlite3_bind_int(pSql, 1, bGroupByParent); 5316 } 5317 5318 if( rc==SQLITE_OK ){ 5319 int rc2; 5320 char *zPrev = 0; 5321 while( SQLITE_ROW==sqlite3_step(pSql) ){ 5322 int res = -1; 5323 sqlite3_stmt *pExplain = 0; 5324 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); 5325 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); 5326 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); 5327 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); 5328 const char *zCI = (const char*)sqlite3_column_text(pSql, 4); 5329 const char *zParent = (const char*)sqlite3_column_text(pSql, 5); 5330 5331 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 5332 if( rc!=SQLITE_OK ) break; 5333 if( SQLITE_ROW==sqlite3_step(pExplain) ){ 5334 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); 5335 res = ( 5336 0==sqlite3_strglob(zGlob, zPlan) 5337 || 0==sqlite3_strglob(zGlobIPK, zPlan) 5338 ); 5339 } 5340 rc = sqlite3_finalize(pExplain); 5341 if( rc!=SQLITE_OK ) break; 5342 5343 if( res<0 ){ 5344 raw_printf(stderr, "Error: internal error"); 5345 break; 5346 }else{ 5347 if( bGroupByParent 5348 && (bVerbose || res==0) 5349 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 5350 ){ 5351 raw_printf(out, "-- Parent table %s\n", zParent); 5352 sqlite3_free(zPrev); 5353 zPrev = sqlite3_mprintf("%s", zParent); 5354 } 5355 5356 if( res==0 ){ 5357 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); 5358 }else if( bVerbose ){ 5359 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 5360 zIndent, zFrom, zTarget 5361 ); 5362 } 5363 } 5364 } 5365 sqlite3_free(zPrev); 5366 5367 if( rc!=SQLITE_OK ){ 5368 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5369 } 5370 5371 rc2 = sqlite3_finalize(pSql); 5372 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ 5373 rc = rc2; 5374 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5375 } 5376 }else{ 5377 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5378 } 5379 5380 return rc; 5381} 5382 5383/* 5384** Implementation of ".lint" dot command. 5385*/ 5386static int lintDotCommand( 5387 ShellState *pState, /* Current shell tool state */ 5388 char **azArg, /* Array of arguments passed to dot command */ 5389 int nArg /* Number of entries in azArg[] */ 5390){ 5391 int n; 5392 n = (nArg>=2 ? strlen30(azArg[1]) : 0); 5393 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; 5394 return lintFkeyIndexes(pState, azArg, nArg); 5395 5396 usage: 5397 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); 5398 raw_printf(stderr, "Where sub-commands are:\n"); 5399 raw_printf(stderr, " fkey-indexes\n"); 5400 return SQLITE_ERROR; 5401} 5402 5403#if !defined SQLITE_OMIT_VIRTUALTABLE 5404static void shellPrepare( 5405 sqlite3 *db, 5406 int *pRc, 5407 const char *zSql, 5408 sqlite3_stmt **ppStmt 5409){ 5410 *ppStmt = 0; 5411 if( *pRc==SQLITE_OK ){ 5412 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); 5413 if( rc!=SQLITE_OK ){ 5414 raw_printf(stderr, "sql error: %s (%d)\n", 5415 sqlite3_errmsg(db), sqlite3_errcode(db) 5416 ); 5417 *pRc = rc; 5418 } 5419 } 5420} 5421 5422/* 5423** Create a prepared statement using printf-style arguments for the SQL. 5424** 5425** This routine is could be marked "static". But it is not always used, 5426** depending on compile-time options. By omitting the "static", we avoid 5427** nuisance compiler warnings about "defined but not used". 5428*/ 5429void shellPreparePrintf( 5430 sqlite3 *db, 5431 int *pRc, 5432 sqlite3_stmt **ppStmt, 5433 const char *zFmt, 5434 ... 5435){ 5436 *ppStmt = 0; 5437 if( *pRc==SQLITE_OK ){ 5438 va_list ap; 5439 char *z; 5440 va_start(ap, zFmt); 5441 z = sqlite3_vmprintf(zFmt, ap); 5442 va_end(ap); 5443 if( z==0 ){ 5444 *pRc = SQLITE_NOMEM; 5445 }else{ 5446 shellPrepare(db, pRc, z, ppStmt); 5447 sqlite3_free(z); 5448 } 5449 } 5450} 5451 5452/* Finalize the prepared statement created using shellPreparePrintf(). 5453** 5454** This routine is could be marked "static". But it is not always used, 5455** depending on compile-time options. By omitting the "static", we avoid 5456** nuisance compiler warnings about "defined but not used". 5457*/ 5458void shellFinalize( 5459 int *pRc, 5460 sqlite3_stmt *pStmt 5461){ 5462 if( pStmt ){ 5463 sqlite3 *db = sqlite3_db_handle(pStmt); 5464 int rc = sqlite3_finalize(pStmt); 5465 if( *pRc==SQLITE_OK ){ 5466 if( rc!=SQLITE_OK ){ 5467 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 5468 } 5469 *pRc = rc; 5470 } 5471 } 5472} 5473 5474/* Reset the prepared statement created using shellPreparePrintf(). 5475** 5476** This routine is could be marked "static". But it is not always used, 5477** depending on compile-time options. By omitting the "static", we avoid 5478** nuisance compiler warnings about "defined but not used". 5479*/ 5480void shellReset( 5481 int *pRc, 5482 sqlite3_stmt *pStmt 5483){ 5484 int rc = sqlite3_reset(pStmt); 5485 if( *pRc==SQLITE_OK ){ 5486 if( rc!=SQLITE_OK ){ 5487 sqlite3 *db = sqlite3_db_handle(pStmt); 5488 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 5489 } 5490 *pRc = rc; 5491 } 5492} 5493#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ 5494 5495#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 5496/********************************************************************************* 5497** The ".archive" or ".ar" command. 5498*/ 5499/* 5500** Structure representing a single ".ar" command. 5501*/ 5502typedef struct ArCommand ArCommand; 5503struct ArCommand { 5504 u8 eCmd; /* An AR_CMD_* value */ 5505 u8 bVerbose; /* True if --verbose */ 5506 u8 bZip; /* True if the archive is a ZIP */ 5507 u8 bDryRun; /* True if --dry-run */ 5508 u8 bAppend; /* True if --append */ 5509 u8 fromCmdLine; /* Run from -A instead of .archive */ 5510 int nArg; /* Number of command arguments */ 5511 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ 5512 const char *zFile; /* --file argument, or NULL */ 5513 const char *zDir; /* --directory argument, or NULL */ 5514 char **azArg; /* Array of command arguments */ 5515 ShellState *p; /* Shell state */ 5516 sqlite3 *db; /* Database containing the archive */ 5517}; 5518 5519/* 5520** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. 5521*/ 5522static int arUsage(FILE *f){ 5523 showHelp(f,"archive"); 5524 return SQLITE_ERROR; 5525} 5526 5527/* 5528** Print an error message for the .ar command to stderr and return 5529** SQLITE_ERROR. 5530*/ 5531static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ 5532 va_list ap; 5533 char *z; 5534 va_start(ap, zFmt); 5535 z = sqlite3_vmprintf(zFmt, ap); 5536 va_end(ap); 5537 utf8_printf(stderr, "Error: %s\n", z); 5538 if( pAr->fromCmdLine ){ 5539 utf8_printf(stderr, "Use \"-A\" for more help\n"); 5540 }else{ 5541 utf8_printf(stderr, "Use \".archive --help\" for more help\n"); 5542 } 5543 sqlite3_free(z); 5544 return SQLITE_ERROR; 5545} 5546 5547/* 5548** Values for ArCommand.eCmd. 5549*/ 5550#define AR_CMD_CREATE 1 5551#define AR_CMD_UPDATE 2 5552#define AR_CMD_INSERT 3 5553#define AR_CMD_EXTRACT 4 5554#define AR_CMD_LIST 5 5555#define AR_CMD_HELP 6 5556 5557/* 5558** Other (non-command) switches. 5559*/ 5560#define AR_SWITCH_VERBOSE 7 5561#define AR_SWITCH_FILE 8 5562#define AR_SWITCH_DIRECTORY 9 5563#define AR_SWITCH_APPEND 10 5564#define AR_SWITCH_DRYRUN 11 5565 5566static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ 5567 switch( eSwitch ){ 5568 case AR_CMD_CREATE: 5569 case AR_CMD_EXTRACT: 5570 case AR_CMD_LIST: 5571 case AR_CMD_UPDATE: 5572 case AR_CMD_INSERT: 5573 case AR_CMD_HELP: 5574 if( pAr->eCmd ){ 5575 return arErrorMsg(pAr, "multiple command options"); 5576 } 5577 pAr->eCmd = eSwitch; 5578 break; 5579 5580 case AR_SWITCH_DRYRUN: 5581 pAr->bDryRun = 1; 5582 break; 5583 case AR_SWITCH_VERBOSE: 5584 pAr->bVerbose = 1; 5585 break; 5586 case AR_SWITCH_APPEND: 5587 pAr->bAppend = 1; 5588 /* Fall thru into --file */ 5589 case AR_SWITCH_FILE: 5590 pAr->zFile = zArg; 5591 break; 5592 case AR_SWITCH_DIRECTORY: 5593 pAr->zDir = zArg; 5594 break; 5595 } 5596 5597 return SQLITE_OK; 5598} 5599 5600/* 5601** Parse the command line for an ".ar" command. The results are written into 5602** structure (*pAr). SQLITE_OK is returned if the command line is parsed 5603** successfully, otherwise an error message is written to stderr and 5604** SQLITE_ERROR returned. 5605*/ 5606static int arParseCommand( 5607 char **azArg, /* Array of arguments passed to dot command */ 5608 int nArg, /* Number of entries in azArg[] */ 5609 ArCommand *pAr /* Populate this object */ 5610){ 5611 struct ArSwitch { 5612 const char *zLong; 5613 char cShort; 5614 u8 eSwitch; 5615 u8 bArg; 5616 } aSwitch[] = { 5617 { "create", 'c', AR_CMD_CREATE, 0 }, 5618 { "extract", 'x', AR_CMD_EXTRACT, 0 }, 5619 { "insert", 'i', AR_CMD_INSERT, 0 }, 5620 { "list", 't', AR_CMD_LIST, 0 }, 5621 { "update", 'u', AR_CMD_UPDATE, 0 }, 5622 { "help", 'h', AR_CMD_HELP, 0 }, 5623 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, 5624 { "file", 'f', AR_SWITCH_FILE, 1 }, 5625 { "append", 'a', AR_SWITCH_APPEND, 1 }, 5626 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, 5627 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, 5628 }; 5629 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); 5630 struct ArSwitch *pEnd = &aSwitch[nSwitch]; 5631 5632 if( nArg<=1 ){ 5633 utf8_printf(stderr, "Wrong number of arguments. Usage:\n"); 5634 return arUsage(stderr); 5635 }else{ 5636 char *z = azArg[1]; 5637 if( z[0]!='-' ){ 5638 /* Traditional style [tar] invocation */ 5639 int i; 5640 int iArg = 2; 5641 for(i=0; z[i]; i++){ 5642 const char *zArg = 0; 5643 struct ArSwitch *pOpt; 5644 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5645 if( z[i]==pOpt->cShort ) break; 5646 } 5647 if( pOpt==pEnd ){ 5648 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 5649 } 5650 if( pOpt->bArg ){ 5651 if( iArg>=nArg ){ 5652 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 5653 } 5654 zArg = azArg[iArg++]; 5655 } 5656 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 5657 } 5658 pAr->nArg = nArg-iArg; 5659 if( pAr->nArg>0 ){ 5660 pAr->azArg = &azArg[iArg]; 5661 } 5662 }else{ 5663 /* Non-traditional invocation */ 5664 int iArg; 5665 for(iArg=1; iArg<nArg; iArg++){ 5666 int n; 5667 z = azArg[iArg]; 5668 if( z[0]!='-' ){ 5669 /* All remaining command line words are command arguments. */ 5670 pAr->azArg = &azArg[iArg]; 5671 pAr->nArg = nArg-iArg; 5672 break; 5673 } 5674 n = strlen30(z); 5675 5676 if( z[1]!='-' ){ 5677 int i; 5678 /* One or more short options */ 5679 for(i=1; i<n; i++){ 5680 const char *zArg = 0; 5681 struct ArSwitch *pOpt; 5682 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5683 if( z[i]==pOpt->cShort ) break; 5684 } 5685 if( pOpt==pEnd ){ 5686 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 5687 } 5688 if( pOpt->bArg ){ 5689 if( i<(n-1) ){ 5690 zArg = &z[i+1]; 5691 i = n; 5692 }else{ 5693 if( iArg>=(nArg-1) ){ 5694 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 5695 } 5696 zArg = azArg[++iArg]; 5697 } 5698 } 5699 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 5700 } 5701 }else if( z[2]=='\0' ){ 5702 /* A -- option, indicating that all remaining command line words 5703 ** are command arguments. */ 5704 pAr->azArg = &azArg[iArg+1]; 5705 pAr->nArg = nArg-iArg-1; 5706 break; 5707 }else{ 5708 /* A long option */ 5709 const char *zArg = 0; /* Argument for option, if any */ 5710 struct ArSwitch *pMatch = 0; /* Matching option */ 5711 struct ArSwitch *pOpt; /* Iterator */ 5712 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5713 const char *zLong = pOpt->zLong; 5714 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ 5715 if( pMatch ){ 5716 return arErrorMsg(pAr, "ambiguous option: %s",z); 5717 }else{ 5718 pMatch = pOpt; 5719 } 5720 } 5721 } 5722 5723 if( pMatch==0 ){ 5724 return arErrorMsg(pAr, "unrecognized option: %s", z); 5725 } 5726 if( pMatch->bArg ){ 5727 if( iArg>=(nArg-1) ){ 5728 return arErrorMsg(pAr, "option requires an argument: %s", z); 5729 } 5730 zArg = azArg[++iArg]; 5731 } 5732 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; 5733 } 5734 } 5735 } 5736 } 5737 5738 return SQLITE_OK; 5739} 5740 5741/* 5742** This function assumes that all arguments within the ArCommand.azArg[] 5743** array refer to archive members, as for the --extract or --list commands. 5744** It checks that each of them are present. If any specified file is not 5745** present in the archive, an error is printed to stderr and an error 5746** code returned. Otherwise, if all specified arguments are present in 5747** the archive, SQLITE_OK is returned. 5748** 5749** This function strips any trailing '/' characters from each argument. 5750** This is consistent with the way the [tar] command seems to work on 5751** Linux. 5752*/ 5753static int arCheckEntries(ArCommand *pAr){ 5754 int rc = SQLITE_OK; 5755 if( pAr->nArg ){ 5756 int i, j; 5757 sqlite3_stmt *pTest = 0; 5758 5759 shellPreparePrintf(pAr->db, &rc, &pTest, 5760 "SELECT name FROM %s WHERE name=$name", 5761 pAr->zSrcTable 5762 ); 5763 j = sqlite3_bind_parameter_index(pTest, "$name"); 5764 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 5765 char *z = pAr->azArg[i]; 5766 int n = strlen30(z); 5767 int bOk = 0; 5768 while( n>0 && z[n-1]=='/' ) n--; 5769 z[n] = '\0'; 5770 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); 5771 if( SQLITE_ROW==sqlite3_step(pTest) ){ 5772 bOk = 1; 5773 } 5774 shellReset(&rc, pTest); 5775 if( rc==SQLITE_OK && bOk==0 ){ 5776 utf8_printf(stderr, "not found in archive: %s\n", z); 5777 rc = SQLITE_ERROR; 5778 } 5779 } 5780 shellFinalize(&rc, pTest); 5781 } 5782 return rc; 5783} 5784 5785/* 5786** Format a WHERE clause that can be used against the "sqlar" table to 5787** identify all archive members that match the command arguments held 5788** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. 5789** The caller is responsible for eventually calling sqlite3_free() on 5790** any non-NULL (*pzWhere) value. 5791*/ 5792static void arWhereClause( 5793 int *pRc, 5794 ArCommand *pAr, 5795 char **pzWhere /* OUT: New WHERE clause */ 5796){ 5797 char *zWhere = 0; 5798 if( *pRc==SQLITE_OK ){ 5799 if( pAr->nArg==0 ){ 5800 zWhere = sqlite3_mprintf("1"); 5801 }else{ 5802 int i; 5803 const char *zSep = ""; 5804 for(i=0; i<pAr->nArg; i++){ 5805 const char *z = pAr->azArg[i]; 5806 zWhere = sqlite3_mprintf( 5807 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 5808 zWhere, zSep, z, strlen30(z)+1, z 5809 ); 5810 if( zWhere==0 ){ 5811 *pRc = SQLITE_NOMEM; 5812 break; 5813 } 5814 zSep = " OR "; 5815 } 5816 } 5817 } 5818 *pzWhere = zWhere; 5819} 5820 5821/* 5822** Implementation of .ar "lisT" command. 5823*/ 5824static int arListCommand(ArCommand *pAr){ 5825 const char *zSql = "SELECT %s FROM %s WHERE %s"; 5826 const char *azCols[] = { 5827 "name", 5828 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" 5829 }; 5830 5831 char *zWhere = 0; 5832 sqlite3_stmt *pSql = 0; 5833 int rc; 5834 5835 rc = arCheckEntries(pAr); 5836 arWhereClause(&rc, pAr, &zWhere); 5837 5838 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], 5839 pAr->zSrcTable, zWhere); 5840 if( pAr->bDryRun ){ 5841 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 5842 }else{ 5843 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 5844 if( pAr->bVerbose ){ 5845 utf8_printf(pAr->p->out, "%s % 10d %s %s\n", 5846 sqlite3_column_text(pSql, 0), 5847 sqlite3_column_int(pSql, 1), 5848 sqlite3_column_text(pSql, 2), 5849 sqlite3_column_text(pSql, 3) 5850 ); 5851 }else{ 5852 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 5853 } 5854 } 5855 } 5856 shellFinalize(&rc, pSql); 5857 sqlite3_free(zWhere); 5858 return rc; 5859} 5860 5861 5862/* 5863** Implementation of .ar "eXtract" command. 5864*/ 5865static int arExtractCommand(ArCommand *pAr){ 5866 const char *zSql1 = 5867 "SELECT " 5868 " ($dir || name)," 5869 " writefile(($dir || name), %s, mode, mtime) " 5870 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" 5871 " AND name NOT GLOB '*..[/\\]*'"; 5872 5873 const char *azExtraArg[] = { 5874 "sqlar_uncompress(data, sz)", 5875 "data" 5876 }; 5877 5878 sqlite3_stmt *pSql = 0; 5879 int rc = SQLITE_OK; 5880 char *zDir = 0; 5881 char *zWhere = 0; 5882 int i, j; 5883 5884 /* If arguments are specified, check that they actually exist within 5885 ** the archive before proceeding. And formulate a WHERE clause to 5886 ** match them. */ 5887 rc = arCheckEntries(pAr); 5888 arWhereClause(&rc, pAr, &zWhere); 5889 5890 if( rc==SQLITE_OK ){ 5891 if( pAr->zDir ){ 5892 zDir = sqlite3_mprintf("%s/", pAr->zDir); 5893 }else{ 5894 zDir = sqlite3_mprintf(""); 5895 } 5896 if( zDir==0 ) rc = SQLITE_NOMEM; 5897 } 5898 5899 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 5900 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere 5901 ); 5902 5903 if( rc==SQLITE_OK ){ 5904 j = sqlite3_bind_parameter_index(pSql, "$dir"); 5905 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); 5906 5907 /* Run the SELECT statement twice. The first time, writefile() is called 5908 ** for all archive members that should be extracted. The second time, 5909 ** only for the directories. This is because the timestamps for 5910 ** extracted directories must be reset after they are populated (as 5911 ** populating them changes the timestamp). */ 5912 for(i=0; i<2; i++){ 5913 j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); 5914 sqlite3_bind_int(pSql, j, i); 5915 if( pAr->bDryRun ){ 5916 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 5917 }else{ 5918 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 5919 if( i==0 && pAr->bVerbose ){ 5920 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 5921 } 5922 } 5923 } 5924 shellReset(&rc, pSql); 5925 } 5926 shellFinalize(&rc, pSql); 5927 } 5928 5929 sqlite3_free(zDir); 5930 sqlite3_free(zWhere); 5931 return rc; 5932} 5933 5934/* 5935** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. 5936*/ 5937static int arExecSql(ArCommand *pAr, const char *zSql){ 5938 int rc; 5939 if( pAr->bDryRun ){ 5940 utf8_printf(pAr->p->out, "%s\n", zSql); 5941 rc = SQLITE_OK; 5942 }else{ 5943 char *zErr = 0; 5944 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 5945 if( zErr ){ 5946 utf8_printf(stdout, "ERROR: %s\n", zErr); 5947 sqlite3_free(zErr); 5948 } 5949 } 5950 return rc; 5951} 5952 5953 5954/* 5955** Implementation of .ar "create", "insert", and "update" commands. 5956** 5957** create -> Create a new SQL archive 5958** insert -> Insert or reinsert all files listed 5959** update -> Insert files that have changed or that were not 5960** previously in the archive 5961** 5962** Create the "sqlar" table in the database if it does not already exist. 5963** Then add each file in the azFile[] array to the archive. Directories 5964** are added recursively. If argument bVerbose is non-zero, a message is 5965** printed on stdout for each file archived. 5966** 5967** The create command is the same as update, except that it drops 5968** any existing "sqlar" table before beginning. The "insert" command 5969** always overwrites every file named on the command-line, where as 5970** "update" only overwrites if the size or mtime or mode has changed. 5971*/ 5972static int arCreateOrUpdateCommand( 5973 ArCommand *pAr, /* Command arguments and options */ 5974 int bUpdate, /* true for a --create. */ 5975 int bOnlyIfChanged /* Only update if file has changed */ 5976){ 5977 const char *zCreate = 5978 "CREATE TABLE IF NOT EXISTS sqlar(\n" 5979 " name TEXT PRIMARY KEY, -- name of the file\n" 5980 " mode INT, -- access permissions\n" 5981 " mtime INT, -- last modification time\n" 5982 " sz INT, -- original file size\n" 5983 " data BLOB -- compressed content\n" 5984 ")"; 5985 const char *zDrop = "DROP TABLE IF EXISTS sqlar"; 5986 const char *zInsertFmt[2] = { 5987 "REPLACE INTO %s(name,mode,mtime,sz,data)\n" 5988 " SELECT\n" 5989 " %s,\n" 5990 " mode,\n" 5991 " mtime,\n" 5992 " CASE substr(lsmode(mode),1,1)\n" 5993 " WHEN '-' THEN length(data)\n" 5994 " WHEN 'd' THEN 0\n" 5995 " ELSE -1 END,\n" 5996 " sqlar_compress(data)\n" 5997 " FROM fsdir(%Q,%Q) AS disk\n" 5998 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 5999 , 6000 "REPLACE INTO %s(name,mode,mtime,data)\n" 6001 " SELECT\n" 6002 " %s,\n" 6003 " mode,\n" 6004 " mtime,\n" 6005 " data\n" 6006 " FROM fsdir(%Q,%Q) AS disk\n" 6007 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6008 }; 6009 int i; /* For iterating through azFile[] */ 6010 int rc; /* Return code */ 6011 const char *zTab = 0; /* SQL table into which to insert */ 6012 char *zSql; 6013 char zTemp[50]; 6014 char *zExists = 0; 6015 6016 arExecSql(pAr, "PRAGMA page_size=512"); 6017 rc = arExecSql(pAr, "SAVEPOINT ar;"); 6018 if( rc!=SQLITE_OK ) return rc; 6019 zTemp[0] = 0; 6020 if( pAr->bZip ){ 6021 /* Initialize the zipfile virtual table, if necessary */ 6022 if( pAr->zFile ){ 6023 sqlite3_uint64 r; 6024 sqlite3_randomness(sizeof(r),&r); 6025 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); 6026 zTab = zTemp; 6027 zSql = sqlite3_mprintf( 6028 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", 6029 zTab, pAr->zFile 6030 ); 6031 rc = arExecSql(pAr, zSql); 6032 sqlite3_free(zSql); 6033 }else{ 6034 zTab = "zip"; 6035 } 6036 }else{ 6037 /* Initialize the table for an SQLAR */ 6038 zTab = "sqlar"; 6039 if( bUpdate==0 ){ 6040 rc = arExecSql(pAr, zDrop); 6041 if( rc!=SQLITE_OK ) goto end_ar_transaction; 6042 } 6043 rc = arExecSql(pAr, zCreate); 6044 } 6045 if( bOnlyIfChanged ){ 6046 zExists = sqlite3_mprintf( 6047 " AND NOT EXISTS(" 6048 "SELECT 1 FROM %s AS mem" 6049 " WHERE mem.name=disk.name" 6050 " AND mem.mtime=disk.mtime" 6051 " AND mem.mode=disk.mode)", zTab); 6052 }else{ 6053 zExists = sqlite3_mprintf(""); 6054 } 6055 if( zExists==0 ) rc = SQLITE_NOMEM; 6056 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6057 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, 6058 pAr->bVerbose ? "shell_putsnl(name)" : "name", 6059 pAr->azArg[i], pAr->zDir, zExists); 6060 rc = arExecSql(pAr, zSql2); 6061 sqlite3_free(zSql2); 6062 } 6063end_ar_transaction: 6064 if( rc!=SQLITE_OK ){ 6065 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 6066 }else{ 6067 rc = arExecSql(pAr, "RELEASE ar;"); 6068 if( pAr->bZip && pAr->zFile ){ 6069 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); 6070 arExecSql(pAr, zSql); 6071 sqlite3_free(zSql); 6072 } 6073 } 6074 sqlite3_free(zExists); 6075 return rc; 6076} 6077 6078/* 6079** Implementation of ".ar" dot command. 6080*/ 6081static int arDotCommand( 6082 ShellState *pState, /* Current shell tool state */ 6083 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ 6084 char **azArg, /* Array of arguments passed to dot command */ 6085 int nArg /* Number of entries in azArg[] */ 6086){ 6087 ArCommand cmd; 6088 int rc; 6089 memset(&cmd, 0, sizeof(cmd)); 6090 cmd.fromCmdLine = fromCmdLine; 6091 rc = arParseCommand(azArg, nArg, &cmd); 6092 if( rc==SQLITE_OK ){ 6093 int eDbType = SHELL_OPEN_UNSPEC; 6094 cmd.p = pState; 6095 cmd.db = pState->db; 6096 if( cmd.zFile ){ 6097 eDbType = deduceDatabaseType(cmd.zFile, 1); 6098 }else{ 6099 eDbType = pState->openMode; 6100 } 6101 if( eDbType==SHELL_OPEN_ZIPFILE ){ 6102 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ 6103 if( cmd.zFile==0 ){ 6104 cmd.zSrcTable = sqlite3_mprintf("zip"); 6105 }else{ 6106 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); 6107 } 6108 } 6109 cmd.bZip = 1; 6110 }else if( cmd.zFile ){ 6111 int flags; 6112 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; 6113 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 6114 || cmd.eCmd==AR_CMD_UPDATE ){ 6115 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 6116 }else{ 6117 flags = SQLITE_OPEN_READONLY; 6118 } 6119 cmd.db = 0; 6120 if( cmd.bDryRun ){ 6121 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, 6122 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); 6123 } 6124 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 6125 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); 6126 if( rc!=SQLITE_OK ){ 6127 utf8_printf(stderr, "cannot open file: %s (%s)\n", 6128 cmd.zFile, sqlite3_errmsg(cmd.db) 6129 ); 6130 goto end_ar_command; 6131 } 6132 sqlite3_fileio_init(cmd.db, 0, 0); 6133 sqlite3_sqlar_init(cmd.db, 0, 0); 6134 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, 6135 shellPutsFunc, 0, 0); 6136 6137 } 6138 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ 6139 if( cmd.eCmd!=AR_CMD_CREATE 6140 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) 6141 ){ 6142 utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); 6143 rc = SQLITE_ERROR; 6144 goto end_ar_command; 6145 } 6146 cmd.zSrcTable = sqlite3_mprintf("sqlar"); 6147 } 6148 6149 switch( cmd.eCmd ){ 6150 case AR_CMD_CREATE: 6151 rc = arCreateOrUpdateCommand(&cmd, 0, 0); 6152 break; 6153 6154 case AR_CMD_EXTRACT: 6155 rc = arExtractCommand(&cmd); 6156 break; 6157 6158 case AR_CMD_LIST: 6159 rc = arListCommand(&cmd); 6160 break; 6161 6162 case AR_CMD_HELP: 6163 arUsage(pState->out); 6164 break; 6165 6166 case AR_CMD_INSERT: 6167 rc = arCreateOrUpdateCommand(&cmd, 1, 0); 6168 break; 6169 6170 default: 6171 assert( cmd.eCmd==AR_CMD_UPDATE ); 6172 rc = arCreateOrUpdateCommand(&cmd, 1, 1); 6173 break; 6174 } 6175 } 6176end_ar_command: 6177 if( cmd.db!=pState->db ){ 6178 close_db(cmd.db); 6179 } 6180 sqlite3_free(cmd.zSrcTable); 6181 6182 return rc; 6183} 6184/* End of the ".archive" or ".ar" command logic 6185**********************************************************************************/ 6186#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ 6187 6188#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 6189/* 6190** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op. 6191** Otherwise, the SQL statement or statements in zSql are executed using 6192** database connection db and the error code written to *pRc before 6193** this function returns. 6194*/ 6195static void shellExec(sqlite3 *db, int *pRc, const char *zSql){ 6196 int rc = *pRc; 6197 if( rc==SQLITE_OK ){ 6198 char *zErr = 0; 6199 rc = sqlite3_exec(db, zSql, 0, 0, &zErr); 6200 if( rc!=SQLITE_OK ){ 6201 raw_printf(stderr, "SQL error: %s\n", zErr); 6202 } 6203 *pRc = rc; 6204 } 6205} 6206 6207/* 6208** Like shellExec(), except that zFmt is a printf() style format string. 6209*/ 6210static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){ 6211 char *z = 0; 6212 if( *pRc==SQLITE_OK ){ 6213 va_list ap; 6214 va_start(ap, zFmt); 6215 z = sqlite3_vmprintf(zFmt, ap); 6216 va_end(ap); 6217 if( z==0 ){ 6218 *pRc = SQLITE_NOMEM; 6219 }else{ 6220 shellExec(db, pRc, z); 6221 } 6222 sqlite3_free(z); 6223 } 6224} 6225 6226/* 6227** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6228** Otherwise, an attempt is made to allocate, zero and return a pointer 6229** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set 6230** to SQLITE_NOMEM and NULL returned. 6231*/ 6232static void *shellMalloc(int *pRc, sqlite3_int64 nByte){ 6233 void *pRet = 0; 6234 if( *pRc==SQLITE_OK ){ 6235 pRet = sqlite3_malloc64(nByte); 6236 if( pRet==0 ){ 6237 *pRc = SQLITE_NOMEM; 6238 }else{ 6239 memset(pRet, 0, nByte); 6240 } 6241 } 6242 return pRet; 6243} 6244 6245/* 6246** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6247** Otherwise, zFmt is treated as a printf() style string. The result of 6248** formatting it along with any trailing arguments is written into a 6249** buffer obtained from sqlite3_malloc(), and pointer to which is returned. 6250** It is the responsibility of the caller to eventually free this buffer 6251** using a call to sqlite3_free(). 6252** 6253** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL 6254** pointer returned. 6255*/ 6256static char *shellMPrintf(int *pRc, const char *zFmt, ...){ 6257 char *z = 0; 6258 if( *pRc==SQLITE_OK ){ 6259 va_list ap; 6260 va_start(ap, zFmt); 6261 z = sqlite3_vmprintf(zFmt, ap); 6262 va_end(ap); 6263 if( z==0 ){ 6264 *pRc = SQLITE_NOMEM; 6265 } 6266 } 6267 return z; 6268} 6269 6270/* 6271** When running the ".recover" command, each output table, and the special 6272** orphaned row table if it is required, is represented by an instance 6273** of the following struct. 6274*/ 6275typedef struct RecoverTable RecoverTable; 6276struct RecoverTable { 6277 char *zQuoted; /* Quoted version of table name */ 6278 int nCol; /* Number of columns in table */ 6279 char **azlCol; /* Array of column lists */ 6280 int iPk; /* Index of IPK column */ 6281}; 6282 6283/* 6284** Free a RecoverTable object allocated by recoverFindTable() or 6285** recoverOrphanTable(). 6286*/ 6287static void recoverFreeTable(RecoverTable *pTab){ 6288 if( pTab ){ 6289 sqlite3_free(pTab->zQuoted); 6290 if( pTab->azlCol ){ 6291 int i; 6292 for(i=0; i<=pTab->nCol; i++){ 6293 sqlite3_free(pTab->azlCol[i]); 6294 } 6295 sqlite3_free(pTab->azlCol); 6296 } 6297 sqlite3_free(pTab); 6298 } 6299} 6300 6301/* 6302** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. 6303** Otherwise, it allocates and returns a RecoverTable object based on the 6304** final four arguments passed to this function. It is the responsibility 6305** of the caller to eventually free the returned object using 6306** recoverFreeTable(). 6307*/ 6308static RecoverTable *recoverNewTable( 6309 int *pRc, /* IN/OUT: Error code */ 6310 const char *zName, /* Name of table */ 6311 const char *zSql, /* CREATE TABLE statement */ 6312 int bIntkey, 6313 int nCol 6314){ 6315 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */ 6316 int rc = *pRc; 6317 RecoverTable *pTab = 0; 6318 6319 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable)); 6320 if( rc==SQLITE_OK ){ 6321 int nSqlCol = 0; 6322 int bSqlIntkey = 0; 6323 sqlite3_stmt *pStmt = 0; 6324 6325 rc = sqlite3_open("", &dbtmp); 6326 if( rc==SQLITE_OK ){ 6327 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0); 6328 } 6329 if( rc==SQLITE_OK ){ 6330 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0); 6331 if( rc==SQLITE_ERROR ){ 6332 rc = SQLITE_OK; 6333 goto finished; 6334 } 6335 } 6336 shellPreparePrintf(dbtmp, &rc, &pStmt, 6337 "SELECT count(*) FROM pragma_table_info(%Q)", zName 6338 ); 6339 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6340 nSqlCol = sqlite3_column_int(pStmt, 0); 6341 } 6342 shellFinalize(&rc, pStmt); 6343 6344 if( rc!=SQLITE_OK || nSqlCol<nCol ){ 6345 goto finished; 6346 } 6347 6348 shellPreparePrintf(dbtmp, &rc, &pStmt, 6349 "SELECT (" 6350 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage" 6351 ") FROM sqlite_master WHERE name = %Q", zName 6352 ); 6353 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6354 bSqlIntkey = sqlite3_column_int(pStmt, 0); 6355 } 6356 shellFinalize(&rc, pStmt); 6357 6358 if( bIntkey==bSqlIntkey ){ 6359 int i; 6360 const char *zPk = "_rowid_"; 6361 sqlite3_stmt *pPkFinder = 0; 6362 6363 /* If this is an intkey table and there is an INTEGER PRIMARY KEY, 6364 ** set zPk to the name of the PK column, and pTab->iPk to the index 6365 ** of the column, where columns are 0-numbered from left to right. 6366 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column, 6367 ** leave zPk as "_rowid_" and pTab->iPk at -2. */ 6368 pTab->iPk = -2; 6369 if( bIntkey ){ 6370 shellPreparePrintf(dbtmp, &rc, &pPkFinder, 6371 "SELECT cid, name FROM pragma_table_info(%Q) " 6372 " WHERE pk=1 AND type='integer' COLLATE nocase" 6373 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)" 6374 , zName, zName 6375 ); 6376 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){ 6377 pTab->iPk = sqlite3_column_int(pPkFinder, 0); 6378 zPk = (const char*)sqlite3_column_text(pPkFinder, 1); 6379 } 6380 } 6381 6382 pTab->zQuoted = shellMPrintf(&rc, "%Q", zName); 6383 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1)); 6384 pTab->nCol = nSqlCol; 6385 6386 if( bIntkey ){ 6387 pTab->azlCol[0] = shellMPrintf(&rc, "%Q", zPk); 6388 }else{ 6389 pTab->azlCol[0] = shellMPrintf(&rc, ""); 6390 } 6391 i = 1; 6392 shellPreparePrintf(dbtmp, &rc, &pStmt, 6393 "SELECT %Q || group_concat(name, ', ') " 6394 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) " 6395 "FROM pragma_table_info(%Q)", 6396 bIntkey ? ", " : "", pTab->iPk, 6397 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ", 6398 zName 6399 ); 6400 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6401 const char *zText = (const char*)sqlite3_column_text(pStmt, 0); 6402 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText); 6403 i++; 6404 } 6405 shellFinalize(&rc, pStmt); 6406 6407 shellFinalize(&rc, pPkFinder); 6408 } 6409 } 6410 6411 finished: 6412 sqlite3_close(dbtmp); 6413 *pRc = rc; 6414 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){ 6415 recoverFreeTable(pTab); 6416 pTab = 0; 6417 } 6418 return pTab; 6419} 6420 6421/* 6422** This function is called to search the schema recovered from the 6423** sqlite_master table of the (possibly) corrupt database as part 6424** of a ".recover" command. Specifically, for a table with root page 6425** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the 6426** table must be a WITHOUT ROWID table, or if non-zero, not one of 6427** those. 6428** 6429** If a table is found, a (RecoverTable*) object is returned. Or, if 6430** no such table is found, but bIntkey is false and iRoot is the 6431** root page of an index in the recovered schema, then (*pbNoop) is 6432** set to true and NULL returned. Or, if there is no such table or 6433** index, NULL is returned and (*pbNoop) set to 0, indicating that 6434** the caller should write data to the orphans table. 6435*/ 6436static RecoverTable *recoverFindTable( 6437 ShellState *pState, /* Shell state object */ 6438 int *pRc, /* IN/OUT: Error code */ 6439 int iRoot, /* Root page of table */ 6440 int bIntkey, /* True for an intkey table */ 6441 int nCol, /* Number of columns in table */ 6442 int *pbNoop /* OUT: True if iRoot is root of index */ 6443){ 6444 sqlite3_stmt *pStmt = 0; 6445 RecoverTable *pRet = 0; 6446 int bNoop = 0; 6447 const char *zSql = 0; 6448 const char *zName = 0; 6449 6450 /* Search the recovered schema for an object with root page iRoot. */ 6451 shellPreparePrintf(pState->db, pRc, &pStmt, 6452 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot 6453 ); 6454 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6455 const char *zType = (const char*)sqlite3_column_text(pStmt, 0); 6456 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){ 6457 bNoop = 1; 6458 break; 6459 } 6460 if( sqlite3_stricmp(zType, "table")==0 ){ 6461 zName = (const char*)sqlite3_column_text(pStmt, 1); 6462 zSql = (const char*)sqlite3_column_text(pStmt, 2); 6463 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol); 6464 break; 6465 } 6466 } 6467 6468 shellFinalize(pRc, pStmt); 6469 *pbNoop = bNoop; 6470 return pRet; 6471} 6472 6473/* 6474** Return a RecoverTable object representing the orphans table. 6475*/ 6476static RecoverTable *recoverOrphanTable( 6477 ShellState *pState, /* Shell state object */ 6478 int *pRc, /* IN/OUT: Error code */ 6479 const char *zLostAndFound, /* Base name for orphans table */ 6480 int nCol /* Number of user data columns */ 6481){ 6482 RecoverTable *pTab = 0; 6483 if( nCol>=0 && *pRc==SQLITE_OK ){ 6484 int i; 6485 6486 /* This block determines the name of the orphan table. The prefered 6487 ** name is zLostAndFound. But if that clashes with another name 6488 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1 6489 ** and so on until a non-clashing name is found. */ 6490 int iTab = 0; 6491 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound); 6492 sqlite3_stmt *pTest = 0; 6493 shellPrepare(pState->db, pRc, 6494 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest 6495 ); 6496 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 6497 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){ 6498 shellReset(pRc, pTest); 6499 sqlite3_free(zTab); 6500 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++); 6501 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 6502 } 6503 shellFinalize(pRc, pTest); 6504 6505 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable)); 6506 if( pTab ){ 6507 pTab->zQuoted = shellMPrintf(pRc, "%Q", zTab); 6508 pTab->nCol = nCol; 6509 pTab->iPk = -2; 6510 if( nCol>0 ){ 6511 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1)); 6512 if( pTab->azlCol ){ 6513 pTab->azlCol[nCol] = shellMPrintf(pRc, ""); 6514 for(i=nCol-1; i>=0; i--){ 6515 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]); 6516 } 6517 } 6518 } 6519 6520 if( *pRc!=SQLITE_OK ){ 6521 recoverFreeTable(pTab); 6522 pTab = 0; 6523 }else{ 6524 raw_printf(pState->out, 6525 "CREATE TABLE %s(rootpgno INTEGER, " 6526 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted 6527 ); 6528 for(i=0; i<nCol; i++){ 6529 raw_printf(pState->out, ", c%d", i); 6530 } 6531 raw_printf(pState->out, ");\n"); 6532 } 6533 } 6534 sqlite3_free(zTab); 6535 } 6536 return pTab; 6537} 6538 6539/* 6540** This function is called to recover data from the database. A script 6541** to construct a new database containing all recovered data is output 6542** on stream pState->out. 6543*/ 6544static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ 6545 int rc = SQLITE_OK; 6546 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */ 6547 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */ 6548 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */ 6549 const char *zRecoveryDb = ""; /* Name of "recovery" database */ 6550 const char *zLostAndFound = "lost_and_found"; 6551 int i; 6552 int nOrphan = -1; 6553 RecoverTable *pOrphan = 0; 6554 6555 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */ 6556 for(i=1; i<nArg; i++){ 6557 char *z = azArg[i]; 6558 int n; 6559 if( z[0]=='-' && z[1]=='-' ) z++; 6560 n = strlen(z); 6561 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){ 6562 bFreelist = 0; 6563 }else 6564 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ 6565 i++; 6566 zRecoveryDb = azArg[i]; 6567 }else 6568 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ 6569 i++; 6570 zLostAndFound = azArg[i]; 6571 } 6572 else{ 6573 raw_printf(stderr, "unexpected option: %s\n", azArg[i]); 6574 raw_printf(stderr, "options are:\n"); 6575 raw_printf(stderr, " --freelist-corrupt\n"); 6576 raw_printf(stderr, " --recovery-db DATABASE\n"); 6577 raw_printf(stderr, " --lost-and-found TABLE-NAME\n"); 6578 return 1; 6579 } 6580 } 6581 6582 shellExecPrintf(pState->db, &rc, 6583 /* Attach an in-memory database named 'recovery'. Create an indexed 6584 ** cache of the sqlite_dbptr virtual table. */ 6585 "ATTACH %Q AS recovery;" 6586 "DROP TABLE IF EXISTS recovery.dbptr;" 6587 "DROP TABLE IF EXISTS recovery.freelist;" 6588 "DROP TABLE IF EXISTS recovery.map;" 6589 "DROP TABLE IF EXISTS recovery.schema;" 6590 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb 6591 ); 6592 6593 if( bFreelist ){ 6594 shellExec(pState->db, &rc, 6595 "WITH trunk(pgno) AS (" 6596 " SELECT shell_int32(" 6597 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x " 6598 " WHERE x>0" 6599 " UNION" 6600 " SELECT shell_int32(" 6601 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x " 6602 " FROM trunk WHERE x>0" 6603 ")," 6604 "freelist(data, n, freepgno) AS (" 6605 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno " 6606 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno" 6607 " UNION ALL" 6608 " SELECT data, n-1, shell_int32(data, 2+n) " 6609 " FROM freelist WHERE n>=0" 6610 ")" 6611 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;" 6612 ); 6613 } 6614 6615 shellExec(pState->db, &rc, 6616 "CREATE TABLE recovery.dbptr(" 6617 " pgno, child, PRIMARY KEY(child, pgno)" 6618 ") WITHOUT ROWID;" 6619 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) " 6620 " SELECT * FROM sqlite_dbptr" 6621 " WHERE pgno NOT IN freelist AND child NOT IN freelist;" 6622 6623 /* Delete any pointer to page 1. This ensures that page 1 is considered 6624 ** a root page, regardless of how corrupt the db is. */ 6625 "DELETE FROM recovery.dbptr WHERE child = 1;" 6626 6627 /* Delete all pointers to any pages that have more than one pointer 6628 ** to them. Such pages will be treated as root pages when recovering 6629 ** data. */ 6630 "DELETE FROM recovery.dbptr WHERE child IN (" 6631 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1" 6632 ");" 6633 6634 /* Create the "map" table that will (eventually) contain instructions 6635 ** for dealing with each page in the db that contains one or more 6636 ** records. */ 6637 "CREATE TABLE recovery.map(" 6638 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT" 6639 ");" 6640 6641 /* Populate table [map]. If there are circular loops of pages in the 6642 ** database, the following adds all pages in such a loop to the map 6643 ** as individual root pages. This could be handled better. */ 6644 "WITH pages(i, maxlen) AS (" 6645 " SELECT page_count, (" 6646 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count" 6647 " ) FROM pragma_page_count WHERE page_count>0" 6648 " UNION ALL" 6649 " SELECT i-1, (" 6650 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1" 6651 " ) FROM pages WHERE i>=2" 6652 ")" 6653 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) " 6654 " SELECT i, maxlen, NULL, (" 6655 " WITH p(orig, pgno, parent) AS (" 6656 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)" 6657 " UNION " 6658 " SELECT i, p.parent, " 6659 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p" 6660 " )" 6661 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)" 6662 ") " 6663 "FROM pages WHERE maxlen > 0 AND i NOT IN freelist;" 6664 "UPDATE recovery.map AS o SET intkey = (" 6665 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno" 6666 ");" 6667 6668 /* Extract data from page 1 and any linked pages into table 6669 ** recovery.schema. With the same schema as an sqlite_master table. */ 6670 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);" 6671 "INSERT INTO recovery.schema SELECT " 6672 " max(CASE WHEN field=0 THEN value ELSE NULL END)," 6673 " max(CASE WHEN field=1 THEN value ELSE NULL END)," 6674 " max(CASE WHEN field=2 THEN value ELSE NULL END)," 6675 " max(CASE WHEN field=3 THEN value ELSE NULL END)," 6676 " max(CASE WHEN field=4 THEN value ELSE NULL END)" 6677 "FROM sqlite_dbdata WHERE pgno IN (" 6678 " SELECT pgno FROM recovery.map WHERE root=1" 6679 ")" 6680 "GROUP BY pgno, cell;" 6681 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);" 6682 ); 6683 6684 /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 6685 ** CREATE TABLE statements that extracted from the existing schema. */ 6686 if( rc==SQLITE_OK ){ 6687 sqlite3_stmt *pStmt = 0; 6688 raw_printf(pState->out, "BEGIN;\n"); 6689 raw_printf(pState->out, "PRAGMA writable_schema = on;\n"); 6690 shellPrepare(pState->db, &rc, 6691 "SELECT sql FROM recovery.schema " 6692 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt 6693 ); 6694 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6695 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0); 6696 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 6697 &zCreateTable[12] 6698 ); 6699 } 6700 shellFinalize(&rc, pStmt); 6701 } 6702 6703 /* Figure out if an orphan table will be required. And if so, how many 6704 ** user columns it should contain */ 6705 shellPrepare(pState->db, &rc, 6706 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1" 6707 , &pLoop 6708 ); 6709 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 6710 nOrphan = sqlite3_column_int(pLoop, 0); 6711 } 6712 shellFinalize(&rc, pLoop); 6713 pLoop = 0; 6714 6715 shellPrepare(pState->db, &rc, 6716 "SELECT pgno FROM recovery.map WHERE root=?", &pPages 6717 ); 6718 shellPrepare(pState->db, &rc, 6719 "SELECT max(field), group_concat(shell_escape_crnl(quote(value)), ', ')" 6720 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?" 6721 "GROUP BY cell", &pCells 6722 ); 6723 6724 /* Loop through each root page. */ 6725 shellPrepare(pState->db, &rc, 6726 "SELECT root, intkey, max(maxlen) FROM recovery.map" 6727 " WHERE root>1 GROUP BY root, intkey ORDER BY root=(" 6728 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'" 6729 ")", &pLoop 6730 ); 6731 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 6732 int iRoot = sqlite3_column_int(pLoop, 0); 6733 int bIntkey = sqlite3_column_int(pLoop, 1); 6734 int nCol = sqlite3_column_int(pLoop, 2); 6735 int bNoop = 0; 6736 RecoverTable *pTab; 6737 6738 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop); 6739 if( bNoop || rc ) continue; 6740 if( pTab==0 ){ 6741 if( pOrphan==0 ){ 6742 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 6743 } 6744 pTab = pOrphan; 6745 if( pTab==0 ) break; 6746 } 6747 6748 if( 0==sqlite3_stricmp(pTab->zQuoted, "'sqlite_sequence'") ){ 6749 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n"); 6750 } 6751 sqlite3_bind_int(pPages, 1, iRoot); 6752 sqlite3_bind_int(pCells, 2, pTab->iPk); 6753 6754 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){ 6755 int iPgno = sqlite3_column_int(pPages, 0); 6756 sqlite3_bind_int(pCells, 1, iPgno); 6757 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){ 6758 int nField = sqlite3_column_int(pCells, 0); 6759 const char *zVal = (const char*)sqlite3_column_text(pCells, 1); 6760 6761 nField = nField+1; 6762 if( pTab==pOrphan ){ 6763 raw_printf(pState->out, 6764 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n", 6765 pTab->zQuoted, iRoot, iPgno, nField, 6766 bIntkey ? "" : "NULL, ", zVal, pTab->azlCol[nField] 6767 ); 6768 }else{ 6769 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 6770 pTab->zQuoted, pTab->azlCol[nField], zVal 6771 ); 6772 } 6773 } 6774 shellReset(&rc, pCells); 6775 } 6776 shellReset(&rc, pPages); 6777 if( pTab!=pOrphan ) recoverFreeTable(pTab); 6778 } 6779 shellFinalize(&rc, pLoop); 6780 shellFinalize(&rc, pPages); 6781 shellFinalize(&rc, pCells); 6782 recoverFreeTable(pOrphan); 6783 6784 /* The rest of the schema */ 6785 if( rc==SQLITE_OK ){ 6786 sqlite3_stmt *pStmt = 0; 6787 shellPrepare(pState->db, &rc, 6788 "SELECT sql, name FROM recovery.schema " 6789 "WHERE sql NOT LIKE 'create table%'", &pStmt 6790 ); 6791 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6792 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0); 6793 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){ 6794 const char *zName = (const char*)sqlite3_column_text(pStmt, 1); 6795 char *zPrint = shellMPrintf(&rc, 6796 "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)", 6797 zName, zName, zSql 6798 ); 6799 raw_printf(pState->out, "%s;\n", zPrint); 6800 sqlite3_free(zPrint); 6801 }else{ 6802 raw_printf(pState->out, "%s;\n", zSql); 6803 } 6804 } 6805 shellFinalize(&rc, pStmt); 6806 } 6807 6808 if( rc==SQLITE_OK ){ 6809 raw_printf(pState->out, "PRAGMA writable_schema = off;\n"); 6810 raw_printf(pState->out, "COMMIT;\n"); 6811 } 6812 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0); 6813 return rc; 6814} 6815#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 6816 6817 6818/* 6819** If an input line begins with "." then invoke this routine to 6820** process that line. 6821** 6822** Return 1 on error, 2 to exit, and 0 otherwise. 6823*/ 6824static int do_meta_command(char *zLine, ShellState *p){ 6825 int h = 1; 6826 int nArg = 0; 6827 int n, c; 6828 int rc = 0; 6829 char *azArg[50]; 6830 6831#ifndef SQLITE_OMIT_VIRTUALTABLE 6832 if( p->expert.pExpert ){ 6833 expertFinish(p, 1, 0); 6834 } 6835#endif 6836 6837 /* Parse the input line into tokens. 6838 */ 6839 while( zLine[h] && nArg<ArraySize(azArg) ){ 6840 while( IsSpace(zLine[h]) ){ h++; } 6841 if( zLine[h]==0 ) break; 6842 if( zLine[h]=='\'' || zLine[h]=='"' ){ 6843 int delim = zLine[h++]; 6844 azArg[nArg++] = &zLine[h]; 6845 while( zLine[h] && zLine[h]!=delim ){ 6846 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; 6847 h++; 6848 } 6849 if( zLine[h]==delim ){ 6850 zLine[h++] = 0; 6851 } 6852 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); 6853 }else{ 6854 azArg[nArg++] = &zLine[h]; 6855 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } 6856 if( zLine[h] ) zLine[h++] = 0; 6857 resolve_backslashes(azArg[nArg-1]); 6858 } 6859 } 6860 6861 /* Process the input line. 6862 */ 6863 if( nArg==0 ) return 0; /* no tokens, no error */ 6864 n = strlen30(azArg[0]); 6865 c = azArg[0][0]; 6866 clearTempFile(p); 6867 6868#ifndef SQLITE_OMIT_AUTHORIZATION 6869 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){ 6870 if( nArg!=2 ){ 6871 raw_printf(stderr, "Usage: .auth ON|OFF\n"); 6872 rc = 1; 6873 goto meta_command_exit; 6874 } 6875 open_db(p, 0); 6876 if( booleanValue(azArg[1]) ){ 6877 sqlite3_set_authorizer(p->db, shellAuth, p); 6878 }else{ 6879 sqlite3_set_authorizer(p->db, 0, 0); 6880 } 6881 }else 6882#endif 6883 6884#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 6885 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){ 6886 open_db(p, 0); 6887 rc = arDotCommand(p, 0, azArg, nArg); 6888 }else 6889#endif 6890 6891 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) 6892 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) 6893 ){ 6894 const char *zDestFile = 0; 6895 const char *zDb = 0; 6896 sqlite3 *pDest; 6897 sqlite3_backup *pBackup; 6898 int j; 6899 int bAsync = 0; 6900 const char *zVfs = 0; 6901 for(j=1; j<nArg; j++){ 6902 const char *z = azArg[j]; 6903 if( z[0]=='-' ){ 6904 if( z[1]=='-' ) z++; 6905 if( strcmp(z, "-append")==0 ){ 6906 zVfs = "apndvfs"; 6907 }else 6908 if( strcmp(z, "-async")==0 ){ 6909 bAsync = 1; 6910 }else 6911 { 6912 utf8_printf(stderr, "unknown option: %s\n", azArg[j]); 6913 return 1; 6914 } 6915 }else if( zDestFile==0 ){ 6916 zDestFile = azArg[j]; 6917 }else if( zDb==0 ){ 6918 zDb = zDestFile; 6919 zDestFile = azArg[j]; 6920 }else{ 6921 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n"); 6922 return 1; 6923 } 6924 } 6925 if( zDestFile==0 ){ 6926 raw_printf(stderr, "missing FILENAME argument on .backup\n"); 6927 return 1; 6928 } 6929 if( zDb==0 ) zDb = "main"; 6930 rc = sqlite3_open_v2(zDestFile, &pDest, 6931 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs); 6932 if( rc!=SQLITE_OK ){ 6933 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); 6934 close_db(pDest); 6935 return 1; 6936 } 6937 if( bAsync ){ 6938 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;", 6939 0, 0, 0); 6940 } 6941 open_db(p, 0); 6942 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); 6943 if( pBackup==0 ){ 6944 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 6945 close_db(pDest); 6946 return 1; 6947 } 6948 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} 6949 sqlite3_backup_finish(pBackup); 6950 if( rc==SQLITE_DONE ){ 6951 rc = 0; 6952 }else{ 6953 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 6954 rc = 1; 6955 } 6956 close_db(pDest); 6957 }else 6958 6959 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ 6960 if( nArg==2 ){ 6961 bail_on_error = booleanValue(azArg[1]); 6962 }else{ 6963 raw_printf(stderr, "Usage: .bail on|off\n"); 6964 rc = 1; 6965 } 6966 }else 6967 6968 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ 6969 if( nArg==2 ){ 6970 if( booleanValue(azArg[1]) ){ 6971 setBinaryMode(p->out, 1); 6972 }else{ 6973 setTextMode(p->out, 1); 6974 } 6975 }else{ 6976 raw_printf(stderr, "Usage: .binary on|off\n"); 6977 rc = 1; 6978 } 6979 }else 6980 6981 if( c=='c' && strcmp(azArg[0],"cd")==0 ){ 6982 if( nArg==2 ){ 6983#if defined(_WIN32) || defined(WIN32) 6984 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); 6985 rc = !SetCurrentDirectoryW(z); 6986 sqlite3_free(z); 6987#else 6988 rc = chdir(azArg[1]); 6989#endif 6990 if( rc ){ 6991 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); 6992 rc = 1; 6993 } 6994 }else{ 6995 raw_printf(stderr, "Usage: .cd DIRECTORY\n"); 6996 rc = 1; 6997 } 6998 }else 6999 7000 /* The undocumented ".breakpoint" command causes a call to the no-op 7001 ** routine named test_breakpoint(). 7002 */ 7003 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ 7004 test_breakpoint(); 7005 }else 7006 7007 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ 7008 if( nArg==2 ){ 7009 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); 7010 }else{ 7011 raw_printf(stderr, "Usage: .changes on|off\n"); 7012 rc = 1; 7013 } 7014 }else 7015 7016 /* Cancel output redirection, if it is currently set (by .testcase) 7017 ** Then read the content of the testcase-out.txt file and compare against 7018 ** azArg[1]. If there are differences, report an error and exit. 7019 */ 7020 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){ 7021 char *zRes = 0; 7022 output_reset(p); 7023 if( nArg!=2 ){ 7024 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); 7025 rc = 2; 7026 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ 7027 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); 7028 rc = 2; 7029 }else if( testcase_glob(azArg[1],zRes)==0 ){ 7030 utf8_printf(stderr, 7031 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", 7032 p->zTestcase, azArg[1], zRes); 7033 rc = 1; 7034 }else{ 7035 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); 7036 p->nCheck++; 7037 } 7038 sqlite3_free(zRes); 7039 }else 7040 7041 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ 7042 if( nArg==2 ){ 7043 tryToClone(p, azArg[1]); 7044 }else{ 7045 raw_printf(stderr, "Usage: .clone FILENAME\n"); 7046 rc = 1; 7047 } 7048 }else 7049 7050 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ 7051 ShellState data; 7052 char *zErrMsg = 0; 7053 open_db(p, 0); 7054 memcpy(&data, p, sizeof(data)); 7055 data.showHeader = 0; 7056 data.cMode = data.mode = MODE_List; 7057 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": "); 7058 data.cnt = 0; 7059 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list", 7060 callback, &data, &zErrMsg); 7061 if( zErrMsg ){ 7062 utf8_printf(stderr,"Error: %s\n", zErrMsg); 7063 sqlite3_free(zErrMsg); 7064 rc = 1; 7065 } 7066 }else 7067 7068 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){ 7069 static const struct DbConfigChoices { 7070 const char *zName; 7071 int op; 7072 } aDbConfig[] = { 7073 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, 7074 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, 7075 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, 7076 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, 7077 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, 7078 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, 7079 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, 7080 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, 7081 { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, 7082 }; 7083 int ii, v; 7084 open_db(p, 0); 7085 for(ii=0; ii<ArraySize(aDbConfig); ii++){ 7086 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; 7087 if( nArg>=3 ){ 7088 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); 7089 } 7090 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); 7091 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off"); 7092 if( nArg>1 ) break; 7093 } 7094 if( nArg>1 && ii==ArraySize(aDbConfig) ){ 7095 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]); 7096 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n"); 7097 } 7098 }else 7099 7100 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){ 7101 rc = shell_dbinfo_command(p, nArg, azArg); 7102 }else 7103 7104#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 7105 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){ 7106 open_db(p, 0); 7107 rc = recoverDatabaseCmd(p, nArg, azArg); 7108 }else 7109#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 7110 7111 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ 7112 const char *zLike = 0; 7113 int i; 7114 int savedShowHeader = p->showHeader; 7115 int savedShellFlags = p->shellFlgs; 7116 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo); 7117 for(i=1; i<nArg; i++){ 7118 if( azArg[i][0]=='-' ){ 7119 const char *z = azArg[i]+1; 7120 if( z[0]=='-' ) z++; 7121 if( strcmp(z,"preserve-rowids")==0 ){ 7122#ifdef SQLITE_OMIT_VIRTUALTABLE 7123 raw_printf(stderr, "The --preserve-rowids option is not compatible" 7124 " with SQLITE_OMIT_VIRTUALTABLE\n"); 7125 rc = 1; 7126 goto meta_command_exit; 7127#else 7128 ShellSetFlag(p, SHFLG_PreserveRowid); 7129#endif 7130 }else 7131 if( strcmp(z,"newlines")==0 ){ 7132 ShellSetFlag(p, SHFLG_Newlines); 7133 }else 7134 { 7135 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]); 7136 rc = 1; 7137 goto meta_command_exit; 7138 } 7139 }else if( zLike ){ 7140 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? " 7141 "?--newlines? ?LIKE-PATTERN?\n"); 7142 rc = 1; 7143 goto meta_command_exit; 7144 }else{ 7145 zLike = azArg[i]; 7146 } 7147 } 7148 7149 open_db(p, 0); 7150 7151 /* When playing back a "dump", the content might appear in an order 7152 ** which causes immediate foreign key constraints to be violated. 7153 ** So disable foreign-key constraint enforcement to prevent problems. */ 7154 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); 7155 raw_printf(p->out, "BEGIN TRANSACTION;\n"); 7156 p->writableSchema = 0; 7157 p->showHeader = 0; 7158 /* Set writable_schema=ON since doing so forces SQLite to initialize 7159 ** as much of the schema as it can even if the sqlite_master table is 7160 ** corrupt. */ 7161 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); 7162 p->nErr = 0; 7163 if( zLike==0 ){ 7164 run_schema_dump_query(p, 7165 "SELECT name, type, sql FROM sqlite_master " 7166 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" 7167 ); 7168 run_schema_dump_query(p, 7169 "SELECT name, type, sql FROM sqlite_master " 7170 "WHERE name=='sqlite_sequence'" 7171 ); 7172 run_table_dump_query(p, 7173 "SELECT sql FROM sqlite_master " 7174 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 7175 ); 7176 }else{ 7177 char *zSql; 7178 zSql = sqlite3_mprintf( 7179 "SELECT name, type, sql FROM sqlite_master " 7180 "WHERE tbl_name LIKE %Q AND type=='table'" 7181 " AND sql NOT NULL", zLike); 7182 run_schema_dump_query(p,zSql); 7183 sqlite3_free(zSql); 7184 zSql = sqlite3_mprintf( 7185 "SELECT sql FROM sqlite_master " 7186 "WHERE sql NOT NULL" 7187 " AND type IN ('index','trigger','view')" 7188 " AND tbl_name LIKE %Q", zLike); 7189 run_table_dump_query(p, zSql, 0); 7190 sqlite3_free(zSql); 7191 } 7192 if( p->writableSchema ){ 7193 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); 7194 p->writableSchema = 0; 7195 } 7196 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 7197 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); 7198 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); 7199 p->showHeader = savedShowHeader; 7200 p->shellFlgs = savedShellFlags; 7201 }else 7202 7203 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ 7204 if( nArg==2 ){ 7205 setOrClearFlag(p, SHFLG_Echo, azArg[1]); 7206 }else{ 7207 raw_printf(stderr, "Usage: .echo on|off\n"); 7208 rc = 1; 7209 } 7210 }else 7211 7212 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ 7213 if( nArg==2 ){ 7214 p->autoEQPtest = 0; 7215 if( p->autoEQPtrace ){ 7216 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); 7217 p->autoEQPtrace = 0; 7218 } 7219 if( strcmp(azArg[1],"full")==0 ){ 7220 p->autoEQP = AUTOEQP_full; 7221 }else if( strcmp(azArg[1],"trigger")==0 ){ 7222 p->autoEQP = AUTOEQP_trigger; 7223#ifdef SQLITE_DEBUG 7224 }else if( strcmp(azArg[1],"test")==0 ){ 7225 p->autoEQP = AUTOEQP_on; 7226 p->autoEQPtest = 1; 7227 }else if( strcmp(azArg[1],"trace")==0 ){ 7228 p->autoEQP = AUTOEQP_full; 7229 p->autoEQPtrace = 1; 7230 open_db(p, 0); 7231 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0); 7232 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); 7233#endif 7234 }else{ 7235 p->autoEQP = (u8)booleanValue(azArg[1]); 7236 } 7237 }else{ 7238 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n"); 7239 rc = 1; 7240 } 7241 }else 7242 7243 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ 7244 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); 7245 rc = 2; 7246 }else 7247 7248 /* The ".explain" command is automatic now. It is largely pointless. It 7249 ** retained purely for backwards compatibility */ 7250 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ 7251 int val = 1; 7252 if( nArg>=2 ){ 7253 if( strcmp(azArg[1],"auto")==0 ){ 7254 val = 99; 7255 }else{ 7256 val = booleanValue(azArg[1]); 7257 } 7258 } 7259 if( val==1 && p->mode!=MODE_Explain ){ 7260 p->normalMode = p->mode; 7261 p->mode = MODE_Explain; 7262 p->autoExplain = 0; 7263 }else if( val==0 ){ 7264 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 7265 p->autoExplain = 0; 7266 }else if( val==99 ){ 7267 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 7268 p->autoExplain = 1; 7269 } 7270 }else 7271 7272#ifndef SQLITE_OMIT_VIRTUALTABLE 7273 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){ 7274 open_db(p, 0); 7275 expertDotCommand(p, azArg, nArg); 7276 }else 7277#endif 7278 7279 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ 7280 ShellState data; 7281 char *zErrMsg = 0; 7282 int doStats = 0; 7283 memcpy(&data, p, sizeof(data)); 7284 data.showHeader = 0; 7285 data.cMode = data.mode = MODE_Semi; 7286 if( nArg==2 && optionMatch(azArg[1], "indent") ){ 7287 data.cMode = data.mode = MODE_Pretty; 7288 nArg = 1; 7289 } 7290 if( nArg!=1 ){ 7291 raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); 7292 rc = 1; 7293 goto meta_command_exit; 7294 } 7295 open_db(p, 0); 7296 rc = sqlite3_exec(p->db, 7297 "SELECT sql FROM" 7298 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" 7299 " FROM sqlite_master UNION ALL" 7300 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " 7301 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " 7302 "ORDER BY rowid", 7303 callback, &data, &zErrMsg 7304 ); 7305 if( rc==SQLITE_OK ){ 7306 sqlite3_stmt *pStmt; 7307 rc = sqlite3_prepare_v2(p->db, 7308 "SELECT rowid FROM sqlite_master" 7309 " WHERE name GLOB 'sqlite_stat[134]'", 7310 -1, &pStmt, 0); 7311 doStats = sqlite3_step(pStmt)==SQLITE_ROW; 7312 sqlite3_finalize(pStmt); 7313 } 7314 if( doStats==0 ){ 7315 raw_printf(p->out, "/* No STAT tables available */\n"); 7316 }else{ 7317 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 7318 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'", 7319 callback, &data, &zErrMsg); 7320 data.cMode = data.mode = MODE_Insert; 7321 data.zDestTable = "sqlite_stat1"; 7322 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg); 7323 data.zDestTable = "sqlite_stat3"; 7324 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg); 7325 data.zDestTable = "sqlite_stat4"; 7326 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg); 7327 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 7328 } 7329 }else 7330 7331 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ 7332 if( nArg==2 ){ 7333 p->showHeader = booleanValue(azArg[1]); 7334 }else{ 7335 raw_printf(stderr, "Usage: .headers on|off\n"); 7336 rc = 1; 7337 } 7338 }else 7339 7340 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ 7341 if( nArg>=2 ){ 7342 n = showHelp(p->out, azArg[1]); 7343 if( n==0 ){ 7344 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]); 7345 } 7346 }else{ 7347 showHelp(p->out, 0); 7348 } 7349 }else 7350 7351 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ 7352 char *zTable; /* Insert data into this table */ 7353 char *zFile; /* Name of file to extra content from */ 7354 sqlite3_stmt *pStmt = NULL; /* A statement */ 7355 int nCol; /* Number of columns in the table */ 7356 int nByte; /* Number of bytes in an SQL string */ 7357 int i, j; /* Loop counters */ 7358 int needCommit; /* True to COMMIT or ROLLBACK at end */ 7359 int nSep; /* Number of bytes in p->colSeparator[] */ 7360 char *zSql; /* An SQL statement */ 7361 ImportCtx sCtx; /* Reader context */ 7362 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ 7363 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */ 7364 7365 if( nArg!=3 ){ 7366 raw_printf(stderr, "Usage: .import FILE TABLE\n"); 7367 goto meta_command_exit; 7368 } 7369 zFile = azArg[1]; 7370 zTable = azArg[2]; 7371 seenInterrupt = 0; 7372 memset(&sCtx, 0, sizeof(sCtx)); 7373 open_db(p, 0); 7374 nSep = strlen30(p->colSeparator); 7375 if( nSep==0 ){ 7376 raw_printf(stderr, 7377 "Error: non-null column separator required for import\n"); 7378 return 1; 7379 } 7380 if( nSep>1 ){ 7381 raw_printf(stderr, "Error: multi-character column separators not allowed" 7382 " for import\n"); 7383 return 1; 7384 } 7385 nSep = strlen30(p->rowSeparator); 7386 if( nSep==0 ){ 7387 raw_printf(stderr, "Error: non-null row separator required for import\n"); 7388 return 1; 7389 } 7390 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){ 7391 /* When importing CSV (only), if the row separator is set to the 7392 ** default output row separator, change it to the default input 7393 ** row separator. This avoids having to maintain different input 7394 ** and output row separators. */ 7395 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7396 nSep = strlen30(p->rowSeparator); 7397 } 7398 if( nSep>1 ){ 7399 raw_printf(stderr, "Error: multi-character row separators not allowed" 7400 " for import\n"); 7401 return 1; 7402 } 7403 sCtx.zFile = zFile; 7404 sCtx.nLine = 1; 7405 if( sCtx.zFile[0]=='|' ){ 7406#ifdef SQLITE_OMIT_POPEN 7407 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 7408 return 1; 7409#else 7410 sCtx.in = popen(sCtx.zFile+1, "r"); 7411 sCtx.zFile = "<pipe>"; 7412 xCloser = pclose; 7413#endif 7414 }else{ 7415 sCtx.in = fopen(sCtx.zFile, "rb"); 7416 xCloser = fclose; 7417 } 7418 if( p->mode==MODE_Ascii ){ 7419 xRead = ascii_read_one_field; 7420 }else{ 7421 xRead = csv_read_one_field; 7422 } 7423 if( sCtx.in==0 ){ 7424 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 7425 return 1; 7426 } 7427 sCtx.cColSep = p->colSeparator[0]; 7428 sCtx.cRowSep = p->rowSeparator[0]; 7429 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); 7430 if( zSql==0 ){ 7431 xCloser(sCtx.in); 7432 shell_out_of_memory(); 7433 } 7434 nByte = strlen30(zSql); 7435 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7436 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ 7437 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ 7438 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); 7439 char cSep = '('; 7440 while( xRead(&sCtx) ){ 7441 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); 7442 cSep = ','; 7443 if( sCtx.cTerm!=sCtx.cColSep ) break; 7444 } 7445 if( cSep=='(' ){ 7446 sqlite3_free(zCreate); 7447 sqlite3_free(sCtx.z); 7448 xCloser(sCtx.in); 7449 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); 7450 return 1; 7451 } 7452 zCreate = sqlite3_mprintf("%z\n)", zCreate); 7453 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); 7454 sqlite3_free(zCreate); 7455 if( rc ){ 7456 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, 7457 sqlite3_errmsg(p->db)); 7458 sqlite3_free(sCtx.z); 7459 xCloser(sCtx.in); 7460 return 1; 7461 } 7462 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7463 } 7464 sqlite3_free(zSql); 7465 if( rc ){ 7466 if (pStmt) sqlite3_finalize(pStmt); 7467 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); 7468 xCloser(sCtx.in); 7469 return 1; 7470 } 7471 nCol = sqlite3_column_count(pStmt); 7472 sqlite3_finalize(pStmt); 7473 pStmt = 0; 7474 if( nCol==0 ) return 0; /* no columns, no error */ 7475 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); 7476 if( zSql==0 ){ 7477 xCloser(sCtx.in); 7478 shell_out_of_memory(); 7479 } 7480 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); 7481 j = strlen30(zSql); 7482 for(i=1; i<nCol; i++){ 7483 zSql[j++] = ','; 7484 zSql[j++] = '?'; 7485 } 7486 zSql[j++] = ')'; 7487 zSql[j] = 0; 7488 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7489 sqlite3_free(zSql); 7490 if( rc ){ 7491 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7492 if (pStmt) sqlite3_finalize(pStmt); 7493 xCloser(sCtx.in); 7494 return 1; 7495 } 7496 needCommit = sqlite3_get_autocommit(p->db); 7497 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); 7498 do{ 7499 int startLine = sCtx.nLine; 7500 for(i=0; i<nCol; i++){ 7501 char *z = xRead(&sCtx); 7502 /* 7503 ** Did we reach end-of-file before finding any columns? 7504 ** If so, stop instead of NULL filling the remaining columns. 7505 */ 7506 if( z==0 && i==0 ) break; 7507 /* 7508 ** Did we reach end-of-file OR end-of-line before finding any 7509 ** columns in ASCII mode? If so, stop instead of NULL filling 7510 ** the remaining columns. 7511 */ 7512 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; 7513 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); 7514 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ 7515 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 7516 "filling the rest with NULL\n", 7517 sCtx.zFile, startLine, nCol, i+1); 7518 i += 2; 7519 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } 7520 } 7521 } 7522 if( sCtx.cTerm==sCtx.cColSep ){ 7523 do{ 7524 xRead(&sCtx); 7525 i++; 7526 }while( sCtx.cTerm==sCtx.cColSep ); 7527 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 7528 "extras ignored\n", 7529 sCtx.zFile, startLine, nCol, i); 7530 } 7531 if( i>=nCol ){ 7532 sqlite3_step(pStmt); 7533 rc = sqlite3_reset(pStmt); 7534 if( rc!=SQLITE_OK ){ 7535 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, 7536 startLine, sqlite3_errmsg(p->db)); 7537 } 7538 } 7539 }while( sCtx.cTerm!=EOF ); 7540 7541 xCloser(sCtx.in); 7542 sqlite3_free(sCtx.z); 7543 sqlite3_finalize(pStmt); 7544 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); 7545 }else 7546 7547#ifndef SQLITE_UNTESTABLE 7548 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){ 7549 char *zSql; 7550 char *zCollist = 0; 7551 sqlite3_stmt *pStmt; 7552 int tnum = 0; 7553 int i; 7554 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ 7555 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n" 7556 " .imposter off\n"); 7557 rc = 1; 7558 goto meta_command_exit; 7559 } 7560 open_db(p, 0); 7561 if( nArg==2 ){ 7562 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); 7563 goto meta_command_exit; 7564 } 7565 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master" 7566 " WHERE name='%q' AND type='index'", azArg[1]); 7567 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7568 sqlite3_free(zSql); 7569 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 7570 tnum = sqlite3_column_int(pStmt, 0); 7571 } 7572 sqlite3_finalize(pStmt); 7573 if( tnum==0 ){ 7574 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); 7575 rc = 1; 7576 goto meta_command_exit; 7577 } 7578 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); 7579 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7580 sqlite3_free(zSql); 7581 i = 0; 7582 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7583 char zLabel[20]; 7584 const char *zCol = (const char*)sqlite3_column_text(pStmt,2); 7585 i++; 7586 if( zCol==0 ){ 7587 if( sqlite3_column_int(pStmt,1)==-1 ){ 7588 zCol = "_ROWID_"; 7589 }else{ 7590 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); 7591 zCol = zLabel; 7592 } 7593 } 7594 if( zCollist==0 ){ 7595 zCollist = sqlite3_mprintf("\"%w\"", zCol); 7596 }else{ 7597 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); 7598 } 7599 } 7600 sqlite3_finalize(pStmt); 7601 zSql = sqlite3_mprintf( 7602 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID", 7603 azArg[2], zCollist, zCollist); 7604 sqlite3_free(zCollist); 7605 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); 7606 if( rc==SQLITE_OK ){ 7607 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); 7608 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); 7609 if( rc ){ 7610 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); 7611 }else{ 7612 utf8_printf(stdout, "%s;\n", zSql); 7613 raw_printf(stdout, 7614 "WARNING: writing to an imposter table will corrupt the index!\n" 7615 ); 7616 } 7617 }else{ 7618 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); 7619 rc = 1; 7620 } 7621 sqlite3_free(zSql); 7622 }else 7623#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ 7624 7625#ifdef SQLITE_ENABLE_IOTRACE 7626 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ 7627 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); 7628 if( iotrace && iotrace!=stdout ) fclose(iotrace); 7629 iotrace = 0; 7630 if( nArg<2 ){ 7631 sqlite3IoTrace = 0; 7632 }else if( strcmp(azArg[1], "-")==0 ){ 7633 sqlite3IoTrace = iotracePrintf; 7634 iotrace = stdout; 7635 }else{ 7636 iotrace = fopen(azArg[1], "w"); 7637 if( iotrace==0 ){ 7638 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 7639 sqlite3IoTrace = 0; 7640 rc = 1; 7641 }else{ 7642 sqlite3IoTrace = iotracePrintf; 7643 } 7644 } 7645 }else 7646#endif 7647 7648 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ 7649 static const struct { 7650 const char *zLimitName; /* Name of a limit */ 7651 int limitCode; /* Integer code for that limit */ 7652 } aLimit[] = { 7653 { "length", SQLITE_LIMIT_LENGTH }, 7654 { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, 7655 { "column", SQLITE_LIMIT_COLUMN }, 7656 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, 7657 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, 7658 { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, 7659 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, 7660 { "attached", SQLITE_LIMIT_ATTACHED }, 7661 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, 7662 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, 7663 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, 7664 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, 7665 }; 7666 int i, n2; 7667 open_db(p, 0); 7668 if( nArg==1 ){ 7669 for(i=0; i<ArraySize(aLimit); i++){ 7670 printf("%20s %d\n", aLimit[i].zLimitName, 7671 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); 7672 } 7673 }else if( nArg>3 ){ 7674 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); 7675 rc = 1; 7676 goto meta_command_exit; 7677 }else{ 7678 int iLimit = -1; 7679 n2 = strlen30(azArg[1]); 7680 for(i=0; i<ArraySize(aLimit); i++){ 7681 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ 7682 if( iLimit<0 ){ 7683 iLimit = i; 7684 }else{ 7685 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); 7686 rc = 1; 7687 goto meta_command_exit; 7688 } 7689 } 7690 } 7691 if( iLimit<0 ){ 7692 utf8_printf(stderr, "unknown limit: \"%s\"\n" 7693 "enter \".limits\" with no arguments for a list.\n", 7694 azArg[1]); 7695 rc = 1; 7696 goto meta_command_exit; 7697 } 7698 if( nArg==3 ){ 7699 sqlite3_limit(p->db, aLimit[iLimit].limitCode, 7700 (int)integerValue(azArg[2])); 7701 } 7702 printf("%20s %d\n", aLimit[iLimit].zLimitName, 7703 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); 7704 } 7705 }else 7706 7707 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){ 7708 open_db(p, 0); 7709 lintDotCommand(p, azArg, nArg); 7710 }else 7711 7712#ifndef SQLITE_OMIT_LOAD_EXTENSION 7713 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ 7714 const char *zFile, *zProc; 7715 char *zErrMsg = 0; 7716 if( nArg<2 ){ 7717 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); 7718 rc = 1; 7719 goto meta_command_exit; 7720 } 7721 zFile = azArg[1]; 7722 zProc = nArg>=3 ? azArg[2] : 0; 7723 open_db(p, 0); 7724 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); 7725 if( rc!=SQLITE_OK ){ 7726 utf8_printf(stderr, "Error: %s\n", zErrMsg); 7727 sqlite3_free(zErrMsg); 7728 rc = 1; 7729 } 7730 }else 7731#endif 7732 7733 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ 7734 if( nArg!=2 ){ 7735 raw_printf(stderr, "Usage: .log FILENAME\n"); 7736 rc = 1; 7737 }else{ 7738 const char *zFile = azArg[1]; 7739 output_file_close(p->pLog); 7740 p->pLog = output_file_open(zFile, 0); 7741 } 7742 }else 7743 7744 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ 7745 const char *zMode = nArg>=2 ? azArg[1] : ""; 7746 int n2 = strlen30(zMode); 7747 int c2 = zMode[0]; 7748 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ 7749 p->mode = MODE_Line; 7750 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7751 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ 7752 p->mode = MODE_Column; 7753 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7754 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ 7755 p->mode = MODE_List; 7756 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); 7757 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7758 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ 7759 p->mode = MODE_Html; 7760 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ 7761 p->mode = MODE_Tcl; 7762 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); 7763 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7764 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ 7765 p->mode = MODE_Csv; 7766 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 7767 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 7768 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ 7769 p->mode = MODE_List; 7770 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); 7771 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ 7772 p->mode = MODE_Insert; 7773 set_table_name(p, nArg>=3 ? azArg[2] : "table"); 7774 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){ 7775 p->mode = MODE_Quote; 7776 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ 7777 p->mode = MODE_Ascii; 7778 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); 7779 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); 7780 }else if( nArg==1 ){ 7781 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); 7782 }else{ 7783 raw_printf(stderr, "Error: mode should be one of: " 7784 "ascii column csv html insert line list quote tabs tcl\n"); 7785 rc = 1; 7786 } 7787 p->cMode = p->mode; 7788 }else 7789 7790 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ 7791 if( nArg==2 ){ 7792 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, 7793 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); 7794 }else{ 7795 raw_printf(stderr, "Usage: .nullvalue STRING\n"); 7796 rc = 1; 7797 } 7798 }else 7799 7800 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ 7801 char *zNewFilename; /* Name of the database file to open */ 7802 int iName = 1; /* Index in azArg[] of the filename */ 7803 int newFlag = 0; /* True to delete file before opening */ 7804 /* Close the existing database */ 7805 session_close_all(p); 7806 close_db(p->db); 7807 p->db = 0; 7808 p->zDbFilename = 0; 7809 sqlite3_free(p->zFreeOnClose); 7810 p->zFreeOnClose = 0; 7811 p->openMode = SHELL_OPEN_UNSPEC; 7812 p->szMax = 0; 7813 /* Check for command-line arguments */ 7814 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){ 7815 const char *z = azArg[iName]; 7816 if( optionMatch(z,"new") ){ 7817 newFlag = 1; 7818#ifdef SQLITE_HAVE_ZLIB 7819 }else if( optionMatch(z, "zip") ){ 7820 p->openMode = SHELL_OPEN_ZIPFILE; 7821#endif 7822 }else if( optionMatch(z, "append") ){ 7823 p->openMode = SHELL_OPEN_APPENDVFS; 7824 }else if( optionMatch(z, "readonly") ){ 7825 p->openMode = SHELL_OPEN_READONLY; 7826#ifdef SQLITE_ENABLE_DESERIALIZE 7827 }else if( optionMatch(z, "deserialize") ){ 7828 p->openMode = SHELL_OPEN_DESERIALIZE; 7829 }else if( optionMatch(z, "hexdb") ){ 7830 p->openMode = SHELL_OPEN_HEXDB; 7831 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){ 7832 p->szMax = integerValue(azArg[++iName]); 7833#endif /* SQLITE_ENABLE_DESERIALIZE */ 7834 }else if( z[0]=='-' ){ 7835 utf8_printf(stderr, "unknown option: %s\n", z); 7836 rc = 1; 7837 goto meta_command_exit; 7838 } 7839 } 7840 /* If a filename is specified, try to open it first */ 7841 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0; 7842 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){ 7843 if( newFlag ) shellDeleteFile(zNewFilename); 7844 p->zDbFilename = zNewFilename; 7845 open_db(p, OPEN_DB_KEEPALIVE); 7846 if( p->db==0 ){ 7847 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); 7848 sqlite3_free(zNewFilename); 7849 }else{ 7850 p->zFreeOnClose = zNewFilename; 7851 } 7852 } 7853 if( p->db==0 ){ 7854 /* As a fall-back open a TEMP database */ 7855 p->zDbFilename = 0; 7856 open_db(p, 0); 7857 } 7858 }else 7859 7860 if( (c=='o' 7861 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0)) 7862 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0) 7863 ){ 7864 const char *zFile = nArg>=2 ? azArg[1] : "stdout"; 7865 int bTxtMode = 0; 7866 if( azArg[0][0]=='e' ){ 7867 /* Transform the ".excel" command into ".once -x" */ 7868 nArg = 2; 7869 azArg[0] = "once"; 7870 zFile = azArg[1] = "-x"; 7871 n = 4; 7872 } 7873 if( nArg>2 ){ 7874 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]); 7875 rc = 1; 7876 goto meta_command_exit; 7877 } 7878 if( n>1 && strncmp(azArg[0], "once", n)==0 ){ 7879 if( nArg<2 ){ 7880 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n"); 7881 rc = 1; 7882 goto meta_command_exit; 7883 } 7884 p->outCount = 2; 7885 }else{ 7886 p->outCount = 0; 7887 } 7888 output_reset(p); 7889 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++; 7890#ifndef SQLITE_NOHAVE_SYSTEM 7891 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){ 7892 p->doXdgOpen = 1; 7893 outputModePush(p); 7894 if( zFile[1]=='x' ){ 7895 newTempFile(p, "csv"); 7896 p->mode = MODE_Csv; 7897 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 7898 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 7899 }else{ 7900 newTempFile(p, "txt"); 7901 bTxtMode = 1; 7902 } 7903 zFile = p->zTempFile; 7904 } 7905#endif /* SQLITE_NOHAVE_SYSTEM */ 7906 if( zFile[0]=='|' ){ 7907#ifdef SQLITE_OMIT_POPEN 7908 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 7909 rc = 1; 7910 p->out = stdout; 7911#else 7912 p->out = popen(zFile + 1, "w"); 7913 if( p->out==0 ){ 7914 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); 7915 p->out = stdout; 7916 rc = 1; 7917 }else{ 7918 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 7919 } 7920#endif 7921 }else{ 7922 p->out = output_file_open(zFile, bTxtMode); 7923 if( p->out==0 ){ 7924 if( strcmp(zFile,"off")!=0 ){ 7925 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); 7926 } 7927 p->out = stdout; 7928 rc = 1; 7929 } else { 7930 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 7931 } 7932 } 7933 }else 7934 7935 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){ 7936 open_db(p,0); 7937 if( nArg<=1 ) goto parameter_syntax_error; 7938 7939 /* .parameter clear 7940 ** Clear all bind parameters by dropping the TEMP table that holds them. 7941 */ 7942 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){ 7943 int wrSchema = 0; 7944 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); 7945 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 7946 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", 7947 0, 0, 0); 7948 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); 7949 }else 7950 7951 /* .parameter list 7952 ** List all bind parameters. 7953 */ 7954 if( nArg==2 && strcmp(azArg[1],"list")==0 ){ 7955 sqlite3_stmt *pStmt = 0; 7956 int rx; 7957 int len = 0; 7958 rx = sqlite3_prepare_v2(p->db, 7959 "SELECT max(length(key)) " 7960 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 7961 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 7962 len = sqlite3_column_int(pStmt, 0); 7963 if( len>40 ) len = 40; 7964 } 7965 sqlite3_finalize(pStmt); 7966 pStmt = 0; 7967 if( len ){ 7968 rx = sqlite3_prepare_v2(p->db, 7969 "SELECT key, quote(value) " 7970 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 7971 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7972 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0), 7973 sqlite3_column_text(pStmt,1)); 7974 } 7975 sqlite3_finalize(pStmt); 7976 } 7977 }else 7978 7979 /* .parameter init 7980 ** Make sure the TEMP table used to hold bind parameters exists. 7981 ** Create it if necessary. 7982 */ 7983 if( nArg==2 && strcmp(azArg[1],"init")==0 ){ 7984 bind_table_init(p); 7985 }else 7986 7987 /* .parameter set NAME VALUE 7988 ** Set or reset a bind parameter. NAME should be the full parameter 7989 ** name exactly as it appears in the query. (ex: $abc, @def). The 7990 ** VALUE can be in either SQL literal notation, or if not it will be 7991 ** understood to be a text string. 7992 */ 7993 if( nArg==4 && strcmp(azArg[1],"set")==0 ){ 7994 int rx; 7995 char *zSql; 7996 sqlite3_stmt *pStmt; 7997 const char *zKey = azArg[2]; 7998 const char *zValue = azArg[3]; 7999 bind_table_init(p); 8000 zSql = sqlite3_mprintf( 8001 "REPLACE INTO temp.sqlite_parameters(key,value)" 8002 "VALUES(%Q,%s);", zKey, zValue); 8003 if( zSql==0 ) shell_out_of_memory(); 8004 pStmt = 0; 8005 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8006 sqlite3_free(zSql); 8007 if( rx!=SQLITE_OK ){ 8008 sqlite3_finalize(pStmt); 8009 pStmt = 0; 8010 zSql = sqlite3_mprintf( 8011 "REPLACE INTO temp.sqlite_parameters(key,value)" 8012 "VALUES(%Q,%Q);", zKey, zValue); 8013 if( zSql==0 ) shell_out_of_memory(); 8014 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8015 sqlite3_free(zSql); 8016 if( rx!=SQLITE_OK ){ 8017 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); 8018 sqlite3_finalize(pStmt); 8019 pStmt = 0; 8020 rc = 1; 8021 } 8022 } 8023 sqlite3_step(pStmt); 8024 sqlite3_finalize(pStmt); 8025 }else 8026 8027 /* .parameter unset NAME 8028 ** Remove the NAME binding from the parameter binding table, if it 8029 ** exists. 8030 */ 8031 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){ 8032 char *zSql = sqlite3_mprintf( 8033 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); 8034 if( zSql==0 ) shell_out_of_memory(); 8035 sqlite3_exec(p->db, zSql, 0, 0, 0); 8036 sqlite3_free(zSql); 8037 }else 8038 /* If no command name matches, show a syntax error */ 8039 parameter_syntax_error: 8040 showHelp(p->out, "parameter"); 8041 }else 8042 8043 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ 8044 int i; 8045 for(i=1; i<nArg; i++){ 8046 if( i>1 ) raw_printf(p->out, " "); 8047 utf8_printf(p->out, "%s", azArg[i]); 8048 } 8049 raw_printf(p->out, "\n"); 8050 }else 8051 8052#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 8053 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){ 8054 int i; 8055 int nn = 0; 8056 p->flgProgress = 0; 8057 p->mxProgress = 0; 8058 p->nProgress = 0; 8059 for(i=1; i<nArg; i++){ 8060 const char *z = azArg[i]; 8061 if( z[0]=='-' ){ 8062 z++; 8063 if( z[0]=='-' ) z++; 8064 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 8065 p->flgProgress |= SHELL_PROGRESS_QUIET; 8066 continue; 8067 } 8068 if( strcmp(z,"reset")==0 ){ 8069 p->flgProgress |= SHELL_PROGRESS_RESET; 8070 continue; 8071 } 8072 if( strcmp(z,"once")==0 ){ 8073 p->flgProgress |= SHELL_PROGRESS_ONCE; 8074 continue; 8075 } 8076 if( strcmp(z,"limit")==0 ){ 8077 if( i+1>=nArg ){ 8078 utf8_printf(stderr, "Error: missing argument on --limit\n"); 8079 rc = 1; 8080 goto meta_command_exit; 8081 }else{ 8082 p->mxProgress = (int)integerValue(azArg[++i]); 8083 } 8084 continue; 8085 } 8086 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]); 8087 rc = 1; 8088 goto meta_command_exit; 8089 }else{ 8090 nn = (int)integerValue(z); 8091 } 8092 } 8093 open_db(p, 0); 8094 sqlite3_progress_handler(p->db, nn, progress_handler, p); 8095 }else 8096#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 8097 8098 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ 8099 if( nArg >= 2) { 8100 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); 8101 } 8102 if( nArg >= 3) { 8103 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); 8104 } 8105 }else 8106 8107 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ 8108 rc = 2; 8109 }else 8110 8111 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ 8112 FILE *inSaved = p->in; 8113 int savedLineno = p->lineno; 8114 if( nArg!=2 ){ 8115 raw_printf(stderr, "Usage: .read FILE\n"); 8116 rc = 1; 8117 goto meta_command_exit; 8118 } 8119 p->in = fopen(azArg[1], "rb"); 8120 if( p->in==0 ){ 8121 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); 8122 rc = 1; 8123 }else{ 8124 rc = process_input(p); 8125 fclose(p->in); 8126 } 8127 p->in = inSaved; 8128 p->lineno = savedLineno; 8129 }else 8130 8131 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ 8132 const char *zSrcFile; 8133 const char *zDb; 8134 sqlite3 *pSrc; 8135 sqlite3_backup *pBackup; 8136 int nTimeout = 0; 8137 8138 if( nArg==2 ){ 8139 zSrcFile = azArg[1]; 8140 zDb = "main"; 8141 }else if( nArg==3 ){ 8142 zSrcFile = azArg[2]; 8143 zDb = azArg[1]; 8144 }else{ 8145 raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); 8146 rc = 1; 8147 goto meta_command_exit; 8148 } 8149 rc = sqlite3_open(zSrcFile, &pSrc); 8150 if( rc!=SQLITE_OK ){ 8151 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); 8152 close_db(pSrc); 8153 return 1; 8154 } 8155 open_db(p, 0); 8156 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); 8157 if( pBackup==0 ){ 8158 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8159 close_db(pSrc); 8160 return 1; 8161 } 8162 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK 8163 || rc==SQLITE_BUSY ){ 8164 if( rc==SQLITE_BUSY ){ 8165 if( nTimeout++ >= 3 ) break; 8166 sqlite3_sleep(100); 8167 } 8168 } 8169 sqlite3_backup_finish(pBackup); 8170 if( rc==SQLITE_DONE ){ 8171 rc = 0; 8172 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ 8173 raw_printf(stderr, "Error: source database is busy\n"); 8174 rc = 1; 8175 }else{ 8176 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8177 rc = 1; 8178 } 8179 close_db(pSrc); 8180 }else 8181 8182 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ 8183 if( nArg==2 ){ 8184 p->scanstatsOn = (u8)booleanValue(azArg[1]); 8185#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 8186 raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); 8187#endif 8188 }else{ 8189 raw_printf(stderr, "Usage: .scanstats on|off\n"); 8190 rc = 1; 8191 } 8192 }else 8193 8194 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ 8195 ShellText sSelect; 8196 ShellState data; 8197 char *zErrMsg = 0; 8198 const char *zDiv = "("; 8199 const char *zName = 0; 8200 int iSchema = 0; 8201 int bDebug = 0; 8202 int ii; 8203 8204 open_db(p, 0); 8205 memcpy(&data, p, sizeof(data)); 8206 data.showHeader = 0; 8207 data.cMode = data.mode = MODE_Semi; 8208 initText(&sSelect); 8209 for(ii=1; ii<nArg; ii++){ 8210 if( optionMatch(azArg[ii],"indent") ){ 8211 data.cMode = data.mode = MODE_Pretty; 8212 }else if( optionMatch(azArg[ii],"debug") ){ 8213 bDebug = 1; 8214 }else if( zName==0 ){ 8215 zName = azArg[ii]; 8216 }else{ 8217 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n"); 8218 rc = 1; 8219 goto meta_command_exit; 8220 } 8221 } 8222 if( zName!=0 ){ 8223 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0; 8224 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){ 8225 char *new_argv[2], *new_colv[2]; 8226 new_argv[0] = sqlite3_mprintf( 8227 "CREATE TABLE %s (\n" 8228 " type text,\n" 8229 " name text,\n" 8230 " tbl_name text,\n" 8231 " rootpage integer,\n" 8232 " sql text\n" 8233 ")", isMaster ? "sqlite_master" : "sqlite_temp_master"); 8234 new_argv[1] = 0; 8235 new_colv[0] = "sql"; 8236 new_colv[1] = 0; 8237 callback(&data, 1, new_argv, new_colv); 8238 sqlite3_free(new_argv[0]); 8239 } 8240 } 8241 if( zDiv ){ 8242 sqlite3_stmt *pStmt = 0; 8243 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", 8244 -1, &pStmt, 0); 8245 if( rc ){ 8246 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8247 sqlite3_finalize(pStmt); 8248 rc = 1; 8249 goto meta_command_exit; 8250 } 8251 appendText(&sSelect, "SELECT sql FROM", 0); 8252 iSchema = 0; 8253 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 8254 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); 8255 char zScNum[30]; 8256 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); 8257 appendText(&sSelect, zDiv, 0); 8258 zDiv = " UNION ALL "; 8259 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); 8260 if( sqlite3_stricmp(zDb, "main")!=0 ){ 8261 appendText(&sSelect, zDb, '"'); 8262 }else{ 8263 appendText(&sSelect, "NULL", 0); 8264 } 8265 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); 8266 appendText(&sSelect, zScNum, 0); 8267 appendText(&sSelect, " AS snum, ", 0); 8268 appendText(&sSelect, zDb, '\''); 8269 appendText(&sSelect, " AS sname FROM ", 0); 8270 appendText(&sSelect, zDb, '"'); 8271 appendText(&sSelect, ".sqlite_master", 0); 8272 } 8273 sqlite3_finalize(pStmt); 8274#ifdef SQLITE_INTROSPECTION_PRAGMAS 8275 if( zName ){ 8276 appendText(&sSelect, 8277 " UNION ALL SELECT shell_module_schema(name)," 8278 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0); 8279 } 8280#endif 8281 appendText(&sSelect, ") WHERE ", 0); 8282 if( zName ){ 8283 char *zQarg = sqlite3_mprintf("%Q", zName); 8284 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || 8285 strchr(zName, '[') != 0; 8286 if( strchr(zName, '.') ){ 8287 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); 8288 }else{ 8289 appendText(&sSelect, "lower(tbl_name)", 0); 8290 } 8291 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); 8292 appendText(&sSelect, zQarg, 0); 8293 if( !bGlob ){ 8294 appendText(&sSelect, " ESCAPE '\\' ", 0); 8295 } 8296 appendText(&sSelect, " AND ", 0); 8297 sqlite3_free(zQarg); 8298 } 8299 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL" 8300 " ORDER BY snum, rowid", 0); 8301 if( bDebug ){ 8302 utf8_printf(p->out, "SQL: %s;\n", sSelect.z); 8303 }else{ 8304 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); 8305 } 8306 freeText(&sSelect); 8307 } 8308 if( zErrMsg ){ 8309 utf8_printf(stderr,"Error: %s\n", zErrMsg); 8310 sqlite3_free(zErrMsg); 8311 rc = 1; 8312 }else if( rc != SQLITE_OK ){ 8313 raw_printf(stderr,"Error: querying schema information\n"); 8314 rc = 1; 8315 }else{ 8316 rc = 0; 8317 } 8318 }else 8319 8320#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 8321 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ 8322 sqlite3SelectTrace = (int)integerValue(azArg[1]); 8323 }else 8324#endif 8325 8326#if defined(SQLITE_ENABLE_SESSION) 8327 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ 8328 OpenSession *pSession = &p->aSession[0]; 8329 char **azCmd = &azArg[1]; 8330 int iSes = 0; 8331 int nCmd = nArg - 1; 8332 int i; 8333 if( nArg<=1 ) goto session_syntax_error; 8334 open_db(p, 0); 8335 if( nArg>=3 ){ 8336 for(iSes=0; iSes<p->nSession; iSes++){ 8337 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break; 8338 } 8339 if( iSes<p->nSession ){ 8340 pSession = &p->aSession[iSes]; 8341 azCmd++; 8342 nCmd--; 8343 }else{ 8344 pSession = &p->aSession[0]; 8345 iSes = 0; 8346 } 8347 } 8348 8349 /* .session attach TABLE 8350 ** Invoke the sqlite3session_attach() interface to attach a particular 8351 ** table so that it is never filtered. 8352 */ 8353 if( strcmp(azCmd[0],"attach")==0 ){ 8354 if( nCmd!=2 ) goto session_syntax_error; 8355 if( pSession->p==0 ){ 8356 session_not_open: 8357 raw_printf(stderr, "ERROR: No sessions are open\n"); 8358 }else{ 8359 rc = sqlite3session_attach(pSession->p, azCmd[1]); 8360 if( rc ){ 8361 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); 8362 rc = 0; 8363 } 8364 } 8365 }else 8366 8367 /* .session changeset FILE 8368 ** .session patchset FILE 8369 ** Write a changeset or patchset into a file. The file is overwritten. 8370 */ 8371 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ 8372 FILE *out = 0; 8373 if( nCmd!=2 ) goto session_syntax_error; 8374 if( pSession->p==0 ) goto session_not_open; 8375 out = fopen(azCmd[1], "wb"); 8376 if( out==0 ){ 8377 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]); 8378 }else{ 8379 int szChng; 8380 void *pChng; 8381 if( azCmd[0][0]=='c' ){ 8382 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); 8383 }else{ 8384 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); 8385 } 8386 if( rc ){ 8387 printf("Error: error code %d\n", rc); 8388 rc = 0; 8389 } 8390 if( pChng 8391 && fwrite(pChng, szChng, 1, out)!=1 ){ 8392 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", 8393 szChng); 8394 } 8395 sqlite3_free(pChng); 8396 fclose(out); 8397 } 8398 }else 8399 8400 /* .session close 8401 ** Close the identified session 8402 */ 8403 if( strcmp(azCmd[0], "close")==0 ){ 8404 if( nCmd!=1 ) goto session_syntax_error; 8405 if( p->nSession ){ 8406 session_close(pSession); 8407 p->aSession[iSes] = p->aSession[--p->nSession]; 8408 } 8409 }else 8410 8411 /* .session enable ?BOOLEAN? 8412 ** Query or set the enable flag 8413 */ 8414 if( strcmp(azCmd[0], "enable")==0 ){ 8415 int ii; 8416 if( nCmd>2 ) goto session_syntax_error; 8417 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 8418 if( p->nSession ){ 8419 ii = sqlite3session_enable(pSession->p, ii); 8420 utf8_printf(p->out, "session %s enable flag = %d\n", 8421 pSession->zName, ii); 8422 } 8423 }else 8424 8425 /* .session filter GLOB .... 8426 ** Set a list of GLOB patterns of table names to be excluded. 8427 */ 8428 if( strcmp(azCmd[0], "filter")==0 ){ 8429 int ii, nByte; 8430 if( nCmd<2 ) goto session_syntax_error; 8431 if( p->nSession ){ 8432 for(ii=0; ii<pSession->nFilter; ii++){ 8433 sqlite3_free(pSession->azFilter[ii]); 8434 } 8435 sqlite3_free(pSession->azFilter); 8436 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); 8437 pSession->azFilter = sqlite3_malloc( nByte ); 8438 if( pSession->azFilter==0 ){ 8439 raw_printf(stderr, "Error: out or memory\n"); 8440 exit(1); 8441 } 8442 for(ii=1; ii<nCmd; ii++){ 8443 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); 8444 } 8445 pSession->nFilter = ii-1; 8446 } 8447 }else 8448 8449 /* .session indirect ?BOOLEAN? 8450 ** Query or set the indirect flag 8451 */ 8452 if( strcmp(azCmd[0], "indirect")==0 ){ 8453 int ii; 8454 if( nCmd>2 ) goto session_syntax_error; 8455 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 8456 if( p->nSession ){ 8457 ii = sqlite3session_indirect(pSession->p, ii); 8458 utf8_printf(p->out, "session %s indirect flag = %d\n", 8459 pSession->zName, ii); 8460 } 8461 }else 8462 8463 /* .session isempty 8464 ** Determine if the session is empty 8465 */ 8466 if( strcmp(azCmd[0], "isempty")==0 ){ 8467 int ii; 8468 if( nCmd!=1 ) goto session_syntax_error; 8469 if( p->nSession ){ 8470 ii = sqlite3session_isempty(pSession->p); 8471 utf8_printf(p->out, "session %s isempty flag = %d\n", 8472 pSession->zName, ii); 8473 } 8474 }else 8475 8476 /* .session list 8477 ** List all currently open sessions 8478 */ 8479 if( strcmp(azCmd[0],"list")==0 ){ 8480 for(i=0; i<p->nSession; i++){ 8481 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName); 8482 } 8483 }else 8484 8485 /* .session open DB NAME 8486 ** Open a new session called NAME on the attached database DB. 8487 ** DB is normally "main". 8488 */ 8489 if( strcmp(azCmd[0],"open")==0 ){ 8490 char *zName; 8491 if( nCmd!=3 ) goto session_syntax_error; 8492 zName = azCmd[2]; 8493 if( zName[0]==0 ) goto session_syntax_error; 8494 for(i=0; i<p->nSession; i++){ 8495 if( strcmp(p->aSession[i].zName,zName)==0 ){ 8496 utf8_printf(stderr, "Session \"%s\" already exists\n", zName); 8497 goto meta_command_exit; 8498 } 8499 } 8500 if( p->nSession>=ArraySize(p->aSession) ){ 8501 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession)); 8502 goto meta_command_exit; 8503 } 8504 pSession = &p->aSession[p->nSession]; 8505 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); 8506 if( rc ){ 8507 raw_printf(stderr, "Cannot open session: error code=%d\n", rc); 8508 rc = 0; 8509 goto meta_command_exit; 8510 } 8511 pSession->nFilter = 0; 8512 sqlite3session_table_filter(pSession->p, session_filter, pSession); 8513 p->nSession++; 8514 pSession->zName = sqlite3_mprintf("%s", zName); 8515 }else 8516 /* If no command name matches, show a syntax error */ 8517 session_syntax_error: 8518 showHelp(p->out, "session"); 8519 }else 8520#endif 8521 8522#ifdef SQLITE_DEBUG 8523 /* Undocumented commands for internal testing. Subject to change 8524 ** without notice. */ 8525 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ 8526 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ 8527 int i, v; 8528 for(i=1; i<nArg; i++){ 8529 v = booleanValue(azArg[i]); 8530 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); 8531 } 8532 } 8533 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ 8534 int i; sqlite3_int64 v; 8535 for(i=1; i<nArg; i++){ 8536 char zBuf[200]; 8537 v = integerValue(azArg[i]); 8538 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); 8539 utf8_printf(p->out, "%s", zBuf); 8540 } 8541 } 8542 }else 8543#endif 8544 8545 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){ 8546 int bIsInit = 0; /* True to initialize the SELFTEST table */ 8547 int bVerbose = 0; /* Verbose output */ 8548 int bSelftestExists; /* True if SELFTEST already exists */ 8549 int i, k; /* Loop counters */ 8550 int nTest = 0; /* Number of tests runs */ 8551 int nErr = 0; /* Number of errors seen */ 8552 ShellText str; /* Answer for a query */ 8553 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ 8554 8555 open_db(p,0); 8556 for(i=1; i<nArg; i++){ 8557 const char *z = azArg[i]; 8558 if( z[0]=='-' && z[1]=='-' ) z++; 8559 if( strcmp(z,"-init")==0 ){ 8560 bIsInit = 1; 8561 }else 8562 if( strcmp(z,"-v")==0 ){ 8563 bVerbose++; 8564 }else 8565 { 8566 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 8567 azArg[i], azArg[0]); 8568 raw_printf(stderr, "Should be one of: --init -v\n"); 8569 rc = 1; 8570 goto meta_command_exit; 8571 } 8572 } 8573 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) 8574 != SQLITE_OK ){ 8575 bSelftestExists = 0; 8576 }else{ 8577 bSelftestExists = 1; 8578 } 8579 if( bIsInit ){ 8580 createSelftestTable(p); 8581 bSelftestExists = 1; 8582 } 8583 initText(&str); 8584 appendText(&str, "x", 0); 8585 for(k=bSelftestExists; k>=0; k--){ 8586 if( k==1 ){ 8587 rc = sqlite3_prepare_v2(p->db, 8588 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", 8589 -1, &pStmt, 0); 8590 }else{ 8591 rc = sqlite3_prepare_v2(p->db, 8592 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," 8593 " (1,'run','PRAGMA integrity_check','ok')", 8594 -1, &pStmt, 0); 8595 } 8596 if( rc ){ 8597 raw_printf(stderr, "Error querying the selftest table\n"); 8598 rc = 1; 8599 sqlite3_finalize(pStmt); 8600 goto meta_command_exit; 8601 } 8602 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ 8603 int tno = sqlite3_column_int(pStmt, 0); 8604 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); 8605 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); 8606 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); 8607 8608 k = 0; 8609 if( bVerbose>0 ){ 8610 char *zQuote = sqlite3_mprintf("%q", zSql); 8611 printf("%d: %s %s\n", tno, zOp, zSql); 8612 sqlite3_free(zQuote); 8613 } 8614 if( strcmp(zOp,"memo")==0 ){ 8615 utf8_printf(p->out, "%s\n", zSql); 8616 }else 8617 if( strcmp(zOp,"run")==0 ){ 8618 char *zErrMsg = 0; 8619 str.n = 0; 8620 str.z[0] = 0; 8621 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); 8622 nTest++; 8623 if( bVerbose ){ 8624 utf8_printf(p->out, "Result: %s\n", str.z); 8625 } 8626 if( rc || zErrMsg ){ 8627 nErr++; 8628 rc = 1; 8629 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); 8630 sqlite3_free(zErrMsg); 8631 }else if( strcmp(zAns,str.z)!=0 ){ 8632 nErr++; 8633 rc = 1; 8634 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); 8635 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); 8636 } 8637 }else 8638 { 8639 utf8_printf(stderr, 8640 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); 8641 rc = 1; 8642 break; 8643 } 8644 } /* End loop over rows of content from SELFTEST */ 8645 sqlite3_finalize(pStmt); 8646 } /* End loop over k */ 8647 freeText(&str); 8648 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); 8649 }else 8650 8651 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ 8652 if( nArg<2 || nArg>3 ){ 8653 raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); 8654 rc = 1; 8655 } 8656 if( nArg>=2 ){ 8657 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, 8658 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); 8659 } 8660 if( nArg>=3 ){ 8661 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, 8662 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); 8663 } 8664 }else 8665 8666 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){ 8667 const char *zLike = 0; /* Which table to checksum. 0 means everything */ 8668 int i; /* Loop counter */ 8669 int bSchema = 0; /* Also hash the schema */ 8670 int bSeparate = 0; /* Hash each table separately */ 8671 int iSize = 224; /* Hash algorithm to use */ 8672 int bDebug = 0; /* Only show the query that would have run */ 8673 sqlite3_stmt *pStmt; /* For querying tables names */ 8674 char *zSql; /* SQL to be run */ 8675 char *zSep; /* Separator */ 8676 ShellText sSql; /* Complete SQL for the query to run the hash */ 8677 ShellText sQuery; /* Set of queries used to read all content */ 8678 open_db(p, 0); 8679 for(i=1; i<nArg; i++){ 8680 const char *z = azArg[i]; 8681 if( z[0]=='-' ){ 8682 z++; 8683 if( z[0]=='-' ) z++; 8684 if( strcmp(z,"schema")==0 ){ 8685 bSchema = 1; 8686 }else 8687 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 8688 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 8689 ){ 8690 iSize = atoi(&z[5]); 8691 }else 8692 if( strcmp(z,"debug")==0 ){ 8693 bDebug = 1; 8694 }else 8695 { 8696 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 8697 azArg[i], azArg[0]); 8698 raw_printf(stderr, "Should be one of: --schema" 8699 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n"); 8700 rc = 1; 8701 goto meta_command_exit; 8702 } 8703 }else if( zLike ){ 8704 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); 8705 rc = 1; 8706 goto meta_command_exit; 8707 }else{ 8708 zLike = z; 8709 bSeparate = 1; 8710 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; 8711 } 8712 } 8713 if( bSchema ){ 8714 zSql = "SELECT lower(name) FROM sqlite_master" 8715 " WHERE type='table' AND coalesce(rootpage,0)>1" 8716 " UNION ALL SELECT 'sqlite_master'" 8717 " ORDER BY 1 collate nocase"; 8718 }else{ 8719 zSql = "SELECT lower(name) FROM sqlite_master" 8720 " WHERE type='table' AND coalesce(rootpage,0)>1" 8721 " AND name NOT LIKE 'sqlite_%'" 8722 " ORDER BY 1 collate nocase"; 8723 } 8724 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8725 initText(&sQuery); 8726 initText(&sSql); 8727 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); 8728 zSep = "VALUES("; 8729 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 8730 const char *zTab = (const char*)sqlite3_column_text(pStmt,0); 8731 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; 8732 if( strncmp(zTab, "sqlite_",7)!=0 ){ 8733 appendText(&sQuery,"SELECT * FROM ", 0); 8734 appendText(&sQuery,zTab,'"'); 8735 appendText(&sQuery," NOT INDEXED;", 0); 8736 }else if( strcmp(zTab, "sqlite_master")==0 ){ 8737 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master" 8738 " ORDER BY name;", 0); 8739 }else if( strcmp(zTab, "sqlite_sequence")==0 ){ 8740 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" 8741 " ORDER BY name;", 0); 8742 }else if( strcmp(zTab, "sqlite_stat1")==0 ){ 8743 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" 8744 " ORDER BY tbl,idx;", 0); 8745 }else if( strcmp(zTab, "sqlite_stat3")==0 8746 || strcmp(zTab, "sqlite_stat4")==0 ){ 8747 appendText(&sQuery, "SELECT * FROM ", 0); 8748 appendText(&sQuery, zTab, 0); 8749 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); 8750 } 8751 appendText(&sSql, zSep, 0); 8752 appendText(&sSql, sQuery.z, '\''); 8753 sQuery.n = 0; 8754 appendText(&sSql, ",", 0); 8755 appendText(&sSql, zTab, '\''); 8756 zSep = "),("; 8757 } 8758 sqlite3_finalize(pStmt); 8759 if( bSeparate ){ 8760 zSql = sqlite3_mprintf( 8761 "%s))" 8762 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" 8763 " FROM [sha3sum$query]", 8764 sSql.z, iSize); 8765 }else{ 8766 zSql = sqlite3_mprintf( 8767 "%s))" 8768 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" 8769 " FROM [sha3sum$query]", 8770 sSql.z, iSize); 8771 } 8772 freeText(&sQuery); 8773 freeText(&sSql); 8774 if( bDebug ){ 8775 utf8_printf(p->out, "%s\n", zSql); 8776 }else{ 8777 shell_exec(p, zSql, 0); 8778 } 8779 sqlite3_free(zSql); 8780 }else 8781 8782#ifndef SQLITE_NOHAVE_SYSTEM 8783 if( c=='s' 8784 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) 8785 ){ 8786 char *zCmd; 8787 int i, x; 8788 if( nArg<2 ){ 8789 raw_printf(stderr, "Usage: .system COMMAND\n"); 8790 rc = 1; 8791 goto meta_command_exit; 8792 } 8793 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); 8794 for(i=2; i<nArg; i++){ 8795 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", 8796 zCmd, azArg[i]); 8797 } 8798 x = system(zCmd); 8799 sqlite3_free(zCmd); 8800 if( x ) raw_printf(stderr, "System command returns %d\n", x); 8801 }else 8802#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 8803 8804 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){ 8805 static const char *azBool[] = { "off", "on", "trigger", "full"}; 8806 int i; 8807 if( nArg!=1 ){ 8808 raw_printf(stderr, "Usage: .show\n"); 8809 rc = 1; 8810 goto meta_command_exit; 8811 } 8812 utf8_printf(p->out, "%12.12s: %s\n","echo", 8813 azBool[ShellHasFlag(p, SHFLG_Echo)]); 8814 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); 8815 utf8_printf(p->out, "%12.12s: %s\n","explain", 8816 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); 8817 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); 8818 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); 8819 utf8_printf(p->out, "%12.12s: ", "nullvalue"); 8820 output_c_string(p->out, p->nullValue); 8821 raw_printf(p->out, "\n"); 8822 utf8_printf(p->out,"%12.12s: %s\n","output", 8823 strlen30(p->outfile) ? p->outfile : "stdout"); 8824 utf8_printf(p->out,"%12.12s: ", "colseparator"); 8825 output_c_string(p->out, p->colSeparator); 8826 raw_printf(p->out, "\n"); 8827 utf8_printf(p->out,"%12.12s: ", "rowseparator"); 8828 output_c_string(p->out, p->rowSeparator); 8829 raw_printf(p->out, "\n"); 8830 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]); 8831 utf8_printf(p->out, "%12.12s: ", "width"); 8832 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { 8833 raw_printf(p->out, "%d ", p->colWidth[i]); 8834 } 8835 raw_printf(p->out, "\n"); 8836 utf8_printf(p->out, "%12.12s: %s\n", "filename", 8837 p->zDbFilename ? p->zDbFilename : ""); 8838 }else 8839 8840 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ 8841 if( nArg==2 ){ 8842 p->statsOn = (u8)booleanValue(azArg[1]); 8843 }else if( nArg==1 ){ 8844 display_stats(p->db, p, 0); 8845 }else{ 8846 raw_printf(stderr, "Usage: .stats ?on|off?\n"); 8847 rc = 1; 8848 } 8849 }else 8850 8851 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0) 8852 || (c=='i' && (strncmp(azArg[0], "indices", n)==0 8853 || strncmp(azArg[0], "indexes", n)==0) ) 8854 ){ 8855 sqlite3_stmt *pStmt; 8856 char **azResult; 8857 int nRow, nAlloc; 8858 int ii; 8859 ShellText s; 8860 initText(&s); 8861 open_db(p, 0); 8862 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 8863 if( rc ){ 8864 sqlite3_finalize(pStmt); 8865 return shellDatabaseError(p->db); 8866 } 8867 8868 if( nArg>2 && c=='i' ){ 8869 /* It is an historical accident that the .indexes command shows an error 8870 ** when called with the wrong number of arguments whereas the .tables 8871 ** command does not. */ 8872 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); 8873 rc = 1; 8874 sqlite3_finalize(pStmt); 8875 goto meta_command_exit; 8876 } 8877 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ 8878 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); 8879 if( zDbName==0 ) continue; 8880 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); 8881 if( sqlite3_stricmp(zDbName, "main")==0 ){ 8882 appendText(&s, "SELECT name FROM ", 0); 8883 }else{ 8884 appendText(&s, "SELECT ", 0); 8885 appendText(&s, zDbName, '\''); 8886 appendText(&s, "||'.'||name FROM ", 0); 8887 } 8888 appendText(&s, zDbName, '"'); 8889 appendText(&s, ".sqlite_master ", 0); 8890 if( c=='t' ){ 8891 appendText(&s," WHERE type IN ('table','view')" 8892 " AND name NOT LIKE 'sqlite_%'" 8893 " AND name LIKE ?1", 0); 8894 }else{ 8895 appendText(&s," WHERE type='index'" 8896 " AND tbl_name LIKE ?1", 0); 8897 } 8898 } 8899 rc = sqlite3_finalize(pStmt); 8900 appendText(&s, " ORDER BY 1", 0); 8901 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); 8902 freeText(&s); 8903 if( rc ) return shellDatabaseError(p->db); 8904 8905 /* Run the SQL statement prepared by the above block. Store the results 8906 ** as an array of nul-terminated strings in azResult[]. */ 8907 nRow = nAlloc = 0; 8908 azResult = 0; 8909 if( nArg>1 ){ 8910 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); 8911 }else{ 8912 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); 8913 } 8914 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 8915 if( nRow>=nAlloc ){ 8916 char **azNew; 8917 int n2 = nAlloc*2 + 10; 8918 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); 8919 if( azNew==0 ) shell_out_of_memory(); 8920 nAlloc = n2; 8921 azResult = azNew; 8922 } 8923 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 8924 if( 0==azResult[nRow] ) shell_out_of_memory(); 8925 nRow++; 8926 } 8927 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ 8928 rc = shellDatabaseError(p->db); 8929 } 8930 8931 /* Pretty-print the contents of array azResult[] to the output */ 8932 if( rc==0 && nRow>0 ){ 8933 int len, maxlen = 0; 8934 int i, j; 8935 int nPrintCol, nPrintRow; 8936 for(i=0; i<nRow; i++){ 8937 len = strlen30(azResult[i]); 8938 if( len>maxlen ) maxlen = len; 8939 } 8940 nPrintCol = 80/(maxlen+2); 8941 if( nPrintCol<1 ) nPrintCol = 1; 8942 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; 8943 for(i=0; i<nPrintRow; i++){ 8944 for(j=i; j<nRow; j+=nPrintRow){ 8945 char *zSp = j<nPrintRow ? "" : " "; 8946 utf8_printf(p->out, "%s%-*s", zSp, maxlen, 8947 azResult[j] ? azResult[j]:""); 8948 } 8949 raw_printf(p->out, "\n"); 8950 } 8951 } 8952 8953 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); 8954 sqlite3_free(azResult); 8955 }else 8956 8957 /* Begin redirecting output to the file "testcase-out.txt" */ 8958 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){ 8959 output_reset(p); 8960 p->out = output_file_open("testcase-out.txt", 0); 8961 if( p->out==0 ){ 8962 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); 8963 } 8964 if( nArg>=2 ){ 8965 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); 8966 }else{ 8967 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); 8968 } 8969 }else 8970 8971#ifndef SQLITE_UNTESTABLE 8972 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){ 8973 static const struct { 8974 const char *zCtrlName; /* Name of a test-control option */ 8975 int ctrlCode; /* Integer code for that option */ 8976 const char *zUsage; /* Usage notes */ 8977 } aCtrl[] = { 8978 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" }, 8979 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" }, 8980 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/ 8981 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/ 8982 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" }, 8983 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */ 8984 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"}, 8985 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" }, 8986 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" }, 8987 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" }, 8988 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" }, 8989#ifdef YYCOVERAGE 8990 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" }, 8991#endif 8992 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " }, 8993 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" }, 8994 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" }, 8995 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" }, 8996 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" }, 8997 }; 8998 int testctrl = -1; 8999 int iCtrl = -1; 9000 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ 9001 int isOk = 0; 9002 int i, n2; 9003 const char *zCmd = 0; 9004 9005 open_db(p, 0); 9006 zCmd = nArg>=2 ? azArg[1] : "help"; 9007 9008 /* The argument can optionally begin with "-" or "--" */ 9009 if( zCmd[0]=='-' && zCmd[1] ){ 9010 zCmd++; 9011 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 9012 } 9013 9014 /* --help lists all test-controls */ 9015 if( strcmp(zCmd,"help")==0 ){ 9016 utf8_printf(p->out, "Available test-controls:\n"); 9017 for(i=0; i<ArraySize(aCtrl); i++){ 9018 utf8_printf(p->out, " .testctrl %s %s\n", 9019 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 9020 } 9021 rc = 1; 9022 goto meta_command_exit; 9023 } 9024 9025 /* convert testctrl text option to value. allow any unique prefix 9026 ** of the option name, or a numerical value. */ 9027 n2 = strlen30(zCmd); 9028 for(i=0; i<ArraySize(aCtrl); i++){ 9029 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 9030 if( testctrl<0 ){ 9031 testctrl = aCtrl[i].ctrlCode; 9032 iCtrl = i; 9033 }else{ 9034 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n" 9035 "Use \".testctrl --help\" for help\n", zCmd); 9036 rc = 1; 9037 goto meta_command_exit; 9038 } 9039 } 9040 } 9041 if( testctrl<0 ){ 9042 utf8_printf(stderr,"Error: unknown test-control: %s\n" 9043 "Use \".testctrl --help\" for help\n", zCmd); 9044 }else{ 9045 switch(testctrl){ 9046 9047 /* sqlite3_test_control(int, db, int) */ 9048 case SQLITE_TESTCTRL_OPTIMIZATIONS: 9049 case SQLITE_TESTCTRL_RESERVE: 9050 if( nArg==3 ){ 9051 int opt = (int)strtol(azArg[2], 0, 0); 9052 rc2 = sqlite3_test_control(testctrl, p->db, opt); 9053 isOk = 3; 9054 } 9055 break; 9056 9057 /* sqlite3_test_control(int) */ 9058 case SQLITE_TESTCTRL_PRNG_SAVE: 9059 case SQLITE_TESTCTRL_PRNG_RESTORE: 9060 case SQLITE_TESTCTRL_PRNG_RESET: 9061 case SQLITE_TESTCTRL_BYTEORDER: 9062 if( nArg==2 ){ 9063 rc2 = sqlite3_test_control(testctrl); 9064 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; 9065 } 9066 break; 9067 9068 /* sqlite3_test_control(int, uint) */ 9069 case SQLITE_TESTCTRL_PENDING_BYTE: 9070 if( nArg==3 ){ 9071 unsigned int opt = (unsigned int)integerValue(azArg[2]); 9072 rc2 = sqlite3_test_control(testctrl, opt); 9073 isOk = 3; 9074 } 9075 break; 9076 9077 /* sqlite3_test_control(int, int) */ 9078 case SQLITE_TESTCTRL_ASSERT: 9079 case SQLITE_TESTCTRL_ALWAYS: 9080 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: 9081 if( nArg==3 ){ 9082 int opt = booleanValue(azArg[2]); 9083 rc2 = sqlite3_test_control(testctrl, opt); 9084 isOk = 1; 9085 } 9086 break; 9087 9088 /* sqlite3_test_control(int, int) */ 9089 case SQLITE_TESTCTRL_LOCALTIME_FAULT: 9090 case SQLITE_TESTCTRL_NEVER_CORRUPT: 9091 if( nArg==3 ){ 9092 int opt = booleanValue(azArg[2]); 9093 rc2 = sqlite3_test_control(testctrl, opt); 9094 isOk = 3; 9095 } 9096 break; 9097 9098 case SQLITE_TESTCTRL_IMPOSTER: 9099 if( nArg==5 ){ 9100 rc2 = sqlite3_test_control(testctrl, p->db, 9101 azArg[2], 9102 integerValue(azArg[3]), 9103 integerValue(azArg[4])); 9104 isOk = 3; 9105 } 9106 break; 9107 9108#ifdef YYCOVERAGE 9109 case SQLITE_TESTCTRL_PARSER_COVERAGE: 9110 if( nArg==2 ){ 9111 sqlite3_test_control(testctrl, p->out); 9112 isOk = 3; 9113 } 9114#endif 9115 } 9116 } 9117 if( isOk==0 && iCtrl>=0 ){ 9118 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage); 9119 rc = 1; 9120 }else if( isOk==1 ){ 9121 raw_printf(p->out, "%d\n", rc2); 9122 }else if( isOk==2 ){ 9123 raw_printf(p->out, "0x%08x\n", rc2); 9124 } 9125 }else 9126#endif /* !defined(SQLITE_UNTESTABLE) */ 9127 9128 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ 9129 open_db(p, 0); 9130 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); 9131 }else 9132 9133 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ 9134 if( nArg==2 ){ 9135 enableTimer = booleanValue(azArg[1]); 9136 if( enableTimer && !HAS_TIMER ){ 9137 raw_printf(stderr, "Error: timer not available on this system.\n"); 9138 enableTimer = 0; 9139 } 9140 }else{ 9141 raw_printf(stderr, "Usage: .timer on|off\n"); 9142 rc = 1; 9143 } 9144 }else 9145 9146#ifndef SQLITE_OMIT_TRACE 9147 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ 9148 int mType = 0; 9149 int jj; 9150 open_db(p, 0); 9151 for(jj=1; jj<nArg; jj++){ 9152 const char *z = azArg[jj]; 9153 if( z[0]=='-' ){ 9154 if( optionMatch(z, "expanded") ){ 9155 p->eTraceType = SHELL_TRACE_EXPANDED; 9156 } 9157#ifdef SQLITE_ENABLE_NORMALIZE 9158 else if( optionMatch(z, "normalized") ){ 9159 p->eTraceType = SHELL_TRACE_NORMALIZED; 9160 } 9161#endif 9162 else if( optionMatch(z, "plain") ){ 9163 p->eTraceType = SHELL_TRACE_PLAIN; 9164 } 9165 else if( optionMatch(z, "profile") ){ 9166 mType |= SQLITE_TRACE_PROFILE; 9167 } 9168 else if( optionMatch(z, "row") ){ 9169 mType |= SQLITE_TRACE_ROW; 9170 } 9171 else if( optionMatch(z, "stmt") ){ 9172 mType |= SQLITE_TRACE_STMT; 9173 } 9174 else if( optionMatch(z, "close") ){ 9175 mType |= SQLITE_TRACE_CLOSE; 9176 } 9177 else { 9178 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z); 9179 rc = 1; 9180 goto meta_command_exit; 9181 } 9182 }else{ 9183 output_file_close(p->traceOut); 9184 p->traceOut = output_file_open(azArg[1], 0); 9185 } 9186 } 9187 if( p->traceOut==0 ){ 9188 sqlite3_trace_v2(p->db, 0, 0, 0); 9189 }else{ 9190 if( mType==0 ) mType = SQLITE_TRACE_STMT; 9191 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); 9192 } 9193 }else 9194#endif /* !defined(SQLITE_OMIT_TRACE) */ 9195 9196#if SQLITE_USER_AUTHENTICATION 9197 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ 9198 if( nArg<2 ){ 9199 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); 9200 rc = 1; 9201 goto meta_command_exit; 9202 } 9203 open_db(p, 0); 9204 if( strcmp(azArg[1],"login")==0 ){ 9205 if( nArg!=4 ){ 9206 raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); 9207 rc = 1; 9208 goto meta_command_exit; 9209 } 9210 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3])); 9211 if( rc ){ 9212 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); 9213 rc = 1; 9214 } 9215 }else if( strcmp(azArg[1],"add")==0 ){ 9216 if( nArg!=5 ){ 9217 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); 9218 rc = 1; 9219 goto meta_command_exit; 9220 } 9221 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 9222 booleanValue(azArg[4])); 9223 if( rc ){ 9224 raw_printf(stderr, "User-Add failed: %d\n", rc); 9225 rc = 1; 9226 } 9227 }else if( strcmp(azArg[1],"edit")==0 ){ 9228 if( nArg!=5 ){ 9229 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); 9230 rc = 1; 9231 goto meta_command_exit; 9232 } 9233 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 9234 booleanValue(azArg[4])); 9235 if( rc ){ 9236 raw_printf(stderr, "User-Edit failed: %d\n", rc); 9237 rc = 1; 9238 } 9239 }else if( strcmp(azArg[1],"delete")==0 ){ 9240 if( nArg!=3 ){ 9241 raw_printf(stderr, "Usage: .user delete USER\n"); 9242 rc = 1; 9243 goto meta_command_exit; 9244 } 9245 rc = sqlite3_user_delete(p->db, azArg[2]); 9246 if( rc ){ 9247 raw_printf(stderr, "User-Delete failed: %d\n", rc); 9248 rc = 1; 9249 } 9250 }else{ 9251 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); 9252 rc = 1; 9253 goto meta_command_exit; 9254 } 9255 }else 9256#endif /* SQLITE_USER_AUTHENTICATION */ 9257 9258 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ 9259 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, 9260 sqlite3_libversion(), sqlite3_sourceid()); 9261#if SQLITE_HAVE_ZLIB 9262 utf8_printf(p->out, "zlib version %s\n", zlibVersion()); 9263#endif 9264#define CTIMEOPT_VAL_(opt) #opt 9265#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) 9266#if defined(__clang__) && defined(__clang_major__) 9267 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." 9268 CTIMEOPT_VAL(__clang_minor__) "." 9269 CTIMEOPT_VAL(__clang_patchlevel__) "\n"); 9270#elif defined(_MSC_VER) 9271 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); 9272#elif defined(__GNUC__) && defined(__VERSION__) 9273 utf8_printf(p->out, "gcc-" __VERSION__ "\n"); 9274#endif 9275 }else 9276 9277 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ 9278 const char *zDbName = nArg==2 ? azArg[1] : "main"; 9279 sqlite3_vfs *pVfs = 0; 9280 if( p->db ){ 9281 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); 9282 if( pVfs ){ 9283 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); 9284 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 9285 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 9286 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 9287 } 9288 } 9289 }else 9290 9291 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ 9292 sqlite3_vfs *pVfs; 9293 sqlite3_vfs *pCurrent = 0; 9294 if( p->db ){ 9295 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); 9296 } 9297 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ 9298 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, 9299 pVfs==pCurrent ? " <--- CURRENT" : ""); 9300 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 9301 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 9302 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 9303 if( pVfs->pNext ){ 9304 raw_printf(p->out, "-----------------------------------\n"); 9305 } 9306 } 9307 }else 9308 9309 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ 9310 const char *zDbName = nArg==2 ? azArg[1] : "main"; 9311 char *zVfsName = 0; 9312 if( p->db ){ 9313 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); 9314 if( zVfsName ){ 9315 utf8_printf(p->out, "%s\n", zVfsName); 9316 sqlite3_free(zVfsName); 9317 } 9318 } 9319 }else 9320 9321#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 9322 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ 9323 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff; 9324 }else 9325#endif 9326 9327 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ 9328 int j; 9329 assert( nArg<=ArraySize(azArg) ); 9330 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){ 9331 p->colWidth[j-1] = (int)integerValue(azArg[j]); 9332 } 9333 }else 9334 9335 { 9336 utf8_printf(stderr, "Error: unknown command or invalid arguments: " 9337 " \"%s\". Enter \".help\" for help\n", azArg[0]); 9338 rc = 1; 9339 } 9340 9341meta_command_exit: 9342 if( p->outCount ){ 9343 p->outCount--; 9344 if( p->outCount==0 ) output_reset(p); 9345 } 9346 return rc; 9347} 9348 9349/* 9350** Return TRUE if a semicolon occurs anywhere in the first N characters 9351** of string z[]. 9352*/ 9353static int line_contains_semicolon(const char *z, int N){ 9354 int i; 9355 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; } 9356 return 0; 9357} 9358 9359/* 9360** Test to see if a line consists entirely of whitespace. 9361*/ 9362static int _all_whitespace(const char *z){ 9363 for(; *z; z++){ 9364 if( IsSpace(z[0]) ) continue; 9365 if( *z=='/' && z[1]=='*' ){ 9366 z += 2; 9367 while( *z && (*z!='*' || z[1]!='/') ){ z++; } 9368 if( *z==0 ) return 0; 9369 z++; 9370 continue; 9371 } 9372 if( *z=='-' && z[1]=='-' ){ 9373 z += 2; 9374 while( *z && *z!='\n' ){ z++; } 9375 if( *z==0 ) return 1; 9376 continue; 9377 } 9378 return 0; 9379 } 9380 return 1; 9381} 9382 9383/* 9384** Return TRUE if the line typed in is an SQL command terminator other 9385** than a semi-colon. The SQL Server style "go" command is understood 9386** as is the Oracle "/". 9387*/ 9388static int line_is_command_terminator(const char *zLine){ 9389 while( IsSpace(zLine[0]) ){ zLine++; }; 9390 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){ 9391 return 1; /* Oracle */ 9392 } 9393 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' 9394 && _all_whitespace(&zLine[2]) ){ 9395 return 1; /* SQL Server */ 9396 } 9397 return 0; 9398} 9399 9400/* 9401** We need a default sqlite3_complete() implementation to use in case 9402** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes 9403** any arbitrary text is a complete SQL statement. This is not very 9404** user-friendly, but it does seem to work. 9405*/ 9406#ifdef SQLITE_OMIT_COMPLETE 9407#define sqlite3_complete(x) 1 9408#endif 9409 9410/* 9411** Return true if zSql is a complete SQL statement. Return false if it 9412** ends in the middle of a string literal or C-style comment. 9413*/ 9414static int line_is_complete(char *zSql, int nSql){ 9415 int rc; 9416 if( zSql==0 ) return 1; 9417 zSql[nSql] = ';'; 9418 zSql[nSql+1] = 0; 9419 rc = sqlite3_complete(zSql); 9420 zSql[nSql] = 0; 9421 return rc; 9422} 9423 9424/* 9425** Run a single line of SQL. Return the number of errors. 9426*/ 9427static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ 9428 int rc; 9429 char *zErrMsg = 0; 9430 9431 open_db(p, 0); 9432 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); 9433 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 9434 BEGIN_TIMER; 9435 rc = shell_exec(p, zSql, &zErrMsg); 9436 END_TIMER; 9437 if( rc || zErrMsg ){ 9438 char zPrefix[100]; 9439 if( in!=0 || !stdin_is_interactive ){ 9440 sqlite3_snprintf(sizeof(zPrefix), zPrefix, 9441 "Error: near line %d:", startline); 9442 }else{ 9443 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); 9444 } 9445 if( zErrMsg!=0 ){ 9446 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); 9447 sqlite3_free(zErrMsg); 9448 zErrMsg = 0; 9449 }else{ 9450 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); 9451 } 9452 return 1; 9453 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ 9454 raw_printf(p->out, "changes: %3d total_changes: %d\n", 9455 sqlite3_changes(p->db), sqlite3_total_changes(p->db)); 9456 } 9457 return 0; 9458} 9459 9460 9461/* 9462** Read input from *in and process it. If *in==0 then input 9463** is interactive - the user is typing it it. Otherwise, input 9464** is coming from a file or device. A prompt is issued and history 9465** is saved only if input is interactive. An interrupt signal will 9466** cause this routine to exit immediately, unless input is interactive. 9467** 9468** Return the number of errors. 9469*/ 9470static int process_input(ShellState *p){ 9471 char *zLine = 0; /* A single input line */ 9472 char *zSql = 0; /* Accumulated SQL text */ 9473 int nLine; /* Length of current line */ 9474 int nSql = 0; /* Bytes of zSql[] used */ 9475 int nAlloc = 0; /* Allocated zSql[] space */ 9476 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */ 9477 int rc; /* Error code */ 9478 int errCnt = 0; /* Number of errors seen */ 9479 int startline = 0; /* Line number for start of current input */ 9480 9481 p->lineno = 0; 9482 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ 9483 fflush(p->out); 9484 zLine = one_input_line(p->in, zLine, nSql>0); 9485 if( zLine==0 ){ 9486 /* End of input */ 9487 if( p->in==0 && stdin_is_interactive ) printf("\n"); 9488 break; 9489 } 9490 if( seenInterrupt ){ 9491 if( p->in!=0 ) break; 9492 seenInterrupt = 0; 9493 } 9494 p->lineno++; 9495 if( nSql==0 && _all_whitespace(zLine) ){ 9496 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 9497 continue; 9498 } 9499 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ 9500 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 9501 if( zLine[0]=='.' ){ 9502 rc = do_meta_command(zLine, p); 9503 if( rc==2 ){ /* exit requested */ 9504 break; 9505 }else if( rc ){ 9506 errCnt++; 9507 } 9508 } 9509 continue; 9510 } 9511 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ 9512 memcpy(zLine,";",2); 9513 } 9514 nLine = strlen30(zLine); 9515 if( nSql+nLine+2>=nAlloc ){ 9516 nAlloc = nSql+nLine+100; 9517 zSql = realloc(zSql, nAlloc); 9518 if( zSql==0 ) shell_out_of_memory(); 9519 } 9520 nSqlPrior = nSql; 9521 if( nSql==0 ){ 9522 int i; 9523 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} 9524 assert( nAlloc>0 && zSql!=0 ); 9525 memcpy(zSql, zLine+i, nLine+1-i); 9526 startline = p->lineno; 9527 nSql = nLine-i; 9528 }else{ 9529 zSql[nSql++] = '\n'; 9530 memcpy(zSql+nSql, zLine, nLine+1); 9531 nSql += nLine; 9532 } 9533 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) 9534 && sqlite3_complete(zSql) ){ 9535 errCnt += runOneSqlLine(p, zSql, p->in, startline); 9536 nSql = 0; 9537 if( p->outCount ){ 9538 output_reset(p); 9539 p->outCount = 0; 9540 }else{ 9541 clearTempFile(p); 9542 } 9543 }else if( nSql && _all_whitespace(zSql) ){ 9544 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql); 9545 nSql = 0; 9546 } 9547 } 9548 if( nSql && !_all_whitespace(zSql) ){ 9549 errCnt += runOneSqlLine(p, zSql, p->in, startline); 9550 } 9551 free(zSql); 9552 free(zLine); 9553 return errCnt>0; 9554} 9555 9556/* 9557** Return a pathname which is the user's home directory. A 9558** 0 return indicates an error of some kind. 9559*/ 9560static char *find_home_dir(int clearFlag){ 9561 static char *home_dir = NULL; 9562 if( clearFlag ){ 9563 free(home_dir); 9564 home_dir = 0; 9565 return 0; 9566 } 9567 if( home_dir ) return home_dir; 9568 9569#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ 9570 && !defined(__RTP__) && !defined(_WRS_KERNEL) 9571 { 9572 struct passwd *pwent; 9573 uid_t uid = getuid(); 9574 if( (pwent=getpwuid(uid)) != NULL) { 9575 home_dir = pwent->pw_dir; 9576 } 9577 } 9578#endif 9579 9580#if defined(_WIN32_WCE) 9581 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() 9582 */ 9583 home_dir = "/"; 9584#else 9585 9586#if defined(_WIN32) || defined(WIN32) 9587 if (!home_dir) { 9588 home_dir = getenv("USERPROFILE"); 9589 } 9590#endif 9591 9592 if (!home_dir) { 9593 home_dir = getenv("HOME"); 9594 } 9595 9596#if defined(_WIN32) || defined(WIN32) 9597 if (!home_dir) { 9598 char *zDrive, *zPath; 9599 int n; 9600 zDrive = getenv("HOMEDRIVE"); 9601 zPath = getenv("HOMEPATH"); 9602 if( zDrive && zPath ){ 9603 n = strlen30(zDrive) + strlen30(zPath) + 1; 9604 home_dir = malloc( n ); 9605 if( home_dir==0 ) return 0; 9606 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); 9607 return home_dir; 9608 } 9609 home_dir = "c:\\"; 9610 } 9611#endif 9612 9613#endif /* !_WIN32_WCE */ 9614 9615 if( home_dir ){ 9616 int n = strlen30(home_dir) + 1; 9617 char *z = malloc( n ); 9618 if( z ) memcpy(z, home_dir, n); 9619 home_dir = z; 9620 } 9621 9622 return home_dir; 9623} 9624 9625/* 9626** Read input from the file given by sqliterc_override. Or if that 9627** parameter is NULL, take input from ~/.sqliterc 9628** 9629** Returns the number of errors. 9630*/ 9631static void process_sqliterc( 9632 ShellState *p, /* Configuration data */ 9633 const char *sqliterc_override /* Name of config file. NULL to use default */ 9634){ 9635 char *home_dir = NULL; 9636 const char *sqliterc = sqliterc_override; 9637 char *zBuf = 0; 9638 FILE *inSaved = p->in; 9639 int savedLineno = p->lineno; 9640 9641 if (sqliterc == NULL) { 9642 home_dir = find_home_dir(0); 9643 if( home_dir==0 ){ 9644 raw_printf(stderr, "-- warning: cannot find home directory;" 9645 " cannot read ~/.sqliterc\n"); 9646 return; 9647 } 9648 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); 9649 sqliterc = zBuf; 9650 } 9651 p->in = fopen(sqliterc,"rb"); 9652 if( p->in ){ 9653 if( stdin_is_interactive ){ 9654 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); 9655 } 9656 process_input(p); 9657 fclose(p->in); 9658 } 9659 p->in = inSaved; 9660 p->lineno = savedLineno; 9661 sqlite3_free(zBuf); 9662} 9663 9664/* 9665** Show available command line options 9666*/ 9667static const char zOptions[] = 9668#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 9669 " -A ARGS... run \".archive ARGS\" and exit\n" 9670#endif 9671 " -append append the database to the end of the file\n" 9672 " -ascii set output mode to 'ascii'\n" 9673 " -bail stop after hitting an error\n" 9674 " -batch force batch I/O\n" 9675 " -column set output mode to 'column'\n" 9676 " -cmd COMMAND run \"COMMAND\" before reading stdin\n" 9677 " -csv set output mode to 'csv'\n" 9678#if defined(SQLITE_ENABLE_DESERIALIZE) 9679 " -deserialize open the database using sqlite3_deserialize()\n" 9680#endif 9681 " -echo print commands before execution\n" 9682 " -init FILENAME read/process named file\n" 9683 " -[no]header turn headers on or off\n" 9684#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 9685 " -heap SIZE Size of heap for memsys3 or memsys5\n" 9686#endif 9687 " -help show this message\n" 9688 " -html set output mode to HTML\n" 9689 " -interactive force interactive I/O\n" 9690 " -line set output mode to 'line'\n" 9691 " -list set output mode to 'list'\n" 9692 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" 9693#if defined(SQLITE_ENABLE_DESERIALIZE) 9694 " -maxsize N maximum size for a --deserialize database\n" 9695#endif 9696 " -memtrace trace all memory allocations and deallocations\n" 9697 " -mmap N default mmap size set to N\n" 9698#ifdef SQLITE_ENABLE_MULTIPLEX 9699 " -multiplex enable the multiplexor VFS\n" 9700#endif 9701 " -newline SEP set output row separator. Default: '\\n'\n" 9702 " -nullvalue TEXT set text string for NULL values. Default ''\n" 9703 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" 9704 " -quote set output mode to 'quote'\n" 9705 " -readonly open the database read-only\n" 9706 " -separator SEP set output column separator. Default: '|'\n" 9707#ifdef SQLITE_ENABLE_SORTER_REFERENCES 9708 " -sorterref SIZE sorter references threshold size\n" 9709#endif 9710 " -stats print memory stats before each finalize\n" 9711 " -version show SQLite version\n" 9712 " -vfs NAME use NAME as the default VFS\n" 9713#ifdef SQLITE_ENABLE_VFSTRACE 9714 " -vfstrace enable tracing of all VFS calls\n" 9715#endif 9716#ifdef SQLITE_HAVE_ZLIB 9717 " -zip open the file as a ZIP Archive\n" 9718#endif 9719; 9720static void usage(int showDetail){ 9721 utf8_printf(stderr, 9722 "Usage: %s [OPTIONS] FILENAME [SQL]\n" 9723 "FILENAME is the name of an SQLite database. A new database is created\n" 9724 "if the file does not previously exist.\n", Argv0); 9725 if( showDetail ){ 9726 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); 9727 }else{ 9728 raw_printf(stderr, "Use the -help option for additional information\n"); 9729 } 9730 exit(1); 9731} 9732 9733/* 9734** Internal check: Verify that the SQLite is uninitialized. Print a 9735** error message if it is initialized. 9736*/ 9737static void verify_uninitialized(void){ 9738 if( sqlite3_config(-1)==SQLITE_MISUSE ){ 9739 utf8_printf(stdout, "WARNING: attempt to configure SQLite after" 9740 " initialization.\n"); 9741 } 9742} 9743 9744/* 9745** Initialize the state information in data 9746*/ 9747static void main_init(ShellState *data) { 9748 memset(data, 0, sizeof(*data)); 9749 data->normalMode = data->cMode = data->mode = MODE_List; 9750 data->autoExplain = 1; 9751 memcpy(data->colSeparator,SEP_Column, 2); 9752 memcpy(data->rowSeparator,SEP_Row, 2); 9753 data->showHeader = 0; 9754 data->shellFlgs = SHFLG_Lookaside; 9755 verify_uninitialized(); 9756 sqlite3_config(SQLITE_CONFIG_URI, 1); 9757 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); 9758 sqlite3_config(SQLITE_CONFIG_MULTITHREAD); 9759 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); 9760 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); 9761} 9762 9763/* 9764** Output text to the console in a font that attracts extra attention. 9765*/ 9766#ifdef _WIN32 9767static void printBold(const char *zText){ 9768 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 9769 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; 9770 GetConsoleScreenBufferInfo(out, &defaultScreenInfo); 9771 SetConsoleTextAttribute(out, 9772 FOREGROUND_RED|FOREGROUND_INTENSITY 9773 ); 9774 printf("%s", zText); 9775 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); 9776} 9777#else 9778static void printBold(const char *zText){ 9779 printf("\033[1m%s\033[0m", zText); 9780} 9781#endif 9782 9783/* 9784** Get the argument to an --option. Throw an error and die if no argument 9785** is available. 9786*/ 9787static char *cmdline_option_value(int argc, char **argv, int i){ 9788 if( i==argc ){ 9789 utf8_printf(stderr, "%s: Error: missing argument to %s\n", 9790 argv[0], argv[argc-1]); 9791 exit(1); 9792 } 9793 return argv[i]; 9794} 9795 9796#ifndef SQLITE_SHELL_IS_UTF8 9797# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) 9798# define SQLITE_SHELL_IS_UTF8 (0) 9799# else 9800# define SQLITE_SHELL_IS_UTF8 (1) 9801# endif 9802#endif 9803 9804#if SQLITE_SHELL_IS_UTF8 9805int SQLITE_CDECL main(int argc, char **argv){ 9806#else 9807int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ 9808 char **argv; 9809#endif 9810 char *zErrMsg = 0; 9811 ShellState data; 9812 const char *zInitFile = 0; 9813 int i; 9814 int rc = 0; 9815 int warnInmemoryDb = 0; 9816 int readStdin = 1; 9817 int nCmd = 0; 9818 char **azCmd = 0; 9819 const char *zVfs = 0; /* Value of -vfs command-line option */ 9820#if !SQLITE_SHELL_IS_UTF8 9821 char **argvToFree = 0; 9822 int argcToFree = 0; 9823#endif 9824 9825 setBinaryMode(stdin, 0); 9826 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ 9827 stdin_is_interactive = isatty(0); 9828 stdout_is_console = isatty(1); 9829 9830#if !defined(_WIN32_WCE) 9831 if( getenv("SQLITE_DEBUG_BREAK") ){ 9832 if( isatty(0) && isatty(2) ){ 9833 fprintf(stderr, 9834 "attach debugger to process %d and press any key to continue.\n", 9835 GETPID()); 9836 fgetc(stdin); 9837 }else{ 9838#if defined(_WIN32) || defined(WIN32) 9839 DebugBreak(); 9840#elif defined(SIGTRAP) 9841 raise(SIGTRAP); 9842#endif 9843 } 9844 } 9845#endif 9846 9847#if USE_SYSTEM_SQLITE+0!=1 9848 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ 9849 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", 9850 sqlite3_sourceid(), SQLITE_SOURCE_ID); 9851 exit(1); 9852 } 9853#endif 9854 main_init(&data); 9855 9856 /* On Windows, we must translate command-line arguments into UTF-8. 9857 ** The SQLite memory allocator subsystem has to be enabled in order to 9858 ** do this. But we want to run an sqlite3_shutdown() afterwards so that 9859 ** subsequent sqlite3_config() calls will work. So copy all results into 9860 ** memory that does not come from the SQLite memory allocator. 9861 */ 9862#if !SQLITE_SHELL_IS_UTF8 9863 sqlite3_initialize(); 9864 argvToFree = malloc(sizeof(argv[0])*argc*2); 9865 argcToFree = argc; 9866 argv = argvToFree + argc; 9867 if( argv==0 ) shell_out_of_memory(); 9868 for(i=0; i<argc; i++){ 9869 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); 9870 int n; 9871 if( z==0 ) shell_out_of_memory(); 9872 n = (int)strlen(z); 9873 argv[i] = malloc( n+1 ); 9874 if( argv[i]==0 ) shell_out_of_memory(); 9875 memcpy(argv[i], z, n+1); 9876 argvToFree[i] = argv[i]; 9877 sqlite3_free(z); 9878 } 9879 sqlite3_shutdown(); 9880#endif 9881 9882 assert( argc>=1 && argv && argv[0] ); 9883 Argv0 = argv[0]; 9884 9885 /* Make sure we have a valid signal handler early, before anything 9886 ** else is done. 9887 */ 9888#ifdef SIGINT 9889 signal(SIGINT, interrupt_handler); 9890#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 9891 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); 9892#endif 9893 9894#ifdef SQLITE_SHELL_DBNAME_PROC 9895 { 9896 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name 9897 ** of a C-function that will provide the name of the database file. Use 9898 ** this compile-time option to embed this shell program in larger 9899 ** applications. */ 9900 extern void SQLITE_SHELL_DBNAME_PROC(const char**); 9901 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename); 9902 warnInmemoryDb = 0; 9903 } 9904#endif 9905 9906 /* Do an initial pass through the command-line argument to locate 9907 ** the name of the database file, the name of the initialization file, 9908 ** the size of the alternative malloc heap, 9909 ** and the first command to execute. 9910 */ 9911 verify_uninitialized(); 9912 for(i=1; i<argc; i++){ 9913 char *z; 9914 z = argv[i]; 9915 if( z[0]!='-' ){ 9916 if( data.zDbFilename==0 ){ 9917 data.zDbFilename = z; 9918 }else{ 9919 /* Excesss arguments are interpreted as SQL (or dot-commands) and 9920 ** mean that nothing is read from stdin */ 9921 readStdin = 0; 9922 nCmd++; 9923 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); 9924 if( azCmd==0 ) shell_out_of_memory(); 9925 azCmd[nCmd-1] = z; 9926 } 9927 } 9928 if( z[1]=='-' ) z++; 9929 if( strcmp(z,"-separator")==0 9930 || strcmp(z,"-nullvalue")==0 9931 || strcmp(z,"-newline")==0 9932 || strcmp(z,"-cmd")==0 9933 ){ 9934 (void)cmdline_option_value(argc, argv, ++i); 9935 }else if( strcmp(z,"-init")==0 ){ 9936 zInitFile = cmdline_option_value(argc, argv, ++i); 9937 }else if( strcmp(z,"-batch")==0 ){ 9938 /* Need to check for batch mode here to so we can avoid printing 9939 ** informational messages (like from process_sqliterc) before 9940 ** we do the actual processing of arguments later in a second pass. 9941 */ 9942 stdin_is_interactive = 0; 9943 }else if( strcmp(z,"-heap")==0 ){ 9944#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 9945 const char *zSize; 9946 sqlite3_int64 szHeap; 9947 9948 zSize = cmdline_option_value(argc, argv, ++i); 9949 szHeap = integerValue(zSize); 9950 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; 9951 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); 9952#else 9953 (void)cmdline_option_value(argc, argv, ++i); 9954#endif 9955 }else if( strcmp(z,"-pagecache")==0 ){ 9956 int n, sz; 9957 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 9958 if( sz>70000 ) sz = 70000; 9959 if( sz<0 ) sz = 0; 9960 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 9961 sqlite3_config(SQLITE_CONFIG_PAGECACHE, 9962 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); 9963 data.shellFlgs |= SHFLG_Pagecache; 9964 }else if( strcmp(z,"-lookaside")==0 ){ 9965 int n, sz; 9966 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 9967 if( sz<0 ) sz = 0; 9968 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 9969 if( n<0 ) n = 0; 9970 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); 9971 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; 9972#ifdef SQLITE_ENABLE_VFSTRACE 9973 }else if( strcmp(z,"-vfstrace")==0 ){ 9974 extern int vfstrace_register( 9975 const char *zTraceName, 9976 const char *zOldVfsName, 9977 int (*xOut)(const char*,void*), 9978 void *pOutArg, 9979 int makeDefault 9980 ); 9981 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); 9982#endif 9983#ifdef SQLITE_ENABLE_MULTIPLEX 9984 }else if( strcmp(z,"-multiplex")==0 ){ 9985 extern int sqlite3_multiple_initialize(const char*,int); 9986 sqlite3_multiplex_initialize(0, 1); 9987#endif 9988 }else if( strcmp(z,"-mmap")==0 ){ 9989 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 9990 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); 9991#ifdef SQLITE_ENABLE_SORTER_REFERENCES 9992 }else if( strcmp(z,"-sorterref")==0 ){ 9993 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 9994 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); 9995#endif 9996 }else if( strcmp(z,"-vfs")==0 ){ 9997 zVfs = cmdline_option_value(argc, argv, ++i); 9998#ifdef SQLITE_HAVE_ZLIB 9999 }else if( strcmp(z,"-zip")==0 ){ 10000 data.openMode = SHELL_OPEN_ZIPFILE; 10001#endif 10002 }else if( strcmp(z,"-append")==0 ){ 10003 data.openMode = SHELL_OPEN_APPENDVFS; 10004#ifdef SQLITE_ENABLE_DESERIALIZE 10005 }else if( strcmp(z,"-deserialize")==0 ){ 10006 data.openMode = SHELL_OPEN_DESERIALIZE; 10007 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 10008 data.szMax = integerValue(argv[++i]); 10009#endif 10010 }else if( strcmp(z,"-readonly")==0 ){ 10011 data.openMode = SHELL_OPEN_READONLY; 10012#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 10013 }else if( strncmp(z, "-A",2)==0 ){ 10014 /* All remaining command-line arguments are passed to the ".archive" 10015 ** command, so ignore them */ 10016 break; 10017#endif 10018 }else if( strcmp(z, "-memtrace")==0 ){ 10019 sqlite3MemTraceActivate(stderr); 10020 } 10021 } 10022 verify_uninitialized(); 10023 10024 10025#ifdef SQLITE_SHELL_INIT_PROC 10026 { 10027 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name 10028 ** of a C-function that will perform initialization actions on SQLite that 10029 ** occur just before or after sqlite3_initialize(). Use this compile-time 10030 ** option to embed this shell program in larger applications. */ 10031 extern void SQLITE_SHELL_INIT_PROC(void); 10032 SQLITE_SHELL_INIT_PROC(); 10033 } 10034#else 10035 /* All the sqlite3_config() calls have now been made. So it is safe 10036 ** to call sqlite3_initialize() and process any command line -vfs option. */ 10037 sqlite3_initialize(); 10038#endif 10039 10040 if( zVfs ){ 10041 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); 10042 if( pVfs ){ 10043 sqlite3_vfs_register(pVfs, 1); 10044 }else{ 10045 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); 10046 exit(1); 10047 } 10048 } 10049 10050 if( data.zDbFilename==0 ){ 10051#ifndef SQLITE_OMIT_MEMORYDB 10052 data.zDbFilename = ":memory:"; 10053 warnInmemoryDb = argc==1; 10054#else 10055 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); 10056 return 1; 10057#endif 10058 } 10059 data.out = stdout; 10060 sqlite3_appendvfs_init(0,0,0); 10061 10062 /* Go ahead and open the database file if it already exists. If the 10063 ** file does not exist, delay opening it. This prevents empty database 10064 ** files from being created if a user mistypes the database name argument 10065 ** to the sqlite command-line tool. 10066 */ 10067 if( access(data.zDbFilename, 0)==0 ){ 10068 open_db(&data, 0); 10069 } 10070 10071 /* Process the initialization file if there is one. If no -init option 10072 ** is given on the command line, look for a file named ~/.sqliterc and 10073 ** try to process it. 10074 */ 10075 process_sqliterc(&data,zInitFile); 10076 10077 /* Make a second pass through the command-line argument and set 10078 ** options. This second pass is delayed until after the initialization 10079 ** file is processed so that the command-line arguments will override 10080 ** settings in the initialization file. 10081 */ 10082 for(i=1; i<argc; i++){ 10083 char *z = argv[i]; 10084 if( z[0]!='-' ) continue; 10085 if( z[1]=='-' ){ z++; } 10086 if( strcmp(z,"-init")==0 ){ 10087 i++; 10088 }else if( strcmp(z,"-html")==0 ){ 10089 data.mode = MODE_Html; 10090 }else if( strcmp(z,"-list")==0 ){ 10091 data.mode = MODE_List; 10092 }else if( strcmp(z,"-quote")==0 ){ 10093 data.mode = MODE_Quote; 10094 }else if( strcmp(z,"-line")==0 ){ 10095 data.mode = MODE_Line; 10096 }else if( strcmp(z,"-column")==0 ){ 10097 data.mode = MODE_Column; 10098 }else if( strcmp(z,"-csv")==0 ){ 10099 data.mode = MODE_Csv; 10100 memcpy(data.colSeparator,",",2); 10101#ifdef SQLITE_HAVE_ZLIB 10102 }else if( strcmp(z,"-zip")==0 ){ 10103 data.openMode = SHELL_OPEN_ZIPFILE; 10104#endif 10105 }else if( strcmp(z,"-append")==0 ){ 10106 data.openMode = SHELL_OPEN_APPENDVFS; 10107#ifdef SQLITE_ENABLE_DESERIALIZE 10108 }else if( strcmp(z,"-deserialize")==0 ){ 10109 data.openMode = SHELL_OPEN_DESERIALIZE; 10110 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 10111 data.szMax = integerValue(argv[++i]); 10112#endif 10113 }else if( strcmp(z,"-readonly")==0 ){ 10114 data.openMode = SHELL_OPEN_READONLY; 10115 }else if( strcmp(z,"-ascii")==0 ){ 10116 data.mode = MODE_Ascii; 10117 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 10118 SEP_Unit); 10119 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 10120 SEP_Record); 10121 }else if( strcmp(z,"-separator")==0 ){ 10122 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 10123 "%s",cmdline_option_value(argc,argv,++i)); 10124 }else if( strcmp(z,"-newline")==0 ){ 10125 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 10126 "%s",cmdline_option_value(argc,argv,++i)); 10127 }else if( strcmp(z,"-nullvalue")==0 ){ 10128 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, 10129 "%s",cmdline_option_value(argc,argv,++i)); 10130 }else if( strcmp(z,"-header")==0 ){ 10131 data.showHeader = 1; 10132 }else if( strcmp(z,"-noheader")==0 ){ 10133 data.showHeader = 0; 10134 }else if( strcmp(z,"-echo")==0 ){ 10135 ShellSetFlag(&data, SHFLG_Echo); 10136 }else if( strcmp(z,"-eqp")==0 ){ 10137 data.autoEQP = AUTOEQP_on; 10138 }else if( strcmp(z,"-eqpfull")==0 ){ 10139 data.autoEQP = AUTOEQP_full; 10140 }else if( strcmp(z,"-stats")==0 ){ 10141 data.statsOn = 1; 10142 }else if( strcmp(z,"-scanstats")==0 ){ 10143 data.scanstatsOn = 1; 10144 }else if( strcmp(z,"-backslash")==0 ){ 10145 /* Undocumented command-line option: -backslash 10146 ** Causes C-style backslash escapes to be evaluated in SQL statements 10147 ** prior to sending the SQL into SQLite. Useful for injecting 10148 ** crazy bytes in the middle of SQL statements for testing and debugging. 10149 */ 10150 ShellSetFlag(&data, SHFLG_Backslash); 10151 }else if( strcmp(z,"-bail")==0 ){ 10152 bail_on_error = 1; 10153 }else if( strcmp(z,"-version")==0 ){ 10154 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 10155 return 0; 10156 }else if( strcmp(z,"-interactive")==0 ){ 10157 stdin_is_interactive = 1; 10158 }else if( strcmp(z,"-batch")==0 ){ 10159 stdin_is_interactive = 0; 10160 }else if( strcmp(z,"-heap")==0 ){ 10161 i++; 10162 }else if( strcmp(z,"-pagecache")==0 ){ 10163 i+=2; 10164 }else if( strcmp(z,"-lookaside")==0 ){ 10165 i+=2; 10166 }else if( strcmp(z,"-mmap")==0 ){ 10167 i++; 10168 }else if( strcmp(z,"-memtrace")==0 ){ 10169 i++; 10170#ifdef SQLITE_ENABLE_SORTER_REFERENCES 10171 }else if( strcmp(z,"-sorterref")==0 ){ 10172 i++; 10173#endif 10174 }else if( strcmp(z,"-vfs")==0 ){ 10175 i++; 10176#ifdef SQLITE_ENABLE_VFSTRACE 10177 }else if( strcmp(z,"-vfstrace")==0 ){ 10178 i++; 10179#endif 10180#ifdef SQLITE_ENABLE_MULTIPLEX 10181 }else if( strcmp(z,"-multiplex")==0 ){ 10182 i++; 10183#endif 10184 }else if( strcmp(z,"-help")==0 ){ 10185 usage(1); 10186 }else if( strcmp(z,"-cmd")==0 ){ 10187 /* Run commands that follow -cmd first and separately from commands 10188 ** that simply appear on the command-line. This seems goofy. It would 10189 ** be better if all commands ran in the order that they appear. But 10190 ** we retain the goofy behavior for historical compatibility. */ 10191 if( i==argc-1 ) break; 10192 z = cmdline_option_value(argc,argv,++i); 10193 if( z[0]=='.' ){ 10194 rc = do_meta_command(z, &data); 10195 if( rc && bail_on_error ) return rc==2 ? 0 : rc; 10196 }else{ 10197 open_db(&data, 0); 10198 rc = shell_exec(&data, z, &zErrMsg); 10199 if( zErrMsg!=0 ){ 10200 utf8_printf(stderr,"Error: %s\n", zErrMsg); 10201 if( bail_on_error ) return rc!=0 ? rc : 1; 10202 }else if( rc!=0 ){ 10203 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); 10204 if( bail_on_error ) return rc; 10205 } 10206 } 10207#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 10208 }else if( strncmp(z, "-A", 2)==0 ){ 10209 if( nCmd>0 ){ 10210 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" 10211 " with \"%s\"\n", z); 10212 return 1; 10213 } 10214 open_db(&data, OPEN_DB_ZIPFILE); 10215 if( z[2] ){ 10216 argv[i] = &z[2]; 10217 arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); 10218 }else{ 10219 arDotCommand(&data, 1, argv+i, argc-i); 10220 } 10221 readStdin = 0; 10222 break; 10223#endif 10224 }else{ 10225 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); 10226 raw_printf(stderr,"Use -help for a list of options.\n"); 10227 return 1; 10228 } 10229 data.cMode = data.mode; 10230 } 10231 10232 if( !readStdin ){ 10233 /* Run all arguments that do not begin with '-' as if they were separate 10234 ** command-line inputs, except for the argToSkip argument which contains 10235 ** the database filename. 10236 */ 10237 for(i=0; i<nCmd; i++){ 10238 if( azCmd[i][0]=='.' ){ 10239 rc = do_meta_command(azCmd[i], &data); 10240 if( rc ) return rc==2 ? 0 : rc; 10241 }else{ 10242 open_db(&data, 0); 10243 rc = shell_exec(&data, azCmd[i], &zErrMsg); 10244 if( zErrMsg!=0 ){ 10245 utf8_printf(stderr,"Error: %s\n", zErrMsg); 10246 return rc!=0 ? rc : 1; 10247 }else if( rc!=0 ){ 10248 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); 10249 return rc; 10250 } 10251 } 10252 } 10253 free(azCmd); 10254 }else{ 10255 /* Run commands received from standard input 10256 */ 10257 if( stdin_is_interactive ){ 10258 char *zHome; 10259 char *zHistory; 10260 int nHistory; 10261 printf( 10262 "SQLite version %s %.19s\n" /*extra-version-info*/ 10263 "Enter \".help\" for usage hints.\n", 10264 sqlite3_libversion(), sqlite3_sourceid() 10265 ); 10266 if( warnInmemoryDb ){ 10267 printf("Connected to a "); 10268 printBold("transient in-memory database"); 10269 printf(".\nUse \".open FILENAME\" to reopen on a " 10270 "persistent database.\n"); 10271 } 10272 zHistory = getenv("SQLITE_HISTORY"); 10273 if( zHistory ){ 10274 zHistory = strdup(zHistory); 10275 }else if( (zHome = find_home_dir(0))!=0 ){ 10276 nHistory = strlen30(zHome) + 20; 10277 if( (zHistory = malloc(nHistory))!=0 ){ 10278 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); 10279 } 10280 } 10281 if( zHistory ){ shell_read_history(zHistory); } 10282#if HAVE_READLINE || HAVE_EDITLINE 10283 rl_attempted_completion_function = readline_completion; 10284#elif HAVE_LINENOISE 10285 linenoiseSetCompletionCallback(linenoise_completion); 10286#endif 10287 data.in = 0; 10288 rc = process_input(&data); 10289 if( zHistory ){ 10290 shell_stifle_history(2000); 10291 shell_write_history(zHistory); 10292 free(zHistory); 10293 } 10294 }else{ 10295 data.in = stdin; 10296 rc = process_input(&data); 10297 } 10298 } 10299 set_table_name(&data, 0); 10300 if( data.db ){ 10301 session_close_all(&data); 10302 close_db(data.db); 10303 } 10304 sqlite3_free(data.zFreeOnClose); 10305 find_home_dir(1); 10306 output_reset(&data); 10307 data.doXdgOpen = 0; 10308 clearTempFile(&data); 10309#if !SQLITE_SHELL_IS_UTF8 10310 for(i=0; i<argcToFree; i++) free(argvToFree[i]); 10311 free(argvToFree); 10312#endif 10313 /* Clear the global data structure so that valgrind will detect memory 10314 ** leaks */ 10315 memset(&data, 0, sizeof(data)); 10316 return rc; 10317} 10318