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, (size_t)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, (size_t)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, (size_t)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 ".filectrl CMD ... Run various sqlite3_file_control() operations", 3514 " Run \".filectrl\" with no arguments for details", 3515 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", 3516 ".headers on|off Turn display of headers on or off", 3517 ".help ?-all? ?PATTERN? Show help text for PATTERN", 3518 ".import FILE TABLE Import data from FILE into TABLE", 3519#ifndef SQLITE_OMIT_TEST_CONTROL 3520 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", 3521#endif 3522 ".indexes ?TABLE? Show names of indexes", 3523 " If TABLE is specified, only show indexes for", 3524 " tables matching TABLE using the LIKE operator.", 3525#ifdef SQLITE_ENABLE_IOTRACE 3526 ".iotrace FILE Enable I/O diagnostic logging to FILE", 3527#endif 3528 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", 3529 ".lint OPTIONS Report potential schema issues.", 3530 " Options:", 3531 " fkey-indexes Find missing foreign key indexes", 3532#ifndef SQLITE_OMIT_LOAD_EXTENSION 3533 ".load FILE ?ENTRY? Load an extension library", 3534#endif 3535 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout", 3536 ".mode MODE ?TABLE? Set output mode", 3537 " MODE is one of:", 3538 " ascii Columns/rows delimited by 0x1F and 0x1E", 3539 " csv Comma-separated values", 3540 " column Left-aligned columns. (See .width)", 3541 " html HTML <table> code", 3542 " insert SQL insert statements for TABLE", 3543 " line One value per line", 3544 " list Values delimited by \"|\"", 3545 " quote Escape answers as for SQL", 3546 " tabs Tab-separated values", 3547 " tcl TCL list elements", 3548 ".nullvalue STRING Use STRING in place of NULL values", 3549 ".once (-e|-x|FILE) Output for the next SQL command only to FILE", 3550 " If FILE begins with '|' then open as a pipe", 3551 " Other options:", 3552 " -e Invoke system text editor", 3553 " -x Open in a spreadsheet", 3554 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", 3555 " Options:", 3556 " --append Use appendvfs to append database to the end of FILE", 3557#ifdef SQLITE_ENABLE_DESERIALIZE 3558 " --deserialize Load into memory useing sqlite3_deserialize()", 3559 " --hexdb Load the output of \"dbtotxt\" as an in-memory database", 3560 " --maxsize N Maximum size for --hexdb or --deserialized database", 3561#endif 3562 " --new Initialize FILE to an empty database", 3563 " --readonly Open FILE readonly", 3564 " --zip FILE is a ZIP archive", 3565 ".output ?FILE? Send output to FILE or stdout if FILE is omitted", 3566 " If FILE begins with '|' then open it as a pipe.", 3567 ".parameter CMD ... Manage SQL parameter bindings", 3568 " clear Erase all bindings", 3569 " init Initialize the TEMP table that holds bindings", 3570 " list List the current parameter bindings", 3571 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", 3572 " PARAMETER should start with '$', ':', '@', or '?'", 3573 " unset PARAMETER Remove PARAMETER from the binding table", 3574 ".print STRING... Print literal STRING", 3575#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 3576 ".progress N Invoke progress handler after every N opcodes", 3577 " --limit N Interrupt after N progress callbacks", 3578 " --once Do no more than one progress interrupt", 3579 " --quiet|-q No output except at interrupts", 3580 " --reset Reset the count for each input and interrupt", 3581#endif 3582 ".prompt MAIN CONTINUE Replace the standard prompts", 3583 ".quit Exit this program", 3584 ".read FILE Read input from FILE", 3585#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 3586 ".recover Recover as much data as possible from corrupt db.", 3587#endif 3588 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", 3589 ".save FILE Write in-memory database into FILE", 3590 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off", 3591 ".schema ?PATTERN? Show the CREATE statements matching PATTERN", 3592 " Options:", 3593 " --indent Try to pretty-print the schema", 3594 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table", 3595 " Options:", 3596 " --init Create a new SELFTEST table", 3597 " -v Verbose output", 3598 ".separator COL ?ROW? Change the column and row separators", 3599#if defined(SQLITE_ENABLE_SESSION) 3600 ".session ?NAME? CMD ... Create or control sessions", 3601 " Subcommands:", 3602 " attach TABLE Attach TABLE", 3603 " changeset FILE Write a changeset into FILE", 3604 " close Close one session", 3605 " enable ?BOOLEAN? Set or query the enable bit", 3606 " filter GLOB... Reject tables matching GLOBs", 3607 " indirect ?BOOLEAN? Mark or query the indirect status", 3608 " isempty Query whether the session is empty", 3609 " list List currently open session names", 3610 " open DB NAME Open a new session on DB", 3611 " patchset FILE Write a patchset into FILE", 3612 " If ?NAME? is omitted, the first defined session is used.", 3613#endif 3614 ".sha3sum ... Compute a SHA3 hash of database content", 3615 " Options:", 3616 " --schema Also hash the sqlite_master table", 3617 " --sha3-224 Use the sha3-224 algorithm", 3618 " --sha3-256 Use the sha3-256 algorithm. This is the default.", 3619 " --sha3-384 Use the sha3-384 algorithm", 3620 " --sha3-512 Use the sha3-512 algorithm", 3621 " Any other argument is a LIKE pattern for tables to hash", 3622#ifndef SQLITE_NOHAVE_SYSTEM 3623 ".shell CMD ARGS... Run CMD ARGS... in a system shell", 3624#endif 3625 ".show Show the current values for various settings", 3626 ".stats ?on|off? Show stats or turn stats on or off", 3627#ifndef SQLITE_NOHAVE_SYSTEM 3628 ".system CMD ARGS... Run CMD ARGS... in a system shell", 3629#endif 3630 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", 3631 ".testcase NAME Begin redirecting output to 'testcase-out.txt'", 3632 ".testctrl CMD ... Run various sqlite3_test_control() operations", 3633 " Run \".testctrl\" with no arguments for details", 3634 ".timeout MS Try opening locked tables for MS milliseconds", 3635 ".timer on|off Turn SQL timer on or off", 3636#ifndef SQLITE_OMIT_TRACE 3637 ".trace ?OPTIONS? Output each SQL statement as it is run", 3638 " FILE Send output to FILE", 3639 " stdout Send output to stdout", 3640 " stderr Send output to stderr", 3641 " off Disable tracing", 3642 " --expanded Expand query parameters", 3643#ifdef SQLITE_ENABLE_NORMALIZE 3644 " --normalized Normal the SQL statements", 3645#endif 3646 " --plain Show SQL as it is input", 3647 " --stmt Trace statement execution (SQLITE_TRACE_STMT)", 3648 " --profile Profile statements (SQLITE_TRACE_PROFILE)", 3649 " --row Trace each row (SQLITE_TRACE_ROW)", 3650 " --close Trace connection close (SQLITE_TRACE_CLOSE)", 3651#endif /* SQLITE_OMIT_TRACE */ 3652 ".vfsinfo ?AUX? Information about the top-level VFS", 3653 ".vfslist List all available VFSes", 3654 ".vfsname ?AUX? Print the name of the VFS stack", 3655 ".width NUM1 NUM2 ... Set column widths for \"column\" mode", 3656 " Negative values right-justify", 3657}; 3658 3659/* 3660** Output help text. 3661** 3662** zPattern describes the set of commands for which help text is provided. 3663** If zPattern is NULL, then show all commands, but only give a one-line 3664** description of each. 3665** 3666** Return the number of matches. 3667*/ 3668static int showHelp(FILE *out, const char *zPattern){ 3669 int i = 0; 3670 int j = 0; 3671 int n = 0; 3672 char *zPat; 3673 if( zPattern==0 3674 || zPattern[0]=='0' 3675 || strcmp(zPattern,"-a")==0 3676 || strcmp(zPattern,"-all")==0 3677 ){ 3678 /* Show all commands, but only one line per command */ 3679 if( zPattern==0 ) zPattern = ""; 3680 for(i=0; i<ArraySize(azHelp); i++){ 3681 if( azHelp[i][0]=='.' || zPattern[0] ){ 3682 utf8_printf(out, "%s\n", azHelp[i]); 3683 n++; 3684 } 3685 } 3686 }else{ 3687 /* Look for commands that for which zPattern is an exact prefix */ 3688 zPat = sqlite3_mprintf(".%s*", zPattern); 3689 for(i=0; i<ArraySize(azHelp); i++){ 3690 if( sqlite3_strglob(zPat, azHelp[i])==0 ){ 3691 utf8_printf(out, "%s\n", azHelp[i]); 3692 j = i+1; 3693 n++; 3694 } 3695 } 3696 sqlite3_free(zPat); 3697 if( n ){ 3698 if( n==1 ){ 3699 /* when zPattern is a prefix of exactly one command, then include the 3700 ** details of that command, which should begin at offset j */ 3701 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){ 3702 utf8_printf(out, "%s\n", azHelp[j]); 3703 j++; 3704 } 3705 } 3706 return n; 3707 } 3708 /* Look for commands that contain zPattern anywhere. Show the complete 3709 ** text of all commands that match. */ 3710 zPat = sqlite3_mprintf("%%%s%%", zPattern); 3711 for(i=0; i<ArraySize(azHelp); i++){ 3712 if( azHelp[i][0]=='.' ) j = i; 3713 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){ 3714 utf8_printf(out, "%s\n", azHelp[j]); 3715 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){ 3716 j++; 3717 utf8_printf(out, "%s\n", azHelp[j]); 3718 } 3719 i = j; 3720 n++; 3721 } 3722 } 3723 sqlite3_free(zPat); 3724 } 3725 return n; 3726} 3727 3728/* Forward reference */ 3729static int process_input(ShellState *p); 3730 3731/* 3732** Read the content of file zName into memory obtained from sqlite3_malloc64() 3733** and return a pointer to the buffer. The caller is responsible for freeing 3734** the memory. 3735** 3736** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes 3737** read. 3738** 3739** For convenience, a nul-terminator byte is always appended to the data read 3740** from the file before the buffer is returned. This byte is not included in 3741** the final value of (*pnByte), if applicable. 3742** 3743** NULL is returned if any error is encountered. The final value of *pnByte 3744** is undefined in this case. 3745*/ 3746static char *readFile(const char *zName, int *pnByte){ 3747 FILE *in = fopen(zName, "rb"); 3748 long nIn; 3749 size_t nRead; 3750 char *pBuf; 3751 if( in==0 ) return 0; 3752 fseek(in, 0, SEEK_END); 3753 nIn = ftell(in); 3754 rewind(in); 3755 pBuf = sqlite3_malloc64( nIn+1 ); 3756 if( pBuf==0 ){ fclose(in); return 0; } 3757 nRead = fread(pBuf, nIn, 1, in); 3758 fclose(in); 3759 if( nRead!=1 ){ 3760 sqlite3_free(pBuf); 3761 return 0; 3762 } 3763 pBuf[nIn] = 0; 3764 if( pnByte ) *pnByte = nIn; 3765 return pBuf; 3766} 3767 3768#if defined(SQLITE_ENABLE_SESSION) 3769/* 3770** Close a single OpenSession object and release all of its associated 3771** resources. 3772*/ 3773static void session_close(OpenSession *pSession){ 3774 int i; 3775 sqlite3session_delete(pSession->p); 3776 sqlite3_free(pSession->zName); 3777 for(i=0; i<pSession->nFilter; i++){ 3778 sqlite3_free(pSession->azFilter[i]); 3779 } 3780 sqlite3_free(pSession->azFilter); 3781 memset(pSession, 0, sizeof(OpenSession)); 3782} 3783#endif 3784 3785/* 3786** Close all OpenSession objects and release all associated resources. 3787*/ 3788#if defined(SQLITE_ENABLE_SESSION) 3789static void session_close_all(ShellState *p){ 3790 int i; 3791 for(i=0; i<p->nSession; i++){ 3792 session_close(&p->aSession[i]); 3793 } 3794 p->nSession = 0; 3795} 3796#else 3797# define session_close_all(X) 3798#endif 3799 3800/* 3801** Implementation of the xFilter function for an open session. Omit 3802** any tables named by ".session filter" but let all other table through. 3803*/ 3804#if defined(SQLITE_ENABLE_SESSION) 3805static int session_filter(void *pCtx, const char *zTab){ 3806 OpenSession *pSession = (OpenSession*)pCtx; 3807 int i; 3808 for(i=0; i<pSession->nFilter; i++){ 3809 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; 3810 } 3811 return 1; 3812} 3813#endif 3814 3815/* 3816** Try to deduce the type of file for zName based on its content. Return 3817** one of the SHELL_OPEN_* constants. 3818** 3819** If the file does not exist or is empty but its name looks like a ZIP 3820** archive and the dfltZip flag is true, then assume it is a ZIP archive. 3821** Otherwise, assume an ordinary database regardless of the filename if 3822** the type cannot be determined from content. 3823*/ 3824int deduceDatabaseType(const char *zName, int dfltZip){ 3825 FILE *f = fopen(zName, "rb"); 3826 size_t n; 3827 int rc = SHELL_OPEN_UNSPEC; 3828 char zBuf[100]; 3829 if( f==0 ){ 3830 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 3831 return SHELL_OPEN_ZIPFILE; 3832 }else{ 3833 return SHELL_OPEN_NORMAL; 3834 } 3835 } 3836 n = fread(zBuf, 16, 1, f); 3837 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ 3838 fclose(f); 3839 return SHELL_OPEN_NORMAL; 3840 } 3841 fseek(f, -25, SEEK_END); 3842 n = fread(zBuf, 25, 1, f); 3843 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ 3844 rc = SHELL_OPEN_APPENDVFS; 3845 }else{ 3846 fseek(f, -22, SEEK_END); 3847 n = fread(zBuf, 22, 1, f); 3848 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 3849 && zBuf[3]==0x06 ){ 3850 rc = SHELL_OPEN_ZIPFILE; 3851 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 3852 rc = SHELL_OPEN_ZIPFILE; 3853 } 3854 } 3855 fclose(f); 3856 return rc; 3857} 3858 3859#ifdef SQLITE_ENABLE_DESERIALIZE 3860/* 3861** Reconstruct an in-memory database using the output from the "dbtotxt" 3862** program. Read content from the file in p->zDbFilename. If p->zDbFilename 3863** is 0, then read from standard input. 3864*/ 3865static unsigned char *readHexDb(ShellState *p, int *pnData){ 3866 unsigned char *a = 0; 3867 int nLine; 3868 int n = 0; 3869 int pgsz = 0; 3870 int iOffset = 0; 3871 int j, k; 3872 int rc; 3873 FILE *in; 3874 unsigned int x[16]; 3875 char zLine[1000]; 3876 if( p->zDbFilename ){ 3877 in = fopen(p->zDbFilename, "r"); 3878 if( in==0 ){ 3879 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename); 3880 return 0; 3881 } 3882 nLine = 0; 3883 }else{ 3884 in = p->in; 3885 nLine = p->lineno; 3886 if( in==0 ) in = stdin; 3887 } 3888 *pnData = 0; 3889 nLine++; 3890 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; 3891 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); 3892 if( rc!=2 ) goto readHexDb_error; 3893 if( n<0 ) goto readHexDb_error; 3894 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; 3895 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ 3896 a = sqlite3_malloc( n ? n : 1 ); 3897 if( a==0 ){ 3898 utf8_printf(stderr, "Out of memory!\n"); 3899 goto readHexDb_error; 3900 } 3901 memset(a, 0, n); 3902 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ 3903 utf8_printf(stderr, "invalid pagesize\n"); 3904 goto readHexDb_error; 3905 } 3906 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){ 3907 rc = sscanf(zLine, "| page %d offset %d", &j, &k); 3908 if( rc==2 ){ 3909 iOffset = k; 3910 continue; 3911 } 3912 if( strncmp(zLine, "| end ", 6)==0 ){ 3913 break; 3914 } 3915 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x", 3916 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], 3917 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); 3918 if( rc==17 ){ 3919 k = iOffset+j; 3920 if( k+16<=n ){ 3921 int ii; 3922 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff; 3923 } 3924 } 3925 } 3926 *pnData = n; 3927 if( in!=p->in ){ 3928 fclose(in); 3929 }else{ 3930 p->lineno = nLine; 3931 } 3932 return a; 3933 3934readHexDb_error: 3935 if( in!=p->in ){ 3936 fclose(in); 3937 }else{ 3938 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ 3939 nLine++; 3940 if(strncmp(zLine, "| end ", 6)==0 ) break; 3941 } 3942 p->lineno = nLine; 3943 } 3944 sqlite3_free(a); 3945 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine); 3946 return 0; 3947} 3948#endif /* SQLITE_ENABLE_DESERIALIZE */ 3949 3950/* 3951** Scalar function "shell_int32". The first argument to this function 3952** must be a blob. The second a non-negative integer. This function 3953** reads and returns a 32-bit big-endian integer from byte 3954** offset (4*<arg2>) of the blob. 3955*/ 3956static void shellInt32( 3957 sqlite3_context *context, 3958 int argc, 3959 sqlite3_value **argv 3960){ 3961 const unsigned char *pBlob; 3962 int nBlob; 3963 int iInt; 3964 3965 UNUSED_PARAMETER(argc); 3966 nBlob = sqlite3_value_bytes(argv[0]); 3967 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); 3968 iInt = sqlite3_value_int(argv[1]); 3969 3970 if( iInt>=0 && (iInt+1)*4<=nBlob ){ 3971 const unsigned char *a = &pBlob[iInt*4]; 3972 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24) 3973 + ((sqlite3_int64)a[1]<<16) 3974 + ((sqlite3_int64)a[2]<< 8) 3975 + ((sqlite3_int64)a[3]<< 0); 3976 sqlite3_result_int64(context, iVal); 3977 } 3978} 3979 3980/* 3981** Scalar function "shell_idquote(X)" returns string X quoted as an identifier, 3982** using "..." with internal double-quote characters doubled. 3983*/ 3984static void shellIdQuote( 3985 sqlite3_context *context, 3986 int argc, 3987 sqlite3_value **argv 3988){ 3989 const char *zName = (const char*)sqlite3_value_text(argv[0]); 3990 UNUSED_PARAMETER(argc); 3991 if( zName ){ 3992 char *z = sqlite3_mprintf("\"%w\"", zName); 3993 sqlite3_result_text(context, z, -1, sqlite3_free); 3994 } 3995} 3996 3997/* 3998** Scalar function "shell_escape_crnl" used by the .recover command. 3999** The argument passed to this function is the output of built-in 4000** function quote(). If the first character of the input is "'", 4001** indicating that the value passed to quote() was a text value, 4002** then this function searches the input for "\n" and "\r" characters 4003** and adds a wrapper similar to the following: 4004** 4005** replace(replace(<input>, '\n', char(10), '\r', char(13)); 4006** 4007** Or, if the first character of the input is not "'", then a copy 4008** of the input is returned. 4009*/ 4010static void shellEscapeCrnl( 4011 sqlite3_context *context, 4012 int argc, 4013 sqlite3_value **argv 4014){ 4015 const char *zText = (const char*)sqlite3_value_text(argv[0]); 4016 UNUSED_PARAMETER(argc); 4017 if( zText[0]=='\'' ){ 4018 int nText = sqlite3_value_bytes(argv[0]); 4019 int i; 4020 char zBuf1[20]; 4021 char zBuf2[20]; 4022 const char *zNL = 0; 4023 const char *zCR = 0; 4024 int nCR = 0; 4025 int nNL = 0; 4026 4027 for(i=0; zText[i]; i++){ 4028 if( zNL==0 && zText[i]=='\n' ){ 4029 zNL = unused_string(zText, "\\n", "\\012", zBuf1); 4030 nNL = (int)strlen(zNL); 4031 } 4032 if( zCR==0 && zText[i]=='\r' ){ 4033 zCR = unused_string(zText, "\\r", "\\015", zBuf2); 4034 nCR = (int)strlen(zCR); 4035 } 4036 } 4037 4038 if( zNL || zCR ){ 4039 int iOut = 0; 4040 i64 nMax = (nNL > nCR) ? nNL : nCR; 4041 i64 nAlloc = nMax * nText + (nMax+64)*2; 4042 char *zOut = (char*)sqlite3_malloc64(nAlloc); 4043 if( zOut==0 ){ 4044 sqlite3_result_error_nomem(context); 4045 return; 4046 } 4047 4048 if( zNL && zCR ){ 4049 memcpy(&zOut[iOut], "replace(replace(", 16); 4050 iOut += 16; 4051 }else{ 4052 memcpy(&zOut[iOut], "replace(", 8); 4053 iOut += 8; 4054 } 4055 for(i=0; zText[i]; i++){ 4056 if( zText[i]=='\n' ){ 4057 memcpy(&zOut[iOut], zNL, nNL); 4058 iOut += nNL; 4059 }else if( zText[i]=='\r' ){ 4060 memcpy(&zOut[iOut], zCR, nCR); 4061 iOut += nCR; 4062 }else{ 4063 zOut[iOut] = zText[i]; 4064 iOut++; 4065 } 4066 } 4067 4068 if( zNL ){ 4069 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4070 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; 4071 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; 4072 } 4073 if( zCR ){ 4074 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4075 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; 4076 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; 4077 } 4078 4079 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); 4080 sqlite3_free(zOut); 4081 return; 4082 } 4083 } 4084 4085 sqlite3_result_value(context, argv[0]); 4086} 4087 4088/* Flags for open_db(). 4089** 4090** The default behavior of open_db() is to exit(1) if the database fails to 4091** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error 4092** but still returns without calling exit. 4093** 4094** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a 4095** ZIP archive if the file does not exist or is empty and its name matches 4096** the *.zip pattern. 4097*/ 4098#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ 4099#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ 4100 4101/* 4102** Make sure the database is open. If it is not, then open it. If 4103** the database fails to open, print an error message and exit. 4104*/ 4105static void open_db(ShellState *p, int openFlags){ 4106 if( p->db==0 ){ 4107 if( p->openMode==SHELL_OPEN_UNSPEC ){ 4108 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){ 4109 p->openMode = SHELL_OPEN_NORMAL; 4110 }else{ 4111 p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 4112 (openFlags & OPEN_DB_ZIPFILE)!=0); 4113 } 4114 } 4115 switch( p->openMode ){ 4116 case SHELL_OPEN_APPENDVFS: { 4117 sqlite3_open_v2(p->zDbFilename, &p->db, 4118 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs"); 4119 break; 4120 } 4121 case SHELL_OPEN_HEXDB: 4122 case SHELL_OPEN_DESERIALIZE: { 4123 sqlite3_open(0, &p->db); 4124 break; 4125 } 4126 case SHELL_OPEN_ZIPFILE: { 4127 sqlite3_open(":memory:", &p->db); 4128 break; 4129 } 4130 case SHELL_OPEN_READONLY: { 4131 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0); 4132 break; 4133 } 4134 case SHELL_OPEN_UNSPEC: 4135 case SHELL_OPEN_NORMAL: { 4136 sqlite3_open(p->zDbFilename, &p->db); 4137 break; 4138 } 4139 } 4140 globalDb = p->db; 4141 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ 4142 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", 4143 p->zDbFilename, sqlite3_errmsg(p->db)); 4144 if( openFlags & OPEN_DB_KEEPALIVE ){ 4145 sqlite3_open(":memory:", &p->db); 4146 return; 4147 } 4148 exit(1); 4149 } 4150#ifndef SQLITE_OMIT_LOAD_EXTENSION 4151 sqlite3_enable_load_extension(p->db, 1); 4152#endif 4153 sqlite3_fileio_init(p->db, 0, 0); 4154 sqlite3_shathree_init(p->db, 0, 0); 4155 sqlite3_completion_init(p->db, 0, 0); 4156#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 4157 sqlite3_dbdata_init(p->db, 0, 0); 4158#endif 4159#ifdef SQLITE_HAVE_ZLIB 4160 sqlite3_zipfile_init(p->db, 0, 0); 4161 sqlite3_sqlar_init(p->db, 0, 0); 4162#endif 4163 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, 4164 shellAddSchemaName, 0, 0); 4165 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, 4166 shellModuleSchema, 0, 0); 4167 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, 4168 shellPutsFunc, 0, 0); 4169 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0, 4170 shellEscapeCrnl, 0, 0); 4171 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0, 4172 shellInt32, 0, 0); 4173 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0, 4174 shellIdQuote, 0, 0); 4175#ifndef SQLITE_NOHAVE_SYSTEM 4176 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, 4177 editFunc, 0, 0); 4178 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, 4179 editFunc, 0, 0); 4180#endif 4181 if( p->openMode==SHELL_OPEN_ZIPFILE ){ 4182 char *zSql = sqlite3_mprintf( 4183 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename); 4184 sqlite3_exec(p->db, zSql, 0, 0, 0); 4185 sqlite3_free(zSql); 4186 } 4187#ifdef SQLITE_ENABLE_DESERIALIZE 4188 else 4189 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ 4190 int rc; 4191 int nData = 0; 4192 unsigned char *aData; 4193 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ 4194 aData = (unsigned char*)readFile(p->zDbFilename, &nData); 4195 }else{ 4196 aData = readHexDb(p, &nData); 4197 if( aData==0 ){ 4198 return; 4199 } 4200 } 4201 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, 4202 SQLITE_DESERIALIZE_RESIZEABLE | 4203 SQLITE_DESERIALIZE_FREEONCLOSE); 4204 if( rc ){ 4205 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc); 4206 } 4207 if( p->szMax>0 ){ 4208 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); 4209 } 4210 } 4211#endif 4212 } 4213} 4214 4215/* 4216** Attempt to close the databaes connection. Report errors. 4217*/ 4218void close_db(sqlite3 *db){ 4219 int rc = sqlite3_close(db); 4220 if( rc ){ 4221 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n", 4222 rc, sqlite3_errmsg(db)); 4223 } 4224} 4225 4226#if HAVE_READLINE || HAVE_EDITLINE 4227/* 4228** Readline completion callbacks 4229*/ 4230static char *readline_completion_generator(const char *text, int state){ 4231 static sqlite3_stmt *pStmt = 0; 4232 char *zRet; 4233 if( state==0 ){ 4234 char *zSql; 4235 sqlite3_finalize(pStmt); 4236 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4237 " FROM completion(%Q) ORDER BY 1", text); 4238 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4239 sqlite3_free(zSql); 4240 } 4241 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 4242 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0)); 4243 }else{ 4244 sqlite3_finalize(pStmt); 4245 pStmt = 0; 4246 zRet = 0; 4247 } 4248 return zRet; 4249} 4250static char **readline_completion(const char *zText, int iStart, int iEnd){ 4251 rl_attempted_completion_over = 1; 4252 return rl_completion_matches(zText, readline_completion_generator); 4253} 4254 4255#elif HAVE_LINENOISE 4256/* 4257** Linenoise completion callback 4258*/ 4259static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ 4260 int nLine = strlen30(zLine); 4261 int i, iStart; 4262 sqlite3_stmt *pStmt = 0; 4263 char *zSql; 4264 char zBuf[1000]; 4265 4266 if( nLine>sizeof(zBuf)-30 ) return; 4267 if( zLine[0]=='.' || zLine[0]=='#') return; 4268 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} 4269 if( i==nLine-1 ) return; 4270 iStart = i+1; 4271 memcpy(zBuf, zLine, iStart); 4272 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4273 " FROM completion(%Q,%Q) ORDER BY 1", 4274 &zLine[iStart], zLine); 4275 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4276 sqlite3_free(zSql); 4277 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ 4278 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 4279 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); 4280 int nCompletion = sqlite3_column_bytes(pStmt, 0); 4281 if( iStart+nCompletion < sizeof(zBuf)-1 ){ 4282 memcpy(zBuf+iStart, zCompletion, nCompletion+1); 4283 linenoiseAddCompletion(lc, zBuf); 4284 } 4285 } 4286 sqlite3_finalize(pStmt); 4287} 4288#endif 4289 4290/* 4291** Do C-language style dequoting. 4292** 4293** \a -> alarm 4294** \b -> backspace 4295** \t -> tab 4296** \n -> newline 4297** \v -> vertical tab 4298** \f -> form feed 4299** \r -> carriage return 4300** \s -> space 4301** \" -> " 4302** \' -> ' 4303** \\ -> backslash 4304** \NNN -> ascii character NNN in octal 4305*/ 4306static void resolve_backslashes(char *z){ 4307 int i, j; 4308 char c; 4309 while( *z && *z!='\\' ) z++; 4310 for(i=j=0; (c = z[i])!=0; i++, j++){ 4311 if( c=='\\' && z[i+1]!=0 ){ 4312 c = z[++i]; 4313 if( c=='a' ){ 4314 c = '\a'; 4315 }else if( c=='b' ){ 4316 c = '\b'; 4317 }else if( c=='t' ){ 4318 c = '\t'; 4319 }else if( c=='n' ){ 4320 c = '\n'; 4321 }else if( c=='v' ){ 4322 c = '\v'; 4323 }else if( c=='f' ){ 4324 c = '\f'; 4325 }else if( c=='r' ){ 4326 c = '\r'; 4327 }else if( c=='"' ){ 4328 c = '"'; 4329 }else if( c=='\'' ){ 4330 c = '\''; 4331 }else if( c=='\\' ){ 4332 c = '\\'; 4333 }else if( c>='0' && c<='7' ){ 4334 c -= '0'; 4335 if( z[i+1]>='0' && z[i+1]<='7' ){ 4336 i++; 4337 c = (c<<3) + z[i] - '0'; 4338 if( z[i+1]>='0' && z[i+1]<='7' ){ 4339 i++; 4340 c = (c<<3) + z[i] - '0'; 4341 } 4342 } 4343 } 4344 } 4345 z[j] = c; 4346 } 4347 if( j<i ) z[j] = 0; 4348} 4349 4350/* 4351** Interpret zArg as either an integer or a boolean value. Return 1 or 0 4352** for TRUE and FALSE. Return the integer value if appropriate. 4353*/ 4354static int booleanValue(const char *zArg){ 4355 int i; 4356 if( zArg[0]=='0' && zArg[1]=='x' ){ 4357 for(i=2; hexDigitValue(zArg[i])>=0; i++){} 4358 }else{ 4359 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} 4360 } 4361 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); 4362 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ 4363 return 1; 4364 } 4365 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ 4366 return 0; 4367 } 4368 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", 4369 zArg); 4370 return 0; 4371} 4372 4373/* 4374** Set or clear a shell flag according to a boolean value. 4375*/ 4376static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ 4377 if( booleanValue(zArg) ){ 4378 ShellSetFlag(p, mFlag); 4379 }else{ 4380 ShellClearFlag(p, mFlag); 4381 } 4382} 4383 4384/* 4385** Close an output file, assuming it is not stderr or stdout 4386*/ 4387static void output_file_close(FILE *f){ 4388 if( f && f!=stdout && f!=stderr ) fclose(f); 4389} 4390 4391/* 4392** Try to open an output file. The names "stdout" and "stderr" are 4393** recognized and do the right thing. NULL is returned if the output 4394** filename is "off". 4395*/ 4396static FILE *output_file_open(const char *zFile, int bTextMode){ 4397 FILE *f; 4398 if( strcmp(zFile,"stdout")==0 ){ 4399 f = stdout; 4400 }else if( strcmp(zFile, "stderr")==0 ){ 4401 f = stderr; 4402 }else if( strcmp(zFile, "off")==0 ){ 4403 f = 0; 4404 }else{ 4405 f = fopen(zFile, bTextMode ? "w" : "wb"); 4406 if( f==0 ){ 4407 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 4408 } 4409 } 4410 return f; 4411} 4412 4413#ifndef SQLITE_OMIT_TRACE 4414/* 4415** A routine for handling output from sqlite3_trace(). 4416*/ 4417static int sql_trace_callback( 4418 unsigned mType, /* The trace type */ 4419 void *pArg, /* The ShellState pointer */ 4420 void *pP, /* Usually a pointer to sqlite_stmt */ 4421 void *pX /* Auxiliary output */ 4422){ 4423 ShellState *p = (ShellState*)pArg; 4424 sqlite3_stmt *pStmt; 4425 const char *zSql; 4426 int nSql; 4427 if( p->traceOut==0 ) return 0; 4428 if( mType==SQLITE_TRACE_CLOSE ){ 4429 utf8_printf(p->traceOut, "-- closing database connection\n"); 4430 return 0; 4431 } 4432 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){ 4433 zSql = (const char*)pX; 4434 }else{ 4435 pStmt = (sqlite3_stmt*)pP; 4436 switch( p->eTraceType ){ 4437 case SHELL_TRACE_EXPANDED: { 4438 zSql = sqlite3_expanded_sql(pStmt); 4439 break; 4440 } 4441#ifdef SQLITE_ENABLE_NORMALIZE 4442 case SHELL_TRACE_NORMALIZED: { 4443 zSql = sqlite3_normalized_sql(pStmt); 4444 break; 4445 } 4446#endif 4447 default: { 4448 zSql = sqlite3_sql(pStmt); 4449 break; 4450 } 4451 } 4452 } 4453 if( zSql==0 ) return 0; 4454 nSql = strlen30(zSql); 4455 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } 4456 switch( mType ){ 4457 case SQLITE_TRACE_ROW: 4458 case SQLITE_TRACE_STMT: { 4459 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql); 4460 break; 4461 } 4462 case SQLITE_TRACE_PROFILE: { 4463 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX; 4464 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec); 4465 break; 4466 } 4467 } 4468 return 0; 4469} 4470#endif 4471 4472/* 4473** A no-op routine that runs with the ".breakpoint" doc-command. This is 4474** a useful spot to set a debugger breakpoint. 4475*/ 4476static void test_breakpoint(void){ 4477 static int nCall = 0; 4478 nCall++; 4479} 4480 4481/* 4482** An object used to read a CSV and other files for import. 4483*/ 4484typedef struct ImportCtx ImportCtx; 4485struct ImportCtx { 4486 const char *zFile; /* Name of the input file */ 4487 FILE *in; /* Read the CSV text from this input stream */ 4488 char *z; /* Accumulated text for a field */ 4489 int n; /* Number of bytes in z */ 4490 int nAlloc; /* Space allocated for z[] */ 4491 int nLine; /* Current line number */ 4492 int bNotFirst; /* True if one or more bytes already read */ 4493 int cTerm; /* Character that terminated the most recent field */ 4494 int cColSep; /* The column separator character. (Usually ",") */ 4495 int cRowSep; /* The row separator character. (Usually "\n") */ 4496}; 4497 4498/* Append a single byte to z[] */ 4499static void import_append_char(ImportCtx *p, int c){ 4500 if( p->n+1>=p->nAlloc ){ 4501 p->nAlloc += p->nAlloc + 100; 4502 p->z = sqlite3_realloc64(p->z, p->nAlloc); 4503 if( p->z==0 ) shell_out_of_memory(); 4504 } 4505 p->z[p->n++] = (char)c; 4506} 4507 4508/* Read a single field of CSV text. Compatible with rfc4180 and extended 4509** with the option of having a separator other than ",". 4510** 4511** + Input comes from p->in. 4512** + Store results in p->z of length p->n. Space to hold p->z comes 4513** from sqlite3_malloc64(). 4514** + Use p->cSep as the column separator. The default is ",". 4515** + Use p->rSep as the row separator. The default is "\n". 4516** + Keep track of the line number in p->nLine. 4517** + Store the character that terminates the field in p->cTerm. Store 4518** EOF on end-of-file. 4519** + Report syntax errors on stderr 4520*/ 4521static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ 4522 int c; 4523 int cSep = p->cColSep; 4524 int rSep = p->cRowSep; 4525 p->n = 0; 4526 c = fgetc(p->in); 4527 if( c==EOF || seenInterrupt ){ 4528 p->cTerm = EOF; 4529 return 0; 4530 } 4531 if( c=='"' ){ 4532 int pc, ppc; 4533 int startLine = p->nLine; 4534 int cQuote = c; 4535 pc = ppc = 0; 4536 while( 1 ){ 4537 c = fgetc(p->in); 4538 if( c==rSep ) p->nLine++; 4539 if( c==cQuote ){ 4540 if( pc==cQuote ){ 4541 pc = 0; 4542 continue; 4543 } 4544 } 4545 if( (c==cSep && pc==cQuote) 4546 || (c==rSep && pc==cQuote) 4547 || (c==rSep && pc=='\r' && ppc==cQuote) 4548 || (c==EOF && pc==cQuote) 4549 ){ 4550 do{ p->n--; }while( p->z[p->n]!=cQuote ); 4551 p->cTerm = c; 4552 break; 4553 } 4554 if( pc==cQuote && c!='\r' ){ 4555 utf8_printf(stderr, "%s:%d: unescaped %c character\n", 4556 p->zFile, p->nLine, cQuote); 4557 } 4558 if( c==EOF ){ 4559 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", 4560 p->zFile, startLine, cQuote); 4561 p->cTerm = c; 4562 break; 4563 } 4564 import_append_char(p, c); 4565 ppc = pc; 4566 pc = c; 4567 } 4568 }else{ 4569 /* If this is the first field being parsed and it begins with the 4570 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ 4571 if( (c&0xff)==0xef && p->bNotFirst==0 ){ 4572 import_append_char(p, c); 4573 c = fgetc(p->in); 4574 if( (c&0xff)==0xbb ){ 4575 import_append_char(p, c); 4576 c = fgetc(p->in); 4577 if( (c&0xff)==0xbf ){ 4578 p->bNotFirst = 1; 4579 p->n = 0; 4580 return csv_read_one_field(p); 4581 } 4582 } 4583 } 4584 while( c!=EOF && c!=cSep && c!=rSep ){ 4585 import_append_char(p, c); 4586 c = fgetc(p->in); 4587 } 4588 if( c==rSep ){ 4589 p->nLine++; 4590 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; 4591 } 4592 p->cTerm = c; 4593 } 4594 if( p->z ) p->z[p->n] = 0; 4595 p->bNotFirst = 1; 4596 return p->z; 4597} 4598 4599/* Read a single field of ASCII delimited text. 4600** 4601** + Input comes from p->in. 4602** + Store results in p->z of length p->n. Space to hold p->z comes 4603** from sqlite3_malloc64(). 4604** + Use p->cSep as the column separator. The default is "\x1F". 4605** + Use p->rSep as the row separator. The default is "\x1E". 4606** + Keep track of the row number in p->nLine. 4607** + Store the character that terminates the field in p->cTerm. Store 4608** EOF on end-of-file. 4609** + Report syntax errors on stderr 4610*/ 4611static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ 4612 int c; 4613 int cSep = p->cColSep; 4614 int rSep = p->cRowSep; 4615 p->n = 0; 4616 c = fgetc(p->in); 4617 if( c==EOF || seenInterrupt ){ 4618 p->cTerm = EOF; 4619 return 0; 4620 } 4621 while( c!=EOF && c!=cSep && c!=rSep ){ 4622 import_append_char(p, c); 4623 c = fgetc(p->in); 4624 } 4625 if( c==rSep ){ 4626 p->nLine++; 4627 } 4628 p->cTerm = c; 4629 if( p->z ) p->z[p->n] = 0; 4630 return p->z; 4631} 4632 4633/* 4634** Try to transfer data for table zTable. If an error is seen while 4635** moving forward, try to go backwards. The backwards movement won't 4636** work for WITHOUT ROWID tables. 4637*/ 4638static void tryToCloneData( 4639 ShellState *p, 4640 sqlite3 *newDb, 4641 const char *zTable 4642){ 4643 sqlite3_stmt *pQuery = 0; 4644 sqlite3_stmt *pInsert = 0; 4645 char *zQuery = 0; 4646 char *zInsert = 0; 4647 int rc; 4648 int i, j, n; 4649 int nTable = strlen30(zTable); 4650 int k = 0; 4651 int cnt = 0; 4652 const int spinRate = 10000; 4653 4654 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); 4655 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4656 if( rc ){ 4657 utf8_printf(stderr, "Error %d: %s on [%s]\n", 4658 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4659 zQuery); 4660 goto end_data_xfer; 4661 } 4662 n = sqlite3_column_count(pQuery); 4663 zInsert = sqlite3_malloc64(200 + nTable + n*3); 4664 if( zInsert==0 ) shell_out_of_memory(); 4665 sqlite3_snprintf(200+nTable,zInsert, 4666 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); 4667 i = strlen30(zInsert); 4668 for(j=1; j<n; j++){ 4669 memcpy(zInsert+i, ",?", 2); 4670 i += 2; 4671 } 4672 memcpy(zInsert+i, ");", 3); 4673 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); 4674 if( rc ){ 4675 utf8_printf(stderr, "Error %d: %s on [%s]\n", 4676 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), 4677 zQuery); 4678 goto end_data_xfer; 4679 } 4680 for(k=0; k<2; k++){ 4681 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4682 for(i=0; i<n; i++){ 4683 switch( sqlite3_column_type(pQuery, i) ){ 4684 case SQLITE_NULL: { 4685 sqlite3_bind_null(pInsert, i+1); 4686 break; 4687 } 4688 case SQLITE_INTEGER: { 4689 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); 4690 break; 4691 } 4692 case SQLITE_FLOAT: { 4693 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); 4694 break; 4695 } 4696 case SQLITE_TEXT: { 4697 sqlite3_bind_text(pInsert, i+1, 4698 (const char*)sqlite3_column_text(pQuery,i), 4699 -1, SQLITE_STATIC); 4700 break; 4701 } 4702 case SQLITE_BLOB: { 4703 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), 4704 sqlite3_column_bytes(pQuery,i), 4705 SQLITE_STATIC); 4706 break; 4707 } 4708 } 4709 } /* End for */ 4710 rc = sqlite3_step(pInsert); 4711 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ 4712 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), 4713 sqlite3_errmsg(newDb)); 4714 } 4715 sqlite3_reset(pInsert); 4716 cnt++; 4717 if( (cnt%spinRate)==0 ){ 4718 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); 4719 fflush(stdout); 4720 } 4721 } /* End while */ 4722 if( rc==SQLITE_DONE ) break; 4723 sqlite3_finalize(pQuery); 4724 sqlite3_free(zQuery); 4725 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", 4726 zTable); 4727 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4728 if( rc ){ 4729 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); 4730 break; 4731 } 4732 } /* End for(k=0...) */ 4733 4734end_data_xfer: 4735 sqlite3_finalize(pQuery); 4736 sqlite3_finalize(pInsert); 4737 sqlite3_free(zQuery); 4738 sqlite3_free(zInsert); 4739} 4740 4741 4742/* 4743** Try to transfer all rows of the schema that match zWhere. For 4744** each row, invoke xForEach() on the object defined by that row. 4745** If an error is encountered while moving forward through the 4746** sqlite_master table, try again moving backwards. 4747*/ 4748static void tryToCloneSchema( 4749 ShellState *p, 4750 sqlite3 *newDb, 4751 const char *zWhere, 4752 void (*xForEach)(ShellState*,sqlite3*,const char*) 4753){ 4754 sqlite3_stmt *pQuery = 0; 4755 char *zQuery = 0; 4756 int rc; 4757 const unsigned char *zName; 4758 const unsigned char *zSql; 4759 char *zErrMsg = 0; 4760 4761 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" 4762 " WHERE %s", zWhere); 4763 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4764 if( rc ){ 4765 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 4766 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4767 zQuery); 4768 goto end_schema_xfer; 4769 } 4770 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4771 zName = sqlite3_column_text(pQuery, 0); 4772 zSql = sqlite3_column_text(pQuery, 1); 4773 printf("%s... ", zName); fflush(stdout); 4774 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 4775 if( zErrMsg ){ 4776 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 4777 sqlite3_free(zErrMsg); 4778 zErrMsg = 0; 4779 } 4780 if( xForEach ){ 4781 xForEach(p, newDb, (const char*)zName); 4782 } 4783 printf("done\n"); 4784 } 4785 if( rc!=SQLITE_DONE ){ 4786 sqlite3_finalize(pQuery); 4787 sqlite3_free(zQuery); 4788 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" 4789 " WHERE %s ORDER BY rowid DESC", zWhere); 4790 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4791 if( rc ){ 4792 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 4793 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4794 zQuery); 4795 goto end_schema_xfer; 4796 } 4797 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4798 zName = sqlite3_column_text(pQuery, 0); 4799 zSql = sqlite3_column_text(pQuery, 1); 4800 printf("%s... ", zName); fflush(stdout); 4801 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 4802 if( zErrMsg ){ 4803 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 4804 sqlite3_free(zErrMsg); 4805 zErrMsg = 0; 4806 } 4807 if( xForEach ){ 4808 xForEach(p, newDb, (const char*)zName); 4809 } 4810 printf("done\n"); 4811 } 4812 } 4813end_schema_xfer: 4814 sqlite3_finalize(pQuery); 4815 sqlite3_free(zQuery); 4816} 4817 4818/* 4819** Open a new database file named "zNewDb". Try to recover as much information 4820** as possible out of the main database (which might be corrupt) and write it 4821** into zNewDb. 4822*/ 4823static void tryToClone(ShellState *p, const char *zNewDb){ 4824 int rc; 4825 sqlite3 *newDb = 0; 4826 if( access(zNewDb,0)==0 ){ 4827 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); 4828 return; 4829 } 4830 rc = sqlite3_open(zNewDb, &newDb); 4831 if( rc ){ 4832 utf8_printf(stderr, "Cannot create output database: %s\n", 4833 sqlite3_errmsg(newDb)); 4834 }else{ 4835 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); 4836 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); 4837 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); 4838 tryToCloneSchema(p, newDb, "type!='table'", 0); 4839 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); 4840 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 4841 } 4842 close_db(newDb); 4843} 4844 4845/* 4846** Change the output file back to stdout. 4847** 4848** If the p->doXdgOpen flag is set, that means the output was being 4849** redirected to a temporary file named by p->zTempFile. In that case, 4850** launch start/open/xdg-open on that temporary file. 4851*/ 4852static void output_reset(ShellState *p){ 4853 if( p->outfile[0]=='|' ){ 4854#ifndef SQLITE_OMIT_POPEN 4855 pclose(p->out); 4856#endif 4857 }else{ 4858 output_file_close(p->out); 4859#ifndef SQLITE_NOHAVE_SYSTEM 4860 if( p->doXdgOpen ){ 4861 const char *zXdgOpenCmd = 4862#if defined(_WIN32) 4863 "start"; 4864#elif defined(__APPLE__) 4865 "open"; 4866#else 4867 "xdg-open"; 4868#endif 4869 char *zCmd; 4870 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); 4871 if( system(zCmd) ){ 4872 utf8_printf(stderr, "Failed: [%s]\n", zCmd); 4873 } 4874 sqlite3_free(zCmd); 4875 outputModePop(p); 4876 p->doXdgOpen = 0; 4877 sqlite3_sleep(100); 4878 } 4879#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 4880 } 4881 p->outfile[0] = 0; 4882 p->out = stdout; 4883} 4884 4885/* 4886** Run an SQL command and return the single integer result. 4887*/ 4888static int db_int(ShellState *p, const char *zSql){ 4889 sqlite3_stmt *pStmt; 4890 int res = 0; 4891 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 4892 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 4893 res = sqlite3_column_int(pStmt,0); 4894 } 4895 sqlite3_finalize(pStmt); 4896 return res; 4897} 4898 4899/* 4900** Convert a 2-byte or 4-byte big-endian integer into a native integer 4901*/ 4902static unsigned int get2byteInt(unsigned char *a){ 4903 return (a[0]<<8) + a[1]; 4904} 4905static unsigned int get4byteInt(unsigned char *a){ 4906 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; 4907} 4908 4909/* 4910** Implementation of the ".info" command. 4911** 4912** Return 1 on error, 2 to exit, and 0 otherwise. 4913*/ 4914static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ 4915 static const struct { const char *zName; int ofst; } aField[] = { 4916 { "file change counter:", 24 }, 4917 { "database page count:", 28 }, 4918 { "freelist page count:", 36 }, 4919 { "schema cookie:", 40 }, 4920 { "schema format:", 44 }, 4921 { "default cache size:", 48 }, 4922 { "autovacuum top root:", 52 }, 4923 { "incremental vacuum:", 64 }, 4924 { "text encoding:", 56 }, 4925 { "user version:", 60 }, 4926 { "application id:", 68 }, 4927 { "software version:", 96 }, 4928 }; 4929 static const struct { const char *zName; const char *zSql; } aQuery[] = { 4930 { "number of tables:", 4931 "SELECT count(*) FROM %s WHERE type='table'" }, 4932 { "number of indexes:", 4933 "SELECT count(*) FROM %s WHERE type='index'" }, 4934 { "number of triggers:", 4935 "SELECT count(*) FROM %s WHERE type='trigger'" }, 4936 { "number of views:", 4937 "SELECT count(*) FROM %s WHERE type='view'" }, 4938 { "schema size:", 4939 "SELECT total(length(sql)) FROM %s" }, 4940 }; 4941 int i, rc; 4942 unsigned iDataVersion; 4943 char *zSchemaTab; 4944 char *zDb = nArg>=2 ? azArg[1] : "main"; 4945 sqlite3_stmt *pStmt = 0; 4946 unsigned char aHdr[100]; 4947 open_db(p, 0); 4948 if( p->db==0 ) return 1; 4949 rc = sqlite3_prepare_v2(p->db, 4950 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", 4951 -1, &pStmt, 0); 4952 if( rc ){ 4953 if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){ 4954 utf8_printf(stderr, "the \".dbinfo\" command requires the " 4955 "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n"); 4956 }else{ 4957 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db)); 4958 } 4959 sqlite3_finalize(pStmt); 4960 return 1; 4961 } 4962 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); 4963 if( sqlite3_step(pStmt)==SQLITE_ROW 4964 && sqlite3_column_bytes(pStmt,0)>100 4965 ){ 4966 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); 4967 sqlite3_finalize(pStmt); 4968 }else{ 4969 raw_printf(stderr, "unable to read database header\n"); 4970 sqlite3_finalize(pStmt); 4971 return 1; 4972 } 4973 i = get2byteInt(aHdr+16); 4974 if( i==1 ) i = 65536; 4975 utf8_printf(p->out, "%-20s %d\n", "database page size:", i); 4976 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); 4977 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); 4978 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); 4979 for(i=0; i<ArraySize(aField); i++){ 4980 int ofst = aField[i].ofst; 4981 unsigned int val = get4byteInt(aHdr + ofst); 4982 utf8_printf(p->out, "%-20s %u", aField[i].zName, val); 4983 switch( ofst ){ 4984 case 56: { 4985 if( val==1 ) raw_printf(p->out, " (utf8)"); 4986 if( val==2 ) raw_printf(p->out, " (utf16le)"); 4987 if( val==3 ) raw_printf(p->out, " (utf16be)"); 4988 } 4989 } 4990 raw_printf(p->out, "\n"); 4991 } 4992 if( zDb==0 ){ 4993 zSchemaTab = sqlite3_mprintf("main.sqlite_master"); 4994 }else if( strcmp(zDb,"temp")==0 ){ 4995 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master"); 4996 }else{ 4997 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb); 4998 } 4999 for(i=0; i<ArraySize(aQuery); i++){ 5000 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); 5001 int val = db_int(p, zSql); 5002 sqlite3_free(zSql); 5003 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); 5004 } 5005 sqlite3_free(zSchemaTab); 5006 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); 5007 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion); 5008 return 0; 5009} 5010 5011/* 5012** Print the current sqlite3_errmsg() value to stderr and return 1. 5013*/ 5014static int shellDatabaseError(sqlite3 *db){ 5015 const char *zErr = sqlite3_errmsg(db); 5016 utf8_printf(stderr, "Error: %s\n", zErr); 5017 return 1; 5018} 5019 5020/* 5021** Compare the pattern in zGlob[] against the text in z[]. Return TRUE 5022** if they match and FALSE (0) if they do not match. 5023** 5024** Globbing rules: 5025** 5026** '*' Matches any sequence of zero or more characters. 5027** 5028** '?' Matches exactly one character. 5029** 5030** [...] Matches one character from the enclosed list of 5031** characters. 5032** 5033** [^...] Matches one character not in the enclosed list. 5034** 5035** '#' Matches any sequence of one or more digits with an 5036** optional + or - sign in front 5037** 5038** ' ' Any span of whitespace matches any other span of 5039** whitespace. 5040** 5041** Extra whitespace at the end of z[] is ignored. 5042*/ 5043static int testcase_glob(const char *zGlob, const char *z){ 5044 int c, c2; 5045 int invert; 5046 int seen; 5047 5048 while( (c = (*(zGlob++)))!=0 ){ 5049 if( IsSpace(c) ){ 5050 if( !IsSpace(*z) ) return 0; 5051 while( IsSpace(*zGlob) ) zGlob++; 5052 while( IsSpace(*z) ) z++; 5053 }else if( c=='*' ){ 5054 while( (c=(*(zGlob++))) == '*' || c=='?' ){ 5055 if( c=='?' && (*(z++))==0 ) return 0; 5056 } 5057 if( c==0 ){ 5058 return 1; 5059 }else if( c=='[' ){ 5060 while( *z && testcase_glob(zGlob-1,z)==0 ){ 5061 z++; 5062 } 5063 return (*z)!=0; 5064 } 5065 while( (c2 = (*(z++)))!=0 ){ 5066 while( c2!=c ){ 5067 c2 = *(z++); 5068 if( c2==0 ) return 0; 5069 } 5070 if( testcase_glob(zGlob,z) ) return 1; 5071 } 5072 return 0; 5073 }else if( c=='?' ){ 5074 if( (*(z++))==0 ) return 0; 5075 }else if( c=='[' ){ 5076 int prior_c = 0; 5077 seen = 0; 5078 invert = 0; 5079 c = *(z++); 5080 if( c==0 ) return 0; 5081 c2 = *(zGlob++); 5082 if( c2=='^' ){ 5083 invert = 1; 5084 c2 = *(zGlob++); 5085 } 5086 if( c2==']' ){ 5087 if( c==']' ) seen = 1; 5088 c2 = *(zGlob++); 5089 } 5090 while( c2 && c2!=']' ){ 5091 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ 5092 c2 = *(zGlob++); 5093 if( c>=prior_c && c<=c2 ) seen = 1; 5094 prior_c = 0; 5095 }else{ 5096 if( c==c2 ){ 5097 seen = 1; 5098 } 5099 prior_c = c2; 5100 } 5101 c2 = *(zGlob++); 5102 } 5103 if( c2==0 || (seen ^ invert)==0 ) return 0; 5104 }else if( c=='#' ){ 5105 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; 5106 if( !IsDigit(z[0]) ) return 0; 5107 z++; 5108 while( IsDigit(z[0]) ){ z++; } 5109 }else{ 5110 if( c!=(*(z++)) ) return 0; 5111 } 5112 } 5113 while( IsSpace(*z) ){ z++; } 5114 return *z==0; 5115} 5116 5117 5118/* 5119** Compare the string as a command-line option with either one or two 5120** initial "-" characters. 5121*/ 5122static int optionMatch(const char *zStr, const char *zOpt){ 5123 if( zStr[0]!='-' ) return 0; 5124 zStr++; 5125 if( zStr[0]=='-' ) zStr++; 5126 return strcmp(zStr, zOpt)==0; 5127} 5128 5129/* 5130** Delete a file. 5131*/ 5132int shellDeleteFile(const char *zFilename){ 5133 int rc; 5134#ifdef _WIN32 5135 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); 5136 rc = _wunlink(z); 5137 sqlite3_free(z); 5138#else 5139 rc = unlink(zFilename); 5140#endif 5141 return rc; 5142} 5143 5144/* 5145** Try to delete the temporary file (if there is one) and free the 5146** memory used to hold the name of the temp file. 5147*/ 5148static void clearTempFile(ShellState *p){ 5149 if( p->zTempFile==0 ) return; 5150 if( p->doXdgOpen ) return; 5151 if( shellDeleteFile(p->zTempFile) ) return; 5152 sqlite3_free(p->zTempFile); 5153 p->zTempFile = 0; 5154} 5155 5156/* 5157** Create a new temp file name with the given suffix. 5158*/ 5159static void newTempFile(ShellState *p, const char *zSuffix){ 5160 clearTempFile(p); 5161 sqlite3_free(p->zTempFile); 5162 p->zTempFile = 0; 5163 if( p->db ){ 5164 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); 5165 } 5166 if( p->zTempFile==0 ){ 5167 sqlite3_uint64 r; 5168 sqlite3_randomness(sizeof(r), &r); 5169 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix); 5170 }else{ 5171 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); 5172 } 5173 if( p->zTempFile==0 ){ 5174 raw_printf(stderr, "out of memory\n"); 5175 exit(1); 5176 } 5177} 5178 5179 5180/* 5181** The implementation of SQL scalar function fkey_collate_clause(), used 5182** by the ".lint fkey-indexes" command. This scalar function is always 5183** called with four arguments - the parent table name, the parent column name, 5184** the child table name and the child column name. 5185** 5186** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') 5187** 5188** If either of the named tables or columns do not exist, this function 5189** returns an empty string. An empty string is also returned if both tables 5190** and columns exist but have the same default collation sequence. Or, 5191** if both exist but the default collation sequences are different, this 5192** function returns the string " COLLATE <parent-collation>", where 5193** <parent-collation> is the default collation sequence of the parent column. 5194*/ 5195static void shellFkeyCollateClause( 5196 sqlite3_context *pCtx, 5197 int nVal, 5198 sqlite3_value **apVal 5199){ 5200 sqlite3 *db = sqlite3_context_db_handle(pCtx); 5201 const char *zParent; 5202 const char *zParentCol; 5203 const char *zParentSeq; 5204 const char *zChild; 5205 const char *zChildCol; 5206 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ 5207 int rc; 5208 5209 assert( nVal==4 ); 5210 zParent = (const char*)sqlite3_value_text(apVal[0]); 5211 zParentCol = (const char*)sqlite3_value_text(apVal[1]); 5212 zChild = (const char*)sqlite3_value_text(apVal[2]); 5213 zChildCol = (const char*)sqlite3_value_text(apVal[3]); 5214 5215 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); 5216 rc = sqlite3_table_column_metadata( 5217 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 5218 ); 5219 if( rc==SQLITE_OK ){ 5220 rc = sqlite3_table_column_metadata( 5221 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 5222 ); 5223 } 5224 5225 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ 5226 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); 5227 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); 5228 sqlite3_free(z); 5229 } 5230} 5231 5232 5233/* 5234** The implementation of dot-command ".lint fkey-indexes". 5235*/ 5236static int lintFkeyIndexes( 5237 ShellState *pState, /* Current shell tool state */ 5238 char **azArg, /* Array of arguments passed to dot command */ 5239 int nArg /* Number of entries in azArg[] */ 5240){ 5241 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ 5242 FILE *out = pState->out; /* Stream to write non-error output to */ 5243 int bVerbose = 0; /* If -verbose is present */ 5244 int bGroupByParent = 0; /* If -groupbyparent is present */ 5245 int i; /* To iterate through azArg[] */ 5246 const char *zIndent = ""; /* How much to indent CREATE INDEX by */ 5247 int rc; /* Return code */ 5248 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ 5249 5250 /* 5251 ** This SELECT statement returns one row for each foreign key constraint 5252 ** in the schema of the main database. The column values are: 5253 ** 5254 ** 0. The text of an SQL statement similar to: 5255 ** 5256 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" 5257 ** 5258 ** This SELECT is similar to the one that the foreign keys implementation 5259 ** needs to run internally on child tables. If there is an index that can 5260 ** be used to optimize this query, then it can also be used by the FK 5261 ** implementation to optimize DELETE or UPDATE statements on the parent 5262 ** table. 5263 ** 5264 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by 5265 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema 5266 ** contains an index that can be used to optimize the query. 5267 ** 5268 ** 2. Human readable text that describes the child table and columns. e.g. 5269 ** 5270 ** "child_table(child_key1, child_key2)" 5271 ** 5272 ** 3. Human readable text that describes the parent table and columns. e.g. 5273 ** 5274 ** "parent_table(parent_key1, parent_key2)" 5275 ** 5276 ** 4. A full CREATE INDEX statement for an index that could be used to 5277 ** optimize DELETE or UPDATE statements on the parent table. e.g. 5278 ** 5279 ** "CREATE INDEX child_table_child_key ON child_table(child_key)" 5280 ** 5281 ** 5. The name of the parent table. 5282 ** 5283 ** These six values are used by the C logic below to generate the report. 5284 */ 5285 const char *zSql = 5286 "SELECT " 5287 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" 5288 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " 5289 " || fkey_collate_clause(" 5290 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" 5291 ", " 5292 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('" 5293 " || group_concat('*=?', ' AND ') || ')'" 5294 ", " 5295 " s.name || '(' || group_concat(f.[from], ', ') || ')'" 5296 ", " 5297 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" 5298 ", " 5299 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" 5300 " || ' ON ' || quote(s.name) || '('" 5301 " || group_concat(quote(f.[from]) ||" 5302 " fkey_collate_clause(" 5303 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" 5304 " || ');'" 5305 ", " 5306 " f.[table] " 5307 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f " 5308 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " 5309 "GROUP BY s.name, f.id " 5310 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" 5311 ; 5312 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)"; 5313 5314 for(i=2; i<nArg; i++){ 5315 int n = strlen30(azArg[i]); 5316 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ 5317 bVerbose = 1; 5318 } 5319 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ 5320 bGroupByParent = 1; 5321 zIndent = " "; 5322 } 5323 else{ 5324 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", 5325 azArg[0], azArg[1] 5326 ); 5327 return SQLITE_ERROR; 5328 } 5329 } 5330 5331 /* Register the fkey_collate_clause() SQL function */ 5332 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, 5333 0, shellFkeyCollateClause, 0, 0 5334 ); 5335 5336 5337 if( rc==SQLITE_OK ){ 5338 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); 5339 } 5340 if( rc==SQLITE_OK ){ 5341 sqlite3_bind_int(pSql, 1, bGroupByParent); 5342 } 5343 5344 if( rc==SQLITE_OK ){ 5345 int rc2; 5346 char *zPrev = 0; 5347 while( SQLITE_ROW==sqlite3_step(pSql) ){ 5348 int res = -1; 5349 sqlite3_stmt *pExplain = 0; 5350 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); 5351 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); 5352 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); 5353 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); 5354 const char *zCI = (const char*)sqlite3_column_text(pSql, 4); 5355 const char *zParent = (const char*)sqlite3_column_text(pSql, 5); 5356 5357 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 5358 if( rc!=SQLITE_OK ) break; 5359 if( SQLITE_ROW==sqlite3_step(pExplain) ){ 5360 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); 5361 res = ( 5362 0==sqlite3_strglob(zGlob, zPlan) 5363 || 0==sqlite3_strglob(zGlobIPK, zPlan) 5364 ); 5365 } 5366 rc = sqlite3_finalize(pExplain); 5367 if( rc!=SQLITE_OK ) break; 5368 5369 if( res<0 ){ 5370 raw_printf(stderr, "Error: internal error"); 5371 break; 5372 }else{ 5373 if( bGroupByParent 5374 && (bVerbose || res==0) 5375 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 5376 ){ 5377 raw_printf(out, "-- Parent table %s\n", zParent); 5378 sqlite3_free(zPrev); 5379 zPrev = sqlite3_mprintf("%s", zParent); 5380 } 5381 5382 if( res==0 ){ 5383 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); 5384 }else if( bVerbose ){ 5385 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 5386 zIndent, zFrom, zTarget 5387 ); 5388 } 5389 } 5390 } 5391 sqlite3_free(zPrev); 5392 5393 if( rc!=SQLITE_OK ){ 5394 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5395 } 5396 5397 rc2 = sqlite3_finalize(pSql); 5398 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ 5399 rc = rc2; 5400 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5401 } 5402 }else{ 5403 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5404 } 5405 5406 return rc; 5407} 5408 5409/* 5410** Implementation of ".lint" dot command. 5411*/ 5412static int lintDotCommand( 5413 ShellState *pState, /* Current shell tool state */ 5414 char **azArg, /* Array of arguments passed to dot command */ 5415 int nArg /* Number of entries in azArg[] */ 5416){ 5417 int n; 5418 n = (nArg>=2 ? strlen30(azArg[1]) : 0); 5419 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; 5420 return lintFkeyIndexes(pState, azArg, nArg); 5421 5422 usage: 5423 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); 5424 raw_printf(stderr, "Where sub-commands are:\n"); 5425 raw_printf(stderr, " fkey-indexes\n"); 5426 return SQLITE_ERROR; 5427} 5428 5429#if !defined SQLITE_OMIT_VIRTUALTABLE 5430static void shellPrepare( 5431 sqlite3 *db, 5432 int *pRc, 5433 const char *zSql, 5434 sqlite3_stmt **ppStmt 5435){ 5436 *ppStmt = 0; 5437 if( *pRc==SQLITE_OK ){ 5438 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); 5439 if( rc!=SQLITE_OK ){ 5440 raw_printf(stderr, "sql error: %s (%d)\n", 5441 sqlite3_errmsg(db), sqlite3_errcode(db) 5442 ); 5443 *pRc = rc; 5444 } 5445 } 5446} 5447 5448/* 5449** Create a prepared statement using printf-style arguments for the SQL. 5450** 5451** This routine is could be marked "static". But it is not always used, 5452** depending on compile-time options. By omitting the "static", we avoid 5453** nuisance compiler warnings about "defined but not used". 5454*/ 5455void shellPreparePrintf( 5456 sqlite3 *db, 5457 int *pRc, 5458 sqlite3_stmt **ppStmt, 5459 const char *zFmt, 5460 ... 5461){ 5462 *ppStmt = 0; 5463 if( *pRc==SQLITE_OK ){ 5464 va_list ap; 5465 char *z; 5466 va_start(ap, zFmt); 5467 z = sqlite3_vmprintf(zFmt, ap); 5468 va_end(ap); 5469 if( z==0 ){ 5470 *pRc = SQLITE_NOMEM; 5471 }else{ 5472 shellPrepare(db, pRc, z, ppStmt); 5473 sqlite3_free(z); 5474 } 5475 } 5476} 5477 5478/* Finalize the prepared statement created using shellPreparePrintf(). 5479** 5480** This routine is could be marked "static". But it is not always used, 5481** depending on compile-time options. By omitting the "static", we avoid 5482** nuisance compiler warnings about "defined but not used". 5483*/ 5484void shellFinalize( 5485 int *pRc, 5486 sqlite3_stmt *pStmt 5487){ 5488 if( pStmt ){ 5489 sqlite3 *db = sqlite3_db_handle(pStmt); 5490 int rc = sqlite3_finalize(pStmt); 5491 if( *pRc==SQLITE_OK ){ 5492 if( rc!=SQLITE_OK ){ 5493 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 5494 } 5495 *pRc = rc; 5496 } 5497 } 5498} 5499 5500/* Reset the prepared statement created using shellPreparePrintf(). 5501** 5502** This routine is could be marked "static". But it is not always used, 5503** depending on compile-time options. By omitting the "static", we avoid 5504** nuisance compiler warnings about "defined but not used". 5505*/ 5506void shellReset( 5507 int *pRc, 5508 sqlite3_stmt *pStmt 5509){ 5510 int rc = sqlite3_reset(pStmt); 5511 if( *pRc==SQLITE_OK ){ 5512 if( rc!=SQLITE_OK ){ 5513 sqlite3 *db = sqlite3_db_handle(pStmt); 5514 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 5515 } 5516 *pRc = rc; 5517 } 5518} 5519#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ 5520 5521#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 5522/********************************************************************************* 5523** The ".archive" or ".ar" command. 5524*/ 5525/* 5526** Structure representing a single ".ar" command. 5527*/ 5528typedef struct ArCommand ArCommand; 5529struct ArCommand { 5530 u8 eCmd; /* An AR_CMD_* value */ 5531 u8 bVerbose; /* True if --verbose */ 5532 u8 bZip; /* True if the archive is a ZIP */ 5533 u8 bDryRun; /* True if --dry-run */ 5534 u8 bAppend; /* True if --append */ 5535 u8 fromCmdLine; /* Run from -A instead of .archive */ 5536 int nArg; /* Number of command arguments */ 5537 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ 5538 const char *zFile; /* --file argument, or NULL */ 5539 const char *zDir; /* --directory argument, or NULL */ 5540 char **azArg; /* Array of command arguments */ 5541 ShellState *p; /* Shell state */ 5542 sqlite3 *db; /* Database containing the archive */ 5543}; 5544 5545/* 5546** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. 5547*/ 5548static int arUsage(FILE *f){ 5549 showHelp(f,"archive"); 5550 return SQLITE_ERROR; 5551} 5552 5553/* 5554** Print an error message for the .ar command to stderr and return 5555** SQLITE_ERROR. 5556*/ 5557static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ 5558 va_list ap; 5559 char *z; 5560 va_start(ap, zFmt); 5561 z = sqlite3_vmprintf(zFmt, ap); 5562 va_end(ap); 5563 utf8_printf(stderr, "Error: %s\n", z); 5564 if( pAr->fromCmdLine ){ 5565 utf8_printf(stderr, "Use \"-A\" for more help\n"); 5566 }else{ 5567 utf8_printf(stderr, "Use \".archive --help\" for more help\n"); 5568 } 5569 sqlite3_free(z); 5570 return SQLITE_ERROR; 5571} 5572 5573/* 5574** Values for ArCommand.eCmd. 5575*/ 5576#define AR_CMD_CREATE 1 5577#define AR_CMD_UPDATE 2 5578#define AR_CMD_INSERT 3 5579#define AR_CMD_EXTRACT 4 5580#define AR_CMD_LIST 5 5581#define AR_CMD_HELP 6 5582 5583/* 5584** Other (non-command) switches. 5585*/ 5586#define AR_SWITCH_VERBOSE 7 5587#define AR_SWITCH_FILE 8 5588#define AR_SWITCH_DIRECTORY 9 5589#define AR_SWITCH_APPEND 10 5590#define AR_SWITCH_DRYRUN 11 5591 5592static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ 5593 switch( eSwitch ){ 5594 case AR_CMD_CREATE: 5595 case AR_CMD_EXTRACT: 5596 case AR_CMD_LIST: 5597 case AR_CMD_UPDATE: 5598 case AR_CMD_INSERT: 5599 case AR_CMD_HELP: 5600 if( pAr->eCmd ){ 5601 return arErrorMsg(pAr, "multiple command options"); 5602 } 5603 pAr->eCmd = eSwitch; 5604 break; 5605 5606 case AR_SWITCH_DRYRUN: 5607 pAr->bDryRun = 1; 5608 break; 5609 case AR_SWITCH_VERBOSE: 5610 pAr->bVerbose = 1; 5611 break; 5612 case AR_SWITCH_APPEND: 5613 pAr->bAppend = 1; 5614 /* Fall thru into --file */ 5615 case AR_SWITCH_FILE: 5616 pAr->zFile = zArg; 5617 break; 5618 case AR_SWITCH_DIRECTORY: 5619 pAr->zDir = zArg; 5620 break; 5621 } 5622 5623 return SQLITE_OK; 5624} 5625 5626/* 5627** Parse the command line for an ".ar" command. The results are written into 5628** structure (*pAr). SQLITE_OK is returned if the command line is parsed 5629** successfully, otherwise an error message is written to stderr and 5630** SQLITE_ERROR returned. 5631*/ 5632static int arParseCommand( 5633 char **azArg, /* Array of arguments passed to dot command */ 5634 int nArg, /* Number of entries in azArg[] */ 5635 ArCommand *pAr /* Populate this object */ 5636){ 5637 struct ArSwitch { 5638 const char *zLong; 5639 char cShort; 5640 u8 eSwitch; 5641 u8 bArg; 5642 } aSwitch[] = { 5643 { "create", 'c', AR_CMD_CREATE, 0 }, 5644 { "extract", 'x', AR_CMD_EXTRACT, 0 }, 5645 { "insert", 'i', AR_CMD_INSERT, 0 }, 5646 { "list", 't', AR_CMD_LIST, 0 }, 5647 { "update", 'u', AR_CMD_UPDATE, 0 }, 5648 { "help", 'h', AR_CMD_HELP, 0 }, 5649 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, 5650 { "file", 'f', AR_SWITCH_FILE, 1 }, 5651 { "append", 'a', AR_SWITCH_APPEND, 1 }, 5652 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, 5653 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, 5654 }; 5655 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); 5656 struct ArSwitch *pEnd = &aSwitch[nSwitch]; 5657 5658 if( nArg<=1 ){ 5659 utf8_printf(stderr, "Wrong number of arguments. Usage:\n"); 5660 return arUsage(stderr); 5661 }else{ 5662 char *z = azArg[1]; 5663 if( z[0]!='-' ){ 5664 /* Traditional style [tar] invocation */ 5665 int i; 5666 int iArg = 2; 5667 for(i=0; z[i]; i++){ 5668 const char *zArg = 0; 5669 struct ArSwitch *pOpt; 5670 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5671 if( z[i]==pOpt->cShort ) break; 5672 } 5673 if( pOpt==pEnd ){ 5674 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 5675 } 5676 if( pOpt->bArg ){ 5677 if( iArg>=nArg ){ 5678 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 5679 } 5680 zArg = azArg[iArg++]; 5681 } 5682 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 5683 } 5684 pAr->nArg = nArg-iArg; 5685 if( pAr->nArg>0 ){ 5686 pAr->azArg = &azArg[iArg]; 5687 } 5688 }else{ 5689 /* Non-traditional invocation */ 5690 int iArg; 5691 for(iArg=1; iArg<nArg; iArg++){ 5692 int n; 5693 z = azArg[iArg]; 5694 if( z[0]!='-' ){ 5695 /* All remaining command line words are command arguments. */ 5696 pAr->azArg = &azArg[iArg]; 5697 pAr->nArg = nArg-iArg; 5698 break; 5699 } 5700 n = strlen30(z); 5701 5702 if( z[1]!='-' ){ 5703 int i; 5704 /* One or more short options */ 5705 for(i=1; i<n; i++){ 5706 const char *zArg = 0; 5707 struct ArSwitch *pOpt; 5708 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5709 if( z[i]==pOpt->cShort ) break; 5710 } 5711 if( pOpt==pEnd ){ 5712 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 5713 } 5714 if( pOpt->bArg ){ 5715 if( i<(n-1) ){ 5716 zArg = &z[i+1]; 5717 i = n; 5718 }else{ 5719 if( iArg>=(nArg-1) ){ 5720 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 5721 } 5722 zArg = azArg[++iArg]; 5723 } 5724 } 5725 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 5726 } 5727 }else if( z[2]=='\0' ){ 5728 /* A -- option, indicating that all remaining command line words 5729 ** are command arguments. */ 5730 pAr->azArg = &azArg[iArg+1]; 5731 pAr->nArg = nArg-iArg-1; 5732 break; 5733 }else{ 5734 /* A long option */ 5735 const char *zArg = 0; /* Argument for option, if any */ 5736 struct ArSwitch *pMatch = 0; /* Matching option */ 5737 struct ArSwitch *pOpt; /* Iterator */ 5738 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5739 const char *zLong = pOpt->zLong; 5740 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ 5741 if( pMatch ){ 5742 return arErrorMsg(pAr, "ambiguous option: %s",z); 5743 }else{ 5744 pMatch = pOpt; 5745 } 5746 } 5747 } 5748 5749 if( pMatch==0 ){ 5750 return arErrorMsg(pAr, "unrecognized option: %s", z); 5751 } 5752 if( pMatch->bArg ){ 5753 if( iArg>=(nArg-1) ){ 5754 return arErrorMsg(pAr, "option requires an argument: %s", z); 5755 } 5756 zArg = azArg[++iArg]; 5757 } 5758 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; 5759 } 5760 } 5761 } 5762 } 5763 5764 return SQLITE_OK; 5765} 5766 5767/* 5768** This function assumes that all arguments within the ArCommand.azArg[] 5769** array refer to archive members, as for the --extract or --list commands. 5770** It checks that each of them are present. If any specified file is not 5771** present in the archive, an error is printed to stderr and an error 5772** code returned. Otherwise, if all specified arguments are present in 5773** the archive, SQLITE_OK is returned. 5774** 5775** This function strips any trailing '/' characters from each argument. 5776** This is consistent with the way the [tar] command seems to work on 5777** Linux. 5778*/ 5779static int arCheckEntries(ArCommand *pAr){ 5780 int rc = SQLITE_OK; 5781 if( pAr->nArg ){ 5782 int i, j; 5783 sqlite3_stmt *pTest = 0; 5784 5785 shellPreparePrintf(pAr->db, &rc, &pTest, 5786 "SELECT name FROM %s WHERE name=$name", 5787 pAr->zSrcTable 5788 ); 5789 j = sqlite3_bind_parameter_index(pTest, "$name"); 5790 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 5791 char *z = pAr->azArg[i]; 5792 int n = strlen30(z); 5793 int bOk = 0; 5794 while( n>0 && z[n-1]=='/' ) n--; 5795 z[n] = '\0'; 5796 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); 5797 if( SQLITE_ROW==sqlite3_step(pTest) ){ 5798 bOk = 1; 5799 } 5800 shellReset(&rc, pTest); 5801 if( rc==SQLITE_OK && bOk==0 ){ 5802 utf8_printf(stderr, "not found in archive: %s\n", z); 5803 rc = SQLITE_ERROR; 5804 } 5805 } 5806 shellFinalize(&rc, pTest); 5807 } 5808 return rc; 5809} 5810 5811/* 5812** Format a WHERE clause that can be used against the "sqlar" table to 5813** identify all archive members that match the command arguments held 5814** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. 5815** The caller is responsible for eventually calling sqlite3_free() on 5816** any non-NULL (*pzWhere) value. 5817*/ 5818static void arWhereClause( 5819 int *pRc, 5820 ArCommand *pAr, 5821 char **pzWhere /* OUT: New WHERE clause */ 5822){ 5823 char *zWhere = 0; 5824 if( *pRc==SQLITE_OK ){ 5825 if( pAr->nArg==0 ){ 5826 zWhere = sqlite3_mprintf("1"); 5827 }else{ 5828 int i; 5829 const char *zSep = ""; 5830 for(i=0; i<pAr->nArg; i++){ 5831 const char *z = pAr->azArg[i]; 5832 zWhere = sqlite3_mprintf( 5833 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 5834 zWhere, zSep, z, strlen30(z)+1, z 5835 ); 5836 if( zWhere==0 ){ 5837 *pRc = SQLITE_NOMEM; 5838 break; 5839 } 5840 zSep = " OR "; 5841 } 5842 } 5843 } 5844 *pzWhere = zWhere; 5845} 5846 5847/* 5848** Implementation of .ar "lisT" command. 5849*/ 5850static int arListCommand(ArCommand *pAr){ 5851 const char *zSql = "SELECT %s FROM %s WHERE %s"; 5852 const char *azCols[] = { 5853 "name", 5854 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" 5855 }; 5856 5857 char *zWhere = 0; 5858 sqlite3_stmt *pSql = 0; 5859 int rc; 5860 5861 rc = arCheckEntries(pAr); 5862 arWhereClause(&rc, pAr, &zWhere); 5863 5864 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], 5865 pAr->zSrcTable, zWhere); 5866 if( pAr->bDryRun ){ 5867 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 5868 }else{ 5869 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 5870 if( pAr->bVerbose ){ 5871 utf8_printf(pAr->p->out, "%s % 10d %s %s\n", 5872 sqlite3_column_text(pSql, 0), 5873 sqlite3_column_int(pSql, 1), 5874 sqlite3_column_text(pSql, 2), 5875 sqlite3_column_text(pSql, 3) 5876 ); 5877 }else{ 5878 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 5879 } 5880 } 5881 } 5882 shellFinalize(&rc, pSql); 5883 sqlite3_free(zWhere); 5884 return rc; 5885} 5886 5887 5888/* 5889** Implementation of .ar "eXtract" command. 5890*/ 5891static int arExtractCommand(ArCommand *pAr){ 5892 const char *zSql1 = 5893 "SELECT " 5894 " ($dir || name)," 5895 " writefile(($dir || name), %s, mode, mtime) " 5896 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" 5897 " AND name NOT GLOB '*..[/\\]*'"; 5898 5899 const char *azExtraArg[] = { 5900 "sqlar_uncompress(data, sz)", 5901 "data" 5902 }; 5903 5904 sqlite3_stmt *pSql = 0; 5905 int rc = SQLITE_OK; 5906 char *zDir = 0; 5907 char *zWhere = 0; 5908 int i, j; 5909 5910 /* If arguments are specified, check that they actually exist within 5911 ** the archive before proceeding. And formulate a WHERE clause to 5912 ** match them. */ 5913 rc = arCheckEntries(pAr); 5914 arWhereClause(&rc, pAr, &zWhere); 5915 5916 if( rc==SQLITE_OK ){ 5917 if( pAr->zDir ){ 5918 zDir = sqlite3_mprintf("%s/", pAr->zDir); 5919 }else{ 5920 zDir = sqlite3_mprintf(""); 5921 } 5922 if( zDir==0 ) rc = SQLITE_NOMEM; 5923 } 5924 5925 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 5926 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere 5927 ); 5928 5929 if( rc==SQLITE_OK ){ 5930 j = sqlite3_bind_parameter_index(pSql, "$dir"); 5931 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); 5932 5933 /* Run the SELECT statement twice. The first time, writefile() is called 5934 ** for all archive members that should be extracted. The second time, 5935 ** only for the directories. This is because the timestamps for 5936 ** extracted directories must be reset after they are populated (as 5937 ** populating them changes the timestamp). */ 5938 for(i=0; i<2; i++){ 5939 j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); 5940 sqlite3_bind_int(pSql, j, i); 5941 if( pAr->bDryRun ){ 5942 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 5943 }else{ 5944 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 5945 if( i==0 && pAr->bVerbose ){ 5946 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 5947 } 5948 } 5949 } 5950 shellReset(&rc, pSql); 5951 } 5952 shellFinalize(&rc, pSql); 5953 } 5954 5955 sqlite3_free(zDir); 5956 sqlite3_free(zWhere); 5957 return rc; 5958} 5959 5960/* 5961** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. 5962*/ 5963static int arExecSql(ArCommand *pAr, const char *zSql){ 5964 int rc; 5965 if( pAr->bDryRun ){ 5966 utf8_printf(pAr->p->out, "%s\n", zSql); 5967 rc = SQLITE_OK; 5968 }else{ 5969 char *zErr = 0; 5970 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 5971 if( zErr ){ 5972 utf8_printf(stdout, "ERROR: %s\n", zErr); 5973 sqlite3_free(zErr); 5974 } 5975 } 5976 return rc; 5977} 5978 5979 5980/* 5981** Implementation of .ar "create", "insert", and "update" commands. 5982** 5983** create -> Create a new SQL archive 5984** insert -> Insert or reinsert all files listed 5985** update -> Insert files that have changed or that were not 5986** previously in the archive 5987** 5988** Create the "sqlar" table in the database if it does not already exist. 5989** Then add each file in the azFile[] array to the archive. Directories 5990** are added recursively. If argument bVerbose is non-zero, a message is 5991** printed on stdout for each file archived. 5992** 5993** The create command is the same as update, except that it drops 5994** any existing "sqlar" table before beginning. The "insert" command 5995** always overwrites every file named on the command-line, where as 5996** "update" only overwrites if the size or mtime or mode has changed. 5997*/ 5998static int arCreateOrUpdateCommand( 5999 ArCommand *pAr, /* Command arguments and options */ 6000 int bUpdate, /* true for a --create. */ 6001 int bOnlyIfChanged /* Only update if file has changed */ 6002){ 6003 const char *zCreate = 6004 "CREATE TABLE IF NOT EXISTS sqlar(\n" 6005 " name TEXT PRIMARY KEY, -- name of the file\n" 6006 " mode INT, -- access permissions\n" 6007 " mtime INT, -- last modification time\n" 6008 " sz INT, -- original file size\n" 6009 " data BLOB -- compressed content\n" 6010 ")"; 6011 const char *zDrop = "DROP TABLE IF EXISTS sqlar"; 6012 const char *zInsertFmt[2] = { 6013 "REPLACE INTO %s(name,mode,mtime,sz,data)\n" 6014 " SELECT\n" 6015 " %s,\n" 6016 " mode,\n" 6017 " mtime,\n" 6018 " CASE substr(lsmode(mode),1,1)\n" 6019 " WHEN '-' THEN length(data)\n" 6020 " WHEN 'd' THEN 0\n" 6021 " ELSE -1 END,\n" 6022 " sqlar_compress(data)\n" 6023 " FROM fsdir(%Q,%Q) AS disk\n" 6024 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6025 , 6026 "REPLACE INTO %s(name,mode,mtime,data)\n" 6027 " SELECT\n" 6028 " %s,\n" 6029 " mode,\n" 6030 " mtime,\n" 6031 " data\n" 6032 " FROM fsdir(%Q,%Q) AS disk\n" 6033 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6034 }; 6035 int i; /* For iterating through azFile[] */ 6036 int rc; /* Return code */ 6037 const char *zTab = 0; /* SQL table into which to insert */ 6038 char *zSql; 6039 char zTemp[50]; 6040 char *zExists = 0; 6041 6042 arExecSql(pAr, "PRAGMA page_size=512"); 6043 rc = arExecSql(pAr, "SAVEPOINT ar;"); 6044 if( rc!=SQLITE_OK ) return rc; 6045 zTemp[0] = 0; 6046 if( pAr->bZip ){ 6047 /* Initialize the zipfile virtual table, if necessary */ 6048 if( pAr->zFile ){ 6049 sqlite3_uint64 r; 6050 sqlite3_randomness(sizeof(r),&r); 6051 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); 6052 zTab = zTemp; 6053 zSql = sqlite3_mprintf( 6054 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", 6055 zTab, pAr->zFile 6056 ); 6057 rc = arExecSql(pAr, zSql); 6058 sqlite3_free(zSql); 6059 }else{ 6060 zTab = "zip"; 6061 } 6062 }else{ 6063 /* Initialize the table for an SQLAR */ 6064 zTab = "sqlar"; 6065 if( bUpdate==0 ){ 6066 rc = arExecSql(pAr, zDrop); 6067 if( rc!=SQLITE_OK ) goto end_ar_transaction; 6068 } 6069 rc = arExecSql(pAr, zCreate); 6070 } 6071 if( bOnlyIfChanged ){ 6072 zExists = sqlite3_mprintf( 6073 " AND NOT EXISTS(" 6074 "SELECT 1 FROM %s AS mem" 6075 " WHERE mem.name=disk.name" 6076 " AND mem.mtime=disk.mtime" 6077 " AND mem.mode=disk.mode)", zTab); 6078 }else{ 6079 zExists = sqlite3_mprintf(""); 6080 } 6081 if( zExists==0 ) rc = SQLITE_NOMEM; 6082 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6083 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, 6084 pAr->bVerbose ? "shell_putsnl(name)" : "name", 6085 pAr->azArg[i], pAr->zDir, zExists); 6086 rc = arExecSql(pAr, zSql2); 6087 sqlite3_free(zSql2); 6088 } 6089end_ar_transaction: 6090 if( rc!=SQLITE_OK ){ 6091 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 6092 }else{ 6093 rc = arExecSql(pAr, "RELEASE ar;"); 6094 if( pAr->bZip && pAr->zFile ){ 6095 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); 6096 arExecSql(pAr, zSql); 6097 sqlite3_free(zSql); 6098 } 6099 } 6100 sqlite3_free(zExists); 6101 return rc; 6102} 6103 6104/* 6105** Implementation of ".ar" dot command. 6106*/ 6107static int arDotCommand( 6108 ShellState *pState, /* Current shell tool state */ 6109 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ 6110 char **azArg, /* Array of arguments passed to dot command */ 6111 int nArg /* Number of entries in azArg[] */ 6112){ 6113 ArCommand cmd; 6114 int rc; 6115 memset(&cmd, 0, sizeof(cmd)); 6116 cmd.fromCmdLine = fromCmdLine; 6117 rc = arParseCommand(azArg, nArg, &cmd); 6118 if( rc==SQLITE_OK ){ 6119 int eDbType = SHELL_OPEN_UNSPEC; 6120 cmd.p = pState; 6121 cmd.db = pState->db; 6122 if( cmd.zFile ){ 6123 eDbType = deduceDatabaseType(cmd.zFile, 1); 6124 }else{ 6125 eDbType = pState->openMode; 6126 } 6127 if( eDbType==SHELL_OPEN_ZIPFILE ){ 6128 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ 6129 if( cmd.zFile==0 ){ 6130 cmd.zSrcTable = sqlite3_mprintf("zip"); 6131 }else{ 6132 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); 6133 } 6134 } 6135 cmd.bZip = 1; 6136 }else if( cmd.zFile ){ 6137 int flags; 6138 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; 6139 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 6140 || cmd.eCmd==AR_CMD_UPDATE ){ 6141 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 6142 }else{ 6143 flags = SQLITE_OPEN_READONLY; 6144 } 6145 cmd.db = 0; 6146 if( cmd.bDryRun ){ 6147 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, 6148 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); 6149 } 6150 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 6151 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); 6152 if( rc!=SQLITE_OK ){ 6153 utf8_printf(stderr, "cannot open file: %s (%s)\n", 6154 cmd.zFile, sqlite3_errmsg(cmd.db) 6155 ); 6156 goto end_ar_command; 6157 } 6158 sqlite3_fileio_init(cmd.db, 0, 0); 6159 sqlite3_sqlar_init(cmd.db, 0, 0); 6160 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, 6161 shellPutsFunc, 0, 0); 6162 6163 } 6164 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ 6165 if( cmd.eCmd!=AR_CMD_CREATE 6166 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) 6167 ){ 6168 utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); 6169 rc = SQLITE_ERROR; 6170 goto end_ar_command; 6171 } 6172 cmd.zSrcTable = sqlite3_mprintf("sqlar"); 6173 } 6174 6175 switch( cmd.eCmd ){ 6176 case AR_CMD_CREATE: 6177 rc = arCreateOrUpdateCommand(&cmd, 0, 0); 6178 break; 6179 6180 case AR_CMD_EXTRACT: 6181 rc = arExtractCommand(&cmd); 6182 break; 6183 6184 case AR_CMD_LIST: 6185 rc = arListCommand(&cmd); 6186 break; 6187 6188 case AR_CMD_HELP: 6189 arUsage(pState->out); 6190 break; 6191 6192 case AR_CMD_INSERT: 6193 rc = arCreateOrUpdateCommand(&cmd, 1, 0); 6194 break; 6195 6196 default: 6197 assert( cmd.eCmd==AR_CMD_UPDATE ); 6198 rc = arCreateOrUpdateCommand(&cmd, 1, 1); 6199 break; 6200 } 6201 } 6202end_ar_command: 6203 if( cmd.db!=pState->db ){ 6204 close_db(cmd.db); 6205 } 6206 sqlite3_free(cmd.zSrcTable); 6207 6208 return rc; 6209} 6210/* End of the ".archive" or ".ar" command logic 6211**********************************************************************************/ 6212#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ 6213 6214#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 6215/* 6216** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op. 6217** Otherwise, the SQL statement or statements in zSql are executed using 6218** database connection db and the error code written to *pRc before 6219** this function returns. 6220*/ 6221static void shellExec(sqlite3 *db, int *pRc, const char *zSql){ 6222 int rc = *pRc; 6223 if( rc==SQLITE_OK ){ 6224 char *zErr = 0; 6225 rc = sqlite3_exec(db, zSql, 0, 0, &zErr); 6226 if( rc!=SQLITE_OK ){ 6227 raw_printf(stderr, "SQL error: %s\n", zErr); 6228 } 6229 *pRc = rc; 6230 } 6231} 6232 6233/* 6234** Like shellExec(), except that zFmt is a printf() style format string. 6235*/ 6236static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){ 6237 char *z = 0; 6238 if( *pRc==SQLITE_OK ){ 6239 va_list ap; 6240 va_start(ap, zFmt); 6241 z = sqlite3_vmprintf(zFmt, ap); 6242 va_end(ap); 6243 if( z==0 ){ 6244 *pRc = SQLITE_NOMEM; 6245 }else{ 6246 shellExec(db, pRc, z); 6247 } 6248 sqlite3_free(z); 6249 } 6250} 6251 6252/* 6253** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6254** Otherwise, an attempt is made to allocate, zero and return a pointer 6255** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set 6256** to SQLITE_NOMEM and NULL returned. 6257*/ 6258static void *shellMalloc(int *pRc, sqlite3_int64 nByte){ 6259 void *pRet = 0; 6260 if( *pRc==SQLITE_OK ){ 6261 pRet = sqlite3_malloc64(nByte); 6262 if( pRet==0 ){ 6263 *pRc = SQLITE_NOMEM; 6264 }else{ 6265 memset(pRet, 0, nByte); 6266 } 6267 } 6268 return pRet; 6269} 6270 6271/* 6272** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6273** Otherwise, zFmt is treated as a printf() style string. The result of 6274** formatting it along with any trailing arguments is written into a 6275** buffer obtained from sqlite3_malloc(), and pointer to which is returned. 6276** It is the responsibility of the caller to eventually free this buffer 6277** using a call to sqlite3_free(). 6278** 6279** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL 6280** pointer returned. 6281*/ 6282static char *shellMPrintf(int *pRc, const char *zFmt, ...){ 6283 char *z = 0; 6284 if( *pRc==SQLITE_OK ){ 6285 va_list ap; 6286 va_start(ap, zFmt); 6287 z = sqlite3_vmprintf(zFmt, ap); 6288 va_end(ap); 6289 if( z==0 ){ 6290 *pRc = SQLITE_NOMEM; 6291 } 6292 } 6293 return z; 6294} 6295 6296/* 6297** When running the ".recover" command, each output table, and the special 6298** orphaned row table if it is required, is represented by an instance 6299** of the following struct. 6300*/ 6301typedef struct RecoverTable RecoverTable; 6302struct RecoverTable { 6303 char *zQuoted; /* Quoted version of table name */ 6304 int nCol; /* Number of columns in table */ 6305 char **azlCol; /* Array of column lists */ 6306 int iPk; /* Index of IPK column */ 6307}; 6308 6309/* 6310** Free a RecoverTable object allocated by recoverFindTable() or 6311** recoverOrphanTable(). 6312*/ 6313static void recoverFreeTable(RecoverTable *pTab){ 6314 if( pTab ){ 6315 sqlite3_free(pTab->zQuoted); 6316 if( pTab->azlCol ){ 6317 int i; 6318 for(i=0; i<=pTab->nCol; i++){ 6319 sqlite3_free(pTab->azlCol[i]); 6320 } 6321 sqlite3_free(pTab->azlCol); 6322 } 6323 sqlite3_free(pTab); 6324 } 6325} 6326 6327/* 6328** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. 6329** Otherwise, it allocates and returns a RecoverTable object based on the 6330** final four arguments passed to this function. It is the responsibility 6331** of the caller to eventually free the returned object using 6332** recoverFreeTable(). 6333*/ 6334static RecoverTable *recoverNewTable( 6335 int *pRc, /* IN/OUT: Error code */ 6336 const char *zName, /* Name of table */ 6337 const char *zSql, /* CREATE TABLE statement */ 6338 int bIntkey, 6339 int nCol 6340){ 6341 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */ 6342 int rc = *pRc; 6343 RecoverTable *pTab = 0; 6344 6345 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable)); 6346 if( rc==SQLITE_OK ){ 6347 int nSqlCol = 0; 6348 int bSqlIntkey = 0; 6349 sqlite3_stmt *pStmt = 0; 6350 6351 rc = sqlite3_open("", &dbtmp); 6352 if( rc==SQLITE_OK ){ 6353 sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0, 6354 shellIdQuote, 0, 0); 6355 } 6356 if( rc==SQLITE_OK ){ 6357 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0); 6358 } 6359 if( rc==SQLITE_OK ){ 6360 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0); 6361 if( rc==SQLITE_ERROR ){ 6362 rc = SQLITE_OK; 6363 goto finished; 6364 } 6365 } 6366 shellPreparePrintf(dbtmp, &rc, &pStmt, 6367 "SELECT count(*) FROM pragma_table_info(%Q)", zName 6368 ); 6369 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6370 nSqlCol = sqlite3_column_int(pStmt, 0); 6371 } 6372 shellFinalize(&rc, pStmt); 6373 6374 if( rc!=SQLITE_OK || nSqlCol<nCol ){ 6375 goto finished; 6376 } 6377 6378 shellPreparePrintf(dbtmp, &rc, &pStmt, 6379 "SELECT (" 6380 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage" 6381 ") FROM sqlite_master WHERE name = %Q", zName 6382 ); 6383 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6384 bSqlIntkey = sqlite3_column_int(pStmt, 0); 6385 } 6386 shellFinalize(&rc, pStmt); 6387 6388 if( bIntkey==bSqlIntkey ){ 6389 int i; 6390 const char *zPk = "_rowid_"; 6391 sqlite3_stmt *pPkFinder = 0; 6392 6393 /* If this is an intkey table and there is an INTEGER PRIMARY KEY, 6394 ** set zPk to the name of the PK column, and pTab->iPk to the index 6395 ** of the column, where columns are 0-numbered from left to right. 6396 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column, 6397 ** leave zPk as "_rowid_" and pTab->iPk at -2. */ 6398 pTab->iPk = -2; 6399 if( bIntkey ){ 6400 shellPreparePrintf(dbtmp, &rc, &pPkFinder, 6401 "SELECT cid, name FROM pragma_table_info(%Q) " 6402 " WHERE pk=1 AND type='integer' COLLATE nocase" 6403 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)" 6404 , zName, zName 6405 ); 6406 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){ 6407 pTab->iPk = sqlite3_column_int(pPkFinder, 0); 6408 zPk = (const char*)sqlite3_column_text(pPkFinder, 1); 6409 } 6410 } 6411 6412 pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName); 6413 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1)); 6414 pTab->nCol = nSqlCol; 6415 6416 if( bIntkey ){ 6417 pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk); 6418 }else{ 6419 pTab->azlCol[0] = shellMPrintf(&rc, ""); 6420 } 6421 i = 1; 6422 shellPreparePrintf(dbtmp, &rc, &pStmt, 6423 "SELECT %Q || group_concat(shell_idquote(name), ', ') " 6424 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) " 6425 "FROM pragma_table_info(%Q)", 6426 bIntkey ? ", " : "", pTab->iPk, 6427 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ", 6428 zName 6429 ); 6430 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6431 const char *zText = (const char*)sqlite3_column_text(pStmt, 0); 6432 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText); 6433 i++; 6434 } 6435 shellFinalize(&rc, pStmt); 6436 6437 shellFinalize(&rc, pPkFinder); 6438 } 6439 } 6440 6441 finished: 6442 sqlite3_close(dbtmp); 6443 *pRc = rc; 6444 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){ 6445 recoverFreeTable(pTab); 6446 pTab = 0; 6447 } 6448 return pTab; 6449} 6450 6451/* 6452** This function is called to search the schema recovered from the 6453** sqlite_master table of the (possibly) corrupt database as part 6454** of a ".recover" command. Specifically, for a table with root page 6455** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the 6456** table must be a WITHOUT ROWID table, or if non-zero, not one of 6457** those. 6458** 6459** If a table is found, a (RecoverTable*) object is returned. Or, if 6460** no such table is found, but bIntkey is false and iRoot is the 6461** root page of an index in the recovered schema, then (*pbNoop) is 6462** set to true and NULL returned. Or, if there is no such table or 6463** index, NULL is returned and (*pbNoop) set to 0, indicating that 6464** the caller should write data to the orphans table. 6465*/ 6466static RecoverTable *recoverFindTable( 6467 ShellState *pState, /* Shell state object */ 6468 int *pRc, /* IN/OUT: Error code */ 6469 int iRoot, /* Root page of table */ 6470 int bIntkey, /* True for an intkey table */ 6471 int nCol, /* Number of columns in table */ 6472 int *pbNoop /* OUT: True if iRoot is root of index */ 6473){ 6474 sqlite3_stmt *pStmt = 0; 6475 RecoverTable *pRet = 0; 6476 int bNoop = 0; 6477 const char *zSql = 0; 6478 const char *zName = 0; 6479 6480 /* Search the recovered schema for an object with root page iRoot. */ 6481 shellPreparePrintf(pState->db, pRc, &pStmt, 6482 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot 6483 ); 6484 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6485 const char *zType = (const char*)sqlite3_column_text(pStmt, 0); 6486 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){ 6487 bNoop = 1; 6488 break; 6489 } 6490 if( sqlite3_stricmp(zType, "table")==0 ){ 6491 zName = (const char*)sqlite3_column_text(pStmt, 1); 6492 zSql = (const char*)sqlite3_column_text(pStmt, 2); 6493 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol); 6494 break; 6495 } 6496 } 6497 6498 shellFinalize(pRc, pStmt); 6499 *pbNoop = bNoop; 6500 return pRet; 6501} 6502 6503/* 6504** Return a RecoverTable object representing the orphans table. 6505*/ 6506static RecoverTable *recoverOrphanTable( 6507 ShellState *pState, /* Shell state object */ 6508 int *pRc, /* IN/OUT: Error code */ 6509 const char *zLostAndFound, /* Base name for orphans table */ 6510 int nCol /* Number of user data columns */ 6511){ 6512 RecoverTable *pTab = 0; 6513 if( nCol>=0 && *pRc==SQLITE_OK ){ 6514 int i; 6515 6516 /* This block determines the name of the orphan table. The prefered 6517 ** name is zLostAndFound. But if that clashes with another name 6518 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1 6519 ** and so on until a non-clashing name is found. */ 6520 int iTab = 0; 6521 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound); 6522 sqlite3_stmt *pTest = 0; 6523 shellPrepare(pState->db, pRc, 6524 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest 6525 ); 6526 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 6527 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){ 6528 shellReset(pRc, pTest); 6529 sqlite3_free(zTab); 6530 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++); 6531 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 6532 } 6533 shellFinalize(pRc, pTest); 6534 6535 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable)); 6536 if( pTab ){ 6537 pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab); 6538 pTab->nCol = nCol; 6539 pTab->iPk = -2; 6540 if( nCol>0 ){ 6541 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1)); 6542 if( pTab->azlCol ){ 6543 pTab->azlCol[nCol] = shellMPrintf(pRc, ""); 6544 for(i=nCol-1; i>=0; i--){ 6545 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]); 6546 } 6547 } 6548 } 6549 6550 if( *pRc!=SQLITE_OK ){ 6551 recoverFreeTable(pTab); 6552 pTab = 0; 6553 }else{ 6554 raw_printf(pState->out, 6555 "CREATE TABLE %s(rootpgno INTEGER, " 6556 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted 6557 ); 6558 for(i=0; i<nCol; i++){ 6559 raw_printf(pState->out, ", c%d", i); 6560 } 6561 raw_printf(pState->out, ");\n"); 6562 } 6563 } 6564 sqlite3_free(zTab); 6565 } 6566 return pTab; 6567} 6568 6569/* 6570** This function is called to recover data from the database. A script 6571** to construct a new database containing all recovered data is output 6572** on stream pState->out. 6573*/ 6574static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ 6575 int rc = SQLITE_OK; 6576 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */ 6577 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */ 6578 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */ 6579 const char *zRecoveryDb = ""; /* Name of "recovery" database */ 6580 const char *zLostAndFound = "lost_and_found"; 6581 int i; 6582 int nOrphan = -1; 6583 RecoverTable *pOrphan = 0; 6584 6585 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */ 6586 for(i=1; i<nArg; i++){ 6587 char *z = azArg[i]; 6588 int n; 6589 if( z[0]=='-' && z[1]=='-' ) z++; 6590 n = strlen30(z); 6591 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){ 6592 bFreelist = 0; 6593 }else 6594 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ 6595 i++; 6596 zRecoveryDb = azArg[i]; 6597 }else 6598 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ 6599 i++; 6600 zLostAndFound = azArg[i]; 6601 } 6602 else{ 6603 raw_printf(stderr, "unexpected option: %s\n", azArg[i]); 6604 raw_printf(stderr, "options are:\n"); 6605 raw_printf(stderr, " --freelist-corrupt\n"); 6606 raw_printf(stderr, " --recovery-db DATABASE\n"); 6607 raw_printf(stderr, " --lost-and-found TABLE-NAME\n"); 6608 return 1; 6609 } 6610 } 6611 6612 shellExecPrintf(pState->db, &rc, 6613 /* Attach an in-memory database named 'recovery'. Create an indexed 6614 ** cache of the sqlite_dbptr virtual table. */ 6615 "PRAGMA writable_schema = on;" 6616 "ATTACH %Q AS recovery;" 6617 "DROP TABLE IF EXISTS recovery.dbptr;" 6618 "DROP TABLE IF EXISTS recovery.freelist;" 6619 "DROP TABLE IF EXISTS recovery.map;" 6620 "DROP TABLE IF EXISTS recovery.schema;" 6621 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb 6622 ); 6623 6624 if( bFreelist ){ 6625 shellExec(pState->db, &rc, 6626 "WITH trunk(pgno) AS (" 6627 " SELECT shell_int32(" 6628 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x " 6629 " WHERE x>0" 6630 " UNION" 6631 " SELECT shell_int32(" 6632 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x " 6633 " FROM trunk WHERE x>0" 6634 ")," 6635 "freelist(data, n, freepgno) AS (" 6636 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno " 6637 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno" 6638 " UNION ALL" 6639 " SELECT data, n-1, shell_int32(data, 2+n) " 6640 " FROM freelist WHERE n>=0" 6641 ")" 6642 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;" 6643 ); 6644 } 6645 6646 /* If this is an auto-vacuum database, add all pointer-map pages to 6647 ** the freelist table. Do this regardless of whether or not 6648 ** --freelist-corrupt was specified. */ 6649 shellExec(pState->db, &rc, 6650 "WITH ptrmap(pgno) AS (" 6651 " SELECT 2 WHERE shell_int32(" 6652 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13" 6653 " )" 6654 " UNION ALL " 6655 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp " 6656 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)" 6657 ")" 6658 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap" 6659 ); 6660 6661 shellExec(pState->db, &rc, 6662 "CREATE TABLE recovery.dbptr(" 6663 " pgno, child, PRIMARY KEY(child, pgno)" 6664 ") WITHOUT ROWID;" 6665 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) " 6666 " SELECT * FROM sqlite_dbptr" 6667 " WHERE pgno NOT IN freelist AND child NOT IN freelist;" 6668 6669 /* Delete any pointer to page 1. This ensures that page 1 is considered 6670 ** a root page, regardless of how corrupt the db is. */ 6671 "DELETE FROM recovery.dbptr WHERE child = 1;" 6672 6673 /* Delete all pointers to any pages that have more than one pointer 6674 ** to them. Such pages will be treated as root pages when recovering 6675 ** data. */ 6676 "DELETE FROM recovery.dbptr WHERE child IN (" 6677 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1" 6678 ");" 6679 6680 /* Create the "map" table that will (eventually) contain instructions 6681 ** for dealing with each page in the db that contains one or more 6682 ** records. */ 6683 "CREATE TABLE recovery.map(" 6684 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT" 6685 ");" 6686 6687 /* Populate table [map]. If there are circular loops of pages in the 6688 ** database, the following adds all pages in such a loop to the map 6689 ** as individual root pages. This could be handled better. */ 6690 "WITH pages(i, maxlen) AS (" 6691 " SELECT page_count, (" 6692 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count" 6693 " ) FROM pragma_page_count WHERE page_count>0" 6694 " UNION ALL" 6695 " SELECT i-1, (" 6696 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1" 6697 " ) FROM pages WHERE i>=2" 6698 ")" 6699 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) " 6700 " SELECT i, maxlen, NULL, (" 6701 " WITH p(orig, pgno, parent) AS (" 6702 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)" 6703 " UNION " 6704 " SELECT i, p.parent, " 6705 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p" 6706 " )" 6707 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)" 6708 ") " 6709 "FROM pages WHERE maxlen > 0 AND i NOT IN freelist;" 6710 "UPDATE recovery.map AS o SET intkey = (" 6711 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno" 6712 ");" 6713 6714 /* Extract data from page 1 and any linked pages into table 6715 ** recovery.schema. With the same schema as an sqlite_master table. */ 6716 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);" 6717 "INSERT INTO recovery.schema SELECT " 6718 " max(CASE WHEN field=0 THEN value ELSE NULL END)," 6719 " max(CASE WHEN field=1 THEN value ELSE NULL END)," 6720 " max(CASE WHEN field=2 THEN value ELSE NULL END)," 6721 " max(CASE WHEN field=3 THEN value ELSE NULL END)," 6722 " max(CASE WHEN field=4 THEN value ELSE NULL END)" 6723 "FROM sqlite_dbdata WHERE pgno IN (" 6724 " SELECT pgno FROM recovery.map WHERE root=1" 6725 ")" 6726 "GROUP BY pgno, cell;" 6727 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);" 6728 ); 6729 6730 /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 6731 ** CREATE TABLE statements that extracted from the existing schema. */ 6732 if( rc==SQLITE_OK ){ 6733 sqlite3_stmt *pStmt = 0; 6734 /* ".recover" might output content in an order which causes immediate 6735 ** foreign key constraints to be violated. So disable foreign-key 6736 ** constraint enforcement to prevent problems when running the output 6737 ** script. */ 6738 raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n"); 6739 raw_printf(pState->out, "BEGIN;\n"); 6740 raw_printf(pState->out, "PRAGMA writable_schema = on;\n"); 6741 shellPrepare(pState->db, &rc, 6742 "SELECT sql FROM recovery.schema " 6743 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt 6744 ); 6745 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6746 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0); 6747 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 6748 &zCreateTable[12] 6749 ); 6750 } 6751 shellFinalize(&rc, pStmt); 6752 } 6753 6754 /* Figure out if an orphan table will be required. And if so, how many 6755 ** user columns it should contain */ 6756 shellPrepare(pState->db, &rc, 6757 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1" 6758 , &pLoop 6759 ); 6760 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 6761 nOrphan = sqlite3_column_int(pLoop, 0); 6762 } 6763 shellFinalize(&rc, pLoop); 6764 pLoop = 0; 6765 6766 shellPrepare(pState->db, &rc, 6767 "SELECT pgno FROM recovery.map WHERE root=?", &pPages 6768 ); 6769 shellPrepare(pState->db, &rc, 6770 "SELECT max(field), group_concat(shell_escape_crnl(quote(value)), ', ')" 6771 ", min(field) " 6772 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?" 6773 "GROUP BY cell", &pCells 6774 ); 6775 6776 /* Loop through each root page. */ 6777 shellPrepare(pState->db, &rc, 6778 "SELECT root, intkey, max(maxlen) FROM recovery.map" 6779 " WHERE root>1 GROUP BY root, intkey ORDER BY root=(" 6780 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'" 6781 ")", &pLoop 6782 ); 6783 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 6784 int iRoot = sqlite3_column_int(pLoop, 0); 6785 int bIntkey = sqlite3_column_int(pLoop, 1); 6786 int nCol = sqlite3_column_int(pLoop, 2); 6787 int bNoop = 0; 6788 RecoverTable *pTab; 6789 6790 assert( bIntkey==0 || bIntkey==1 ); 6791 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop); 6792 if( bNoop || rc ) continue; 6793 if( pTab==0 ){ 6794 if( pOrphan==0 ){ 6795 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 6796 } 6797 pTab = pOrphan; 6798 if( pTab==0 ) break; 6799 } 6800 6801 if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){ 6802 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n"); 6803 } 6804 sqlite3_bind_int(pPages, 1, iRoot); 6805 sqlite3_bind_int(pCells, 2, pTab->iPk); 6806 6807 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){ 6808 int iPgno = sqlite3_column_int(pPages, 0); 6809 sqlite3_bind_int(pCells, 1, iPgno); 6810 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){ 6811 int nField = sqlite3_column_int(pCells, 0); 6812 int iMin = sqlite3_column_int(pCells, 2); 6813 const char *zVal = (const char*)sqlite3_column_text(pCells, 1); 6814 6815 RecoverTable *pTab2 = pTab; 6816 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){ 6817 if( pOrphan==0 ){ 6818 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 6819 } 6820 pTab2 = pOrphan; 6821 if( pTab2==0 ) break; 6822 } 6823 6824 nField = nField+1; 6825 if( pTab2==pOrphan ){ 6826 raw_printf(pState->out, 6827 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n", 6828 pTab2->zQuoted, iRoot, iPgno, nField, 6829 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField] 6830 ); 6831 }else{ 6832 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 6833 pTab2->zQuoted, pTab2->azlCol[nField], zVal 6834 ); 6835 } 6836 } 6837 shellReset(&rc, pCells); 6838 } 6839 shellReset(&rc, pPages); 6840 if( pTab!=pOrphan ) recoverFreeTable(pTab); 6841 } 6842 shellFinalize(&rc, pLoop); 6843 shellFinalize(&rc, pPages); 6844 shellFinalize(&rc, pCells); 6845 recoverFreeTable(pOrphan); 6846 6847 /* The rest of the schema */ 6848 if( rc==SQLITE_OK ){ 6849 sqlite3_stmt *pStmt = 0; 6850 shellPrepare(pState->db, &rc, 6851 "SELECT sql, name FROM recovery.schema " 6852 "WHERE sql NOT LIKE 'create table%'", &pStmt 6853 ); 6854 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6855 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0); 6856 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){ 6857 const char *zName = (const char*)sqlite3_column_text(pStmt, 1); 6858 char *zPrint = shellMPrintf(&rc, 6859 "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)", 6860 zName, zName, zSql 6861 ); 6862 raw_printf(pState->out, "%s;\n", zPrint); 6863 sqlite3_free(zPrint); 6864 }else{ 6865 raw_printf(pState->out, "%s;\n", zSql); 6866 } 6867 } 6868 shellFinalize(&rc, pStmt); 6869 } 6870 6871 if( rc==SQLITE_OK ){ 6872 raw_printf(pState->out, "PRAGMA writable_schema = off;\n"); 6873 raw_printf(pState->out, "COMMIT;\n"); 6874 } 6875 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0); 6876 return rc; 6877} 6878#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 6879 6880 6881/* 6882** If an input line begins with "." then invoke this routine to 6883** process that line. 6884** 6885** Return 1 on error, 2 to exit, and 0 otherwise. 6886*/ 6887static int do_meta_command(char *zLine, ShellState *p){ 6888 int h = 1; 6889 int nArg = 0; 6890 int n, c; 6891 int rc = 0; 6892 char *azArg[50]; 6893 6894#ifndef SQLITE_OMIT_VIRTUALTABLE 6895 if( p->expert.pExpert ){ 6896 expertFinish(p, 1, 0); 6897 } 6898#endif 6899 6900 /* Parse the input line into tokens. 6901 */ 6902 while( zLine[h] && nArg<ArraySize(azArg) ){ 6903 while( IsSpace(zLine[h]) ){ h++; } 6904 if( zLine[h]==0 ) break; 6905 if( zLine[h]=='\'' || zLine[h]=='"' ){ 6906 int delim = zLine[h++]; 6907 azArg[nArg++] = &zLine[h]; 6908 while( zLine[h] && zLine[h]!=delim ){ 6909 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; 6910 h++; 6911 } 6912 if( zLine[h]==delim ){ 6913 zLine[h++] = 0; 6914 } 6915 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); 6916 }else{ 6917 azArg[nArg++] = &zLine[h]; 6918 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } 6919 if( zLine[h] ) zLine[h++] = 0; 6920 resolve_backslashes(azArg[nArg-1]); 6921 } 6922 } 6923 6924 /* Process the input line. 6925 */ 6926 if( nArg==0 ) return 0; /* no tokens, no error */ 6927 n = strlen30(azArg[0]); 6928 c = azArg[0][0]; 6929 clearTempFile(p); 6930 6931#ifndef SQLITE_OMIT_AUTHORIZATION 6932 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){ 6933 if( nArg!=2 ){ 6934 raw_printf(stderr, "Usage: .auth ON|OFF\n"); 6935 rc = 1; 6936 goto meta_command_exit; 6937 } 6938 open_db(p, 0); 6939 if( booleanValue(azArg[1]) ){ 6940 sqlite3_set_authorizer(p->db, shellAuth, p); 6941 }else{ 6942 sqlite3_set_authorizer(p->db, 0, 0); 6943 } 6944 }else 6945#endif 6946 6947#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 6948 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){ 6949 open_db(p, 0); 6950 rc = arDotCommand(p, 0, azArg, nArg); 6951 }else 6952#endif 6953 6954 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) 6955 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) 6956 ){ 6957 const char *zDestFile = 0; 6958 const char *zDb = 0; 6959 sqlite3 *pDest; 6960 sqlite3_backup *pBackup; 6961 int j; 6962 int bAsync = 0; 6963 const char *zVfs = 0; 6964 for(j=1; j<nArg; j++){ 6965 const char *z = azArg[j]; 6966 if( z[0]=='-' ){ 6967 if( z[1]=='-' ) z++; 6968 if( strcmp(z, "-append")==0 ){ 6969 zVfs = "apndvfs"; 6970 }else 6971 if( strcmp(z, "-async")==0 ){ 6972 bAsync = 1; 6973 }else 6974 { 6975 utf8_printf(stderr, "unknown option: %s\n", azArg[j]); 6976 return 1; 6977 } 6978 }else if( zDestFile==0 ){ 6979 zDestFile = azArg[j]; 6980 }else if( zDb==0 ){ 6981 zDb = zDestFile; 6982 zDestFile = azArg[j]; 6983 }else{ 6984 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n"); 6985 return 1; 6986 } 6987 } 6988 if( zDestFile==0 ){ 6989 raw_printf(stderr, "missing FILENAME argument on .backup\n"); 6990 return 1; 6991 } 6992 if( zDb==0 ) zDb = "main"; 6993 rc = sqlite3_open_v2(zDestFile, &pDest, 6994 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs); 6995 if( rc!=SQLITE_OK ){ 6996 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); 6997 close_db(pDest); 6998 return 1; 6999 } 7000 if( bAsync ){ 7001 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;", 7002 0, 0, 0); 7003 } 7004 open_db(p, 0); 7005 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); 7006 if( pBackup==0 ){ 7007 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7008 close_db(pDest); 7009 return 1; 7010 } 7011 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} 7012 sqlite3_backup_finish(pBackup); 7013 if( rc==SQLITE_DONE ){ 7014 rc = 0; 7015 }else{ 7016 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7017 rc = 1; 7018 } 7019 close_db(pDest); 7020 }else 7021 7022 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ 7023 if( nArg==2 ){ 7024 bail_on_error = booleanValue(azArg[1]); 7025 }else{ 7026 raw_printf(stderr, "Usage: .bail on|off\n"); 7027 rc = 1; 7028 } 7029 }else 7030 7031 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ 7032 if( nArg==2 ){ 7033 if( booleanValue(azArg[1]) ){ 7034 setBinaryMode(p->out, 1); 7035 }else{ 7036 setTextMode(p->out, 1); 7037 } 7038 }else{ 7039 raw_printf(stderr, "Usage: .binary on|off\n"); 7040 rc = 1; 7041 } 7042 }else 7043 7044 if( c=='c' && strcmp(azArg[0],"cd")==0 ){ 7045 if( nArg==2 ){ 7046#if defined(_WIN32) || defined(WIN32) 7047 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); 7048 rc = !SetCurrentDirectoryW(z); 7049 sqlite3_free(z); 7050#else 7051 rc = chdir(azArg[1]); 7052#endif 7053 if( rc ){ 7054 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); 7055 rc = 1; 7056 } 7057 }else{ 7058 raw_printf(stderr, "Usage: .cd DIRECTORY\n"); 7059 rc = 1; 7060 } 7061 }else 7062 7063 /* The undocumented ".breakpoint" command causes a call to the no-op 7064 ** routine named test_breakpoint(). 7065 */ 7066 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ 7067 test_breakpoint(); 7068 }else 7069 7070 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ 7071 if( nArg==2 ){ 7072 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); 7073 }else{ 7074 raw_printf(stderr, "Usage: .changes on|off\n"); 7075 rc = 1; 7076 } 7077 }else 7078 7079 /* Cancel output redirection, if it is currently set (by .testcase) 7080 ** Then read the content of the testcase-out.txt file and compare against 7081 ** azArg[1]. If there are differences, report an error and exit. 7082 */ 7083 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){ 7084 char *zRes = 0; 7085 output_reset(p); 7086 if( nArg!=2 ){ 7087 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); 7088 rc = 2; 7089 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ 7090 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); 7091 rc = 2; 7092 }else if( testcase_glob(azArg[1],zRes)==0 ){ 7093 utf8_printf(stderr, 7094 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", 7095 p->zTestcase, azArg[1], zRes); 7096 rc = 1; 7097 }else{ 7098 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); 7099 p->nCheck++; 7100 } 7101 sqlite3_free(zRes); 7102 }else 7103 7104 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ 7105 if( nArg==2 ){ 7106 tryToClone(p, azArg[1]); 7107 }else{ 7108 raw_printf(stderr, "Usage: .clone FILENAME\n"); 7109 rc = 1; 7110 } 7111 }else 7112 7113 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ 7114 ShellState data; 7115 char *zErrMsg = 0; 7116 open_db(p, 0); 7117 memcpy(&data, p, sizeof(data)); 7118 data.showHeader = 0; 7119 data.cMode = data.mode = MODE_List; 7120 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": "); 7121 data.cnt = 0; 7122 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list", 7123 callback, &data, &zErrMsg); 7124 if( zErrMsg ){ 7125 utf8_printf(stderr,"Error: %s\n", zErrMsg); 7126 sqlite3_free(zErrMsg); 7127 rc = 1; 7128 } 7129 }else 7130 7131 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){ 7132 static const struct DbConfigChoices { 7133 const char *zName; 7134 int op; 7135 } aDbConfig[] = { 7136 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, 7137 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, 7138 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, 7139 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, 7140 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, 7141 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, 7142 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, 7143 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, 7144 { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, 7145 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, 7146 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, 7147 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, 7148 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, 7149 }; 7150 int ii, v; 7151 open_db(p, 0); 7152 for(ii=0; ii<ArraySize(aDbConfig); ii++){ 7153 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; 7154 if( nArg>=3 ){ 7155 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); 7156 } 7157 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); 7158 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off"); 7159 if( nArg>1 ) break; 7160 } 7161 if( nArg>1 && ii==ArraySize(aDbConfig) ){ 7162 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]); 7163 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n"); 7164 } 7165 }else 7166 7167 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){ 7168 rc = shell_dbinfo_command(p, nArg, azArg); 7169 }else 7170 7171#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 7172 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){ 7173 open_db(p, 0); 7174 rc = recoverDatabaseCmd(p, nArg, azArg); 7175 }else 7176#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 7177 7178 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ 7179 const char *zLike = 0; 7180 int i; 7181 int savedShowHeader = p->showHeader; 7182 int savedShellFlags = p->shellFlgs; 7183 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo); 7184 for(i=1; i<nArg; i++){ 7185 if( azArg[i][0]=='-' ){ 7186 const char *z = azArg[i]+1; 7187 if( z[0]=='-' ) z++; 7188 if( strcmp(z,"preserve-rowids")==0 ){ 7189#ifdef SQLITE_OMIT_VIRTUALTABLE 7190 raw_printf(stderr, "The --preserve-rowids option is not compatible" 7191 " with SQLITE_OMIT_VIRTUALTABLE\n"); 7192 rc = 1; 7193 goto meta_command_exit; 7194#else 7195 ShellSetFlag(p, SHFLG_PreserveRowid); 7196#endif 7197 }else 7198 if( strcmp(z,"newlines")==0 ){ 7199 ShellSetFlag(p, SHFLG_Newlines); 7200 }else 7201 { 7202 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]); 7203 rc = 1; 7204 goto meta_command_exit; 7205 } 7206 }else if( zLike ){ 7207 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? " 7208 "?--newlines? ?LIKE-PATTERN?\n"); 7209 rc = 1; 7210 goto meta_command_exit; 7211 }else{ 7212 zLike = azArg[i]; 7213 } 7214 } 7215 7216 open_db(p, 0); 7217 7218 /* When playing back a "dump", the content might appear in an order 7219 ** which causes immediate foreign key constraints to be violated. 7220 ** So disable foreign-key constraint enforcement to prevent problems. */ 7221 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); 7222 raw_printf(p->out, "BEGIN TRANSACTION;\n"); 7223 p->writableSchema = 0; 7224 p->showHeader = 0; 7225 /* Set writable_schema=ON since doing so forces SQLite to initialize 7226 ** as much of the schema as it can even if the sqlite_master table is 7227 ** corrupt. */ 7228 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); 7229 p->nErr = 0; 7230 if( zLike==0 ){ 7231 run_schema_dump_query(p, 7232 "SELECT name, type, sql FROM sqlite_master " 7233 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" 7234 ); 7235 run_schema_dump_query(p, 7236 "SELECT name, type, sql FROM sqlite_master " 7237 "WHERE name=='sqlite_sequence'" 7238 ); 7239 run_table_dump_query(p, 7240 "SELECT sql FROM sqlite_master " 7241 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 7242 ); 7243 }else{ 7244 char *zSql; 7245 zSql = sqlite3_mprintf( 7246 "SELECT name, type, sql FROM sqlite_master " 7247 "WHERE tbl_name LIKE %Q AND type=='table'" 7248 " AND sql NOT NULL", zLike); 7249 run_schema_dump_query(p,zSql); 7250 sqlite3_free(zSql); 7251 zSql = sqlite3_mprintf( 7252 "SELECT sql FROM sqlite_master " 7253 "WHERE sql NOT NULL" 7254 " AND type IN ('index','trigger','view')" 7255 " AND tbl_name LIKE %Q", zLike); 7256 run_table_dump_query(p, zSql, 0); 7257 sqlite3_free(zSql); 7258 } 7259 if( p->writableSchema ){ 7260 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); 7261 p->writableSchema = 0; 7262 } 7263 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 7264 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); 7265 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); 7266 p->showHeader = savedShowHeader; 7267 p->shellFlgs = savedShellFlags; 7268 }else 7269 7270 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ 7271 if( nArg==2 ){ 7272 setOrClearFlag(p, SHFLG_Echo, azArg[1]); 7273 }else{ 7274 raw_printf(stderr, "Usage: .echo on|off\n"); 7275 rc = 1; 7276 } 7277 }else 7278 7279 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ 7280 if( nArg==2 ){ 7281 p->autoEQPtest = 0; 7282 if( p->autoEQPtrace ){ 7283 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); 7284 p->autoEQPtrace = 0; 7285 } 7286 if( strcmp(azArg[1],"full")==0 ){ 7287 p->autoEQP = AUTOEQP_full; 7288 }else if( strcmp(azArg[1],"trigger")==0 ){ 7289 p->autoEQP = AUTOEQP_trigger; 7290#ifdef SQLITE_DEBUG 7291 }else if( strcmp(azArg[1],"test")==0 ){ 7292 p->autoEQP = AUTOEQP_on; 7293 p->autoEQPtest = 1; 7294 }else if( strcmp(azArg[1],"trace")==0 ){ 7295 p->autoEQP = AUTOEQP_full; 7296 p->autoEQPtrace = 1; 7297 open_db(p, 0); 7298 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0); 7299 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); 7300#endif 7301 }else{ 7302 p->autoEQP = (u8)booleanValue(azArg[1]); 7303 } 7304 }else{ 7305 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n"); 7306 rc = 1; 7307 } 7308 }else 7309 7310 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ 7311 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); 7312 rc = 2; 7313 }else 7314 7315 /* The ".explain" command is automatic now. It is largely pointless. It 7316 ** retained purely for backwards compatibility */ 7317 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ 7318 int val = 1; 7319 if( nArg>=2 ){ 7320 if( strcmp(azArg[1],"auto")==0 ){ 7321 val = 99; 7322 }else{ 7323 val = booleanValue(azArg[1]); 7324 } 7325 } 7326 if( val==1 && p->mode!=MODE_Explain ){ 7327 p->normalMode = p->mode; 7328 p->mode = MODE_Explain; 7329 p->autoExplain = 0; 7330 }else if( val==0 ){ 7331 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 7332 p->autoExplain = 0; 7333 }else if( val==99 ){ 7334 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 7335 p->autoExplain = 1; 7336 } 7337 }else 7338 7339#ifndef SQLITE_OMIT_VIRTUALTABLE 7340 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){ 7341 open_db(p, 0); 7342 expertDotCommand(p, azArg, nArg); 7343 }else 7344#endif 7345 7346 if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){ 7347 static const struct { 7348 const char *zCtrlName; /* Name of a test-control option */ 7349 int ctrlCode; /* Integer code for that option */ 7350 const char *zUsage; /* Usage notes */ 7351 } aCtrl[] = { 7352 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" }, 7353 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" }, 7354 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/ 7355 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" }, 7356 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" }, 7357 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/ 7358 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" }, 7359 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" }, 7360 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" }, 7361 }; 7362 int filectrl = -1; 7363 int iCtrl = -1; 7364 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */ 7365 int isOk = 0; /* 0: usage 1: %lld 2: no-result */ 7366 int n2, i; 7367 const char *zCmd = 0; 7368 7369 open_db(p, 0); 7370 zCmd = nArg>=2 ? azArg[1] : "help"; 7371 7372 /* The argument can optionally begin with "-" or "--" */ 7373 if( zCmd[0]=='-' && zCmd[1] ){ 7374 zCmd++; 7375 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 7376 } 7377 7378 /* --help lists all file-controls */ 7379 if( strcmp(zCmd,"help")==0 ){ 7380 utf8_printf(p->out, "Available file-controls:\n"); 7381 for(i=0; i<ArraySize(aCtrl); i++){ 7382 utf8_printf(p->out, " .filectrl %s %s\n", 7383 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 7384 } 7385 rc = 1; 7386 goto meta_command_exit; 7387 } 7388 7389 /* convert filectrl text option to value. allow any unique prefix 7390 ** of the option name, or a numerical value. */ 7391 n2 = strlen30(zCmd); 7392 for(i=0; i<ArraySize(aCtrl); i++){ 7393 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 7394 if( filectrl<0 ){ 7395 filectrl = aCtrl[i].ctrlCode; 7396 iCtrl = i; 7397 }else{ 7398 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n" 7399 "Use \".filectrl --help\" for help\n", zCmd); 7400 rc = 1; 7401 goto meta_command_exit; 7402 } 7403 } 7404 } 7405 if( filectrl<0 ){ 7406 utf8_printf(stderr,"Error: unknown file-control: %s\n" 7407 "Use \".filectrl --help\" for help\n", zCmd); 7408 }else{ 7409 switch(filectrl){ 7410 case SQLITE_FCNTL_SIZE_LIMIT: { 7411 if( nArg!=2 && nArg!=3 ) break; 7412 iRes = nArg==3 ? integerValue(azArg[2]) : -1; 7413 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_SIZE_LIMIT, &iRes); 7414 isOk = 1; 7415 break; 7416 } 7417 case SQLITE_FCNTL_LOCK_TIMEOUT: 7418 case SQLITE_FCNTL_CHUNK_SIZE: { 7419 int x; 7420 if( nArg!=3 ) break; 7421 x = (int)integerValue(azArg[2]); 7422 sqlite3_file_control(p->db, 0, filectrl, &x); 7423 isOk = 2; 7424 break; 7425 } 7426 case SQLITE_FCNTL_PERSIST_WAL: 7427 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { 7428 int x; 7429 if( nArg!=2 && nArg!=3 ) break; 7430 x = nArg==3 ? booleanValue(azArg[2]) : -1; 7431 sqlite3_file_control(p->db, 0, filectrl, &x); 7432 iRes = x; 7433 isOk = 1; 7434 break; 7435 } 7436 case SQLITE_FCNTL_HAS_MOVED: { 7437 int x; 7438 if( nArg!=2 ) break; 7439 sqlite3_file_control(p->db, 0, filectrl, &x); 7440 iRes = x; 7441 isOk = 1; 7442 break; 7443 } 7444 case SQLITE_FCNTL_TEMPFILENAME: { 7445 char *z = 0; 7446 if( nArg!=2 ) break; 7447 sqlite3_file_control(p->db, 0, filectrl, &z); 7448 if( z ){ 7449 utf8_printf(p->out, "%s\n", z); 7450 sqlite3_free(z); 7451 } 7452 isOk = 2; 7453 break; 7454 } 7455 } 7456 } 7457 if( isOk==0 && iCtrl>=0 ){ 7458 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 7459 rc = 1; 7460 }else if( isOk==1 ){ 7461 char zBuf[100]; 7462 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes); 7463 raw_printf(p->out, "%s\n", zBuf); 7464 } 7465 }else 7466 7467 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ 7468 ShellState data; 7469 char *zErrMsg = 0; 7470 int doStats = 0; 7471 memcpy(&data, p, sizeof(data)); 7472 data.showHeader = 0; 7473 data.cMode = data.mode = MODE_Semi; 7474 if( nArg==2 && optionMatch(azArg[1], "indent") ){ 7475 data.cMode = data.mode = MODE_Pretty; 7476 nArg = 1; 7477 } 7478 if( nArg!=1 ){ 7479 raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); 7480 rc = 1; 7481 goto meta_command_exit; 7482 } 7483 open_db(p, 0); 7484 rc = sqlite3_exec(p->db, 7485 "SELECT sql FROM" 7486 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" 7487 " FROM sqlite_master UNION ALL" 7488 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " 7489 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " 7490 "ORDER BY rowid", 7491 callback, &data, &zErrMsg 7492 ); 7493 if( rc==SQLITE_OK ){ 7494 sqlite3_stmt *pStmt; 7495 rc = sqlite3_prepare_v2(p->db, 7496 "SELECT rowid FROM sqlite_master" 7497 " WHERE name GLOB 'sqlite_stat[134]'", 7498 -1, &pStmt, 0); 7499 doStats = sqlite3_step(pStmt)==SQLITE_ROW; 7500 sqlite3_finalize(pStmt); 7501 } 7502 if( doStats==0 ){ 7503 raw_printf(p->out, "/* No STAT tables available */\n"); 7504 }else{ 7505 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 7506 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'", 7507 callback, &data, &zErrMsg); 7508 data.cMode = data.mode = MODE_Insert; 7509 data.zDestTable = "sqlite_stat1"; 7510 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg); 7511 data.zDestTable = "sqlite_stat4"; 7512 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg); 7513 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 7514 } 7515 }else 7516 7517 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ 7518 if( nArg==2 ){ 7519 p->showHeader = booleanValue(azArg[1]); 7520 }else{ 7521 raw_printf(stderr, "Usage: .headers on|off\n"); 7522 rc = 1; 7523 } 7524 }else 7525 7526 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ 7527 if( nArg>=2 ){ 7528 n = showHelp(p->out, azArg[1]); 7529 if( n==0 ){ 7530 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]); 7531 } 7532 }else{ 7533 showHelp(p->out, 0); 7534 } 7535 }else 7536 7537 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ 7538 char *zTable; /* Insert data into this table */ 7539 char *zFile; /* Name of file to extra content from */ 7540 sqlite3_stmt *pStmt = NULL; /* A statement */ 7541 int nCol; /* Number of columns in the table */ 7542 int nByte; /* Number of bytes in an SQL string */ 7543 int i, j; /* Loop counters */ 7544 int needCommit; /* True to COMMIT or ROLLBACK at end */ 7545 int nSep; /* Number of bytes in p->colSeparator[] */ 7546 char *zSql; /* An SQL statement */ 7547 ImportCtx sCtx; /* Reader context */ 7548 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ 7549 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */ 7550 7551 if( nArg!=3 ){ 7552 raw_printf(stderr, "Usage: .import FILE TABLE\n"); 7553 goto meta_command_exit; 7554 } 7555 zFile = azArg[1]; 7556 zTable = azArg[2]; 7557 seenInterrupt = 0; 7558 memset(&sCtx, 0, sizeof(sCtx)); 7559 open_db(p, 0); 7560 nSep = strlen30(p->colSeparator); 7561 if( nSep==0 ){ 7562 raw_printf(stderr, 7563 "Error: non-null column separator required for import\n"); 7564 return 1; 7565 } 7566 if( nSep>1 ){ 7567 raw_printf(stderr, "Error: multi-character column separators not allowed" 7568 " for import\n"); 7569 return 1; 7570 } 7571 nSep = strlen30(p->rowSeparator); 7572 if( nSep==0 ){ 7573 raw_printf(stderr, "Error: non-null row separator required for import\n"); 7574 return 1; 7575 } 7576 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){ 7577 /* When importing CSV (only), if the row separator is set to the 7578 ** default output row separator, change it to the default input 7579 ** row separator. This avoids having to maintain different input 7580 ** and output row separators. */ 7581 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7582 nSep = strlen30(p->rowSeparator); 7583 } 7584 if( nSep>1 ){ 7585 raw_printf(stderr, "Error: multi-character row separators not allowed" 7586 " for import\n"); 7587 return 1; 7588 } 7589 sCtx.zFile = zFile; 7590 sCtx.nLine = 1; 7591 if( sCtx.zFile[0]=='|' ){ 7592#ifdef SQLITE_OMIT_POPEN 7593 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 7594 return 1; 7595#else 7596 sCtx.in = popen(sCtx.zFile+1, "r"); 7597 sCtx.zFile = "<pipe>"; 7598 xCloser = pclose; 7599#endif 7600 }else{ 7601 sCtx.in = fopen(sCtx.zFile, "rb"); 7602 xCloser = fclose; 7603 } 7604 if( p->mode==MODE_Ascii ){ 7605 xRead = ascii_read_one_field; 7606 }else{ 7607 xRead = csv_read_one_field; 7608 } 7609 if( sCtx.in==0 ){ 7610 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 7611 return 1; 7612 } 7613 sCtx.cColSep = p->colSeparator[0]; 7614 sCtx.cRowSep = p->rowSeparator[0]; 7615 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); 7616 if( zSql==0 ){ 7617 xCloser(sCtx.in); 7618 shell_out_of_memory(); 7619 } 7620 nByte = strlen30(zSql); 7621 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7622 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ 7623 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ 7624 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); 7625 char cSep = '('; 7626 while( xRead(&sCtx) ){ 7627 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); 7628 cSep = ','; 7629 if( sCtx.cTerm!=sCtx.cColSep ) break; 7630 } 7631 if( cSep=='(' ){ 7632 sqlite3_free(zCreate); 7633 sqlite3_free(sCtx.z); 7634 xCloser(sCtx.in); 7635 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); 7636 return 1; 7637 } 7638 zCreate = sqlite3_mprintf("%z\n)", zCreate); 7639 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); 7640 sqlite3_free(zCreate); 7641 if( rc ){ 7642 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, 7643 sqlite3_errmsg(p->db)); 7644 sqlite3_free(sCtx.z); 7645 xCloser(sCtx.in); 7646 return 1; 7647 } 7648 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7649 } 7650 sqlite3_free(zSql); 7651 if( rc ){ 7652 if (pStmt) sqlite3_finalize(pStmt); 7653 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); 7654 xCloser(sCtx.in); 7655 return 1; 7656 } 7657 nCol = sqlite3_column_count(pStmt); 7658 sqlite3_finalize(pStmt); 7659 pStmt = 0; 7660 if( nCol==0 ) return 0; /* no columns, no error */ 7661 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); 7662 if( zSql==0 ){ 7663 xCloser(sCtx.in); 7664 shell_out_of_memory(); 7665 } 7666 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); 7667 j = strlen30(zSql); 7668 for(i=1; i<nCol; i++){ 7669 zSql[j++] = ','; 7670 zSql[j++] = '?'; 7671 } 7672 zSql[j++] = ')'; 7673 zSql[j] = 0; 7674 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7675 sqlite3_free(zSql); 7676 if( rc ){ 7677 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7678 if (pStmt) sqlite3_finalize(pStmt); 7679 xCloser(sCtx.in); 7680 return 1; 7681 } 7682 needCommit = sqlite3_get_autocommit(p->db); 7683 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); 7684 do{ 7685 int startLine = sCtx.nLine; 7686 for(i=0; i<nCol; i++){ 7687 char *z = xRead(&sCtx); 7688 /* 7689 ** Did we reach end-of-file before finding any columns? 7690 ** If so, stop instead of NULL filling the remaining columns. 7691 */ 7692 if( z==0 && i==0 ) break; 7693 /* 7694 ** Did we reach end-of-file OR end-of-line before finding any 7695 ** columns in ASCII mode? If so, stop instead of NULL filling 7696 ** the remaining columns. 7697 */ 7698 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; 7699 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); 7700 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ 7701 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 7702 "filling the rest with NULL\n", 7703 sCtx.zFile, startLine, nCol, i+1); 7704 i += 2; 7705 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } 7706 } 7707 } 7708 if( sCtx.cTerm==sCtx.cColSep ){ 7709 do{ 7710 xRead(&sCtx); 7711 i++; 7712 }while( sCtx.cTerm==sCtx.cColSep ); 7713 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 7714 "extras ignored\n", 7715 sCtx.zFile, startLine, nCol, i); 7716 } 7717 if( i>=nCol ){ 7718 sqlite3_step(pStmt); 7719 rc = sqlite3_reset(pStmt); 7720 if( rc!=SQLITE_OK ){ 7721 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, 7722 startLine, sqlite3_errmsg(p->db)); 7723 } 7724 } 7725 }while( sCtx.cTerm!=EOF ); 7726 7727 xCloser(sCtx.in); 7728 sqlite3_free(sCtx.z); 7729 sqlite3_finalize(pStmt); 7730 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); 7731 }else 7732 7733#ifndef SQLITE_UNTESTABLE 7734 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){ 7735 char *zSql; 7736 char *zCollist = 0; 7737 sqlite3_stmt *pStmt; 7738 int tnum = 0; 7739 int i; 7740 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ 7741 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n" 7742 " .imposter off\n"); 7743 rc = 1; 7744 goto meta_command_exit; 7745 } 7746 open_db(p, 0); 7747 if( nArg==2 ){ 7748 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); 7749 goto meta_command_exit; 7750 } 7751 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master" 7752 " WHERE name='%q' AND type='index'", azArg[1]); 7753 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7754 sqlite3_free(zSql); 7755 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 7756 tnum = sqlite3_column_int(pStmt, 0); 7757 } 7758 sqlite3_finalize(pStmt); 7759 if( tnum==0 ){ 7760 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); 7761 rc = 1; 7762 goto meta_command_exit; 7763 } 7764 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); 7765 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7766 sqlite3_free(zSql); 7767 i = 0; 7768 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7769 char zLabel[20]; 7770 const char *zCol = (const char*)sqlite3_column_text(pStmt,2); 7771 i++; 7772 if( zCol==0 ){ 7773 if( sqlite3_column_int(pStmt,1)==-1 ){ 7774 zCol = "_ROWID_"; 7775 }else{ 7776 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); 7777 zCol = zLabel; 7778 } 7779 } 7780 if( zCollist==0 ){ 7781 zCollist = sqlite3_mprintf("\"%w\"", zCol); 7782 }else{ 7783 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); 7784 } 7785 } 7786 sqlite3_finalize(pStmt); 7787 zSql = sqlite3_mprintf( 7788 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID", 7789 azArg[2], zCollist, zCollist); 7790 sqlite3_free(zCollist); 7791 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); 7792 if( rc==SQLITE_OK ){ 7793 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); 7794 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); 7795 if( rc ){ 7796 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); 7797 }else{ 7798 utf8_printf(stdout, "%s;\n", zSql); 7799 raw_printf(stdout, 7800 "WARNING: writing to an imposter table will corrupt the index!\n" 7801 ); 7802 } 7803 }else{ 7804 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); 7805 rc = 1; 7806 } 7807 sqlite3_free(zSql); 7808 }else 7809#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ 7810 7811#ifdef SQLITE_ENABLE_IOTRACE 7812 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ 7813 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); 7814 if( iotrace && iotrace!=stdout ) fclose(iotrace); 7815 iotrace = 0; 7816 if( nArg<2 ){ 7817 sqlite3IoTrace = 0; 7818 }else if( strcmp(azArg[1], "-")==0 ){ 7819 sqlite3IoTrace = iotracePrintf; 7820 iotrace = stdout; 7821 }else{ 7822 iotrace = fopen(azArg[1], "w"); 7823 if( iotrace==0 ){ 7824 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 7825 sqlite3IoTrace = 0; 7826 rc = 1; 7827 }else{ 7828 sqlite3IoTrace = iotracePrintf; 7829 } 7830 } 7831 }else 7832#endif 7833 7834 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ 7835 static const struct { 7836 const char *zLimitName; /* Name of a limit */ 7837 int limitCode; /* Integer code for that limit */ 7838 } aLimit[] = { 7839 { "length", SQLITE_LIMIT_LENGTH }, 7840 { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, 7841 { "column", SQLITE_LIMIT_COLUMN }, 7842 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, 7843 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, 7844 { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, 7845 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, 7846 { "attached", SQLITE_LIMIT_ATTACHED }, 7847 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, 7848 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, 7849 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, 7850 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, 7851 }; 7852 int i, n2; 7853 open_db(p, 0); 7854 if( nArg==1 ){ 7855 for(i=0; i<ArraySize(aLimit); i++){ 7856 printf("%20s %d\n", aLimit[i].zLimitName, 7857 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); 7858 } 7859 }else if( nArg>3 ){ 7860 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); 7861 rc = 1; 7862 goto meta_command_exit; 7863 }else{ 7864 int iLimit = -1; 7865 n2 = strlen30(azArg[1]); 7866 for(i=0; i<ArraySize(aLimit); i++){ 7867 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ 7868 if( iLimit<0 ){ 7869 iLimit = i; 7870 }else{ 7871 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); 7872 rc = 1; 7873 goto meta_command_exit; 7874 } 7875 } 7876 } 7877 if( iLimit<0 ){ 7878 utf8_printf(stderr, "unknown limit: \"%s\"\n" 7879 "enter \".limits\" with no arguments for a list.\n", 7880 azArg[1]); 7881 rc = 1; 7882 goto meta_command_exit; 7883 } 7884 if( nArg==3 ){ 7885 sqlite3_limit(p->db, aLimit[iLimit].limitCode, 7886 (int)integerValue(azArg[2])); 7887 } 7888 printf("%20s %d\n", aLimit[iLimit].zLimitName, 7889 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); 7890 } 7891 }else 7892 7893 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){ 7894 open_db(p, 0); 7895 lintDotCommand(p, azArg, nArg); 7896 }else 7897 7898#ifndef SQLITE_OMIT_LOAD_EXTENSION 7899 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ 7900 const char *zFile, *zProc; 7901 char *zErrMsg = 0; 7902 if( nArg<2 ){ 7903 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); 7904 rc = 1; 7905 goto meta_command_exit; 7906 } 7907 zFile = azArg[1]; 7908 zProc = nArg>=3 ? azArg[2] : 0; 7909 open_db(p, 0); 7910 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); 7911 if( rc!=SQLITE_OK ){ 7912 utf8_printf(stderr, "Error: %s\n", zErrMsg); 7913 sqlite3_free(zErrMsg); 7914 rc = 1; 7915 } 7916 }else 7917#endif 7918 7919 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ 7920 if( nArg!=2 ){ 7921 raw_printf(stderr, "Usage: .log FILENAME\n"); 7922 rc = 1; 7923 }else{ 7924 const char *zFile = azArg[1]; 7925 output_file_close(p->pLog); 7926 p->pLog = output_file_open(zFile, 0); 7927 } 7928 }else 7929 7930 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ 7931 const char *zMode = nArg>=2 ? azArg[1] : ""; 7932 int n2 = strlen30(zMode); 7933 int c2 = zMode[0]; 7934 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ 7935 p->mode = MODE_Line; 7936 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7937 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ 7938 p->mode = MODE_Column; 7939 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7940 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ 7941 p->mode = MODE_List; 7942 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); 7943 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7944 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ 7945 p->mode = MODE_Html; 7946 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ 7947 p->mode = MODE_Tcl; 7948 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); 7949 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7950 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ 7951 p->mode = MODE_Csv; 7952 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 7953 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 7954 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ 7955 p->mode = MODE_List; 7956 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); 7957 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ 7958 p->mode = MODE_Insert; 7959 set_table_name(p, nArg>=3 ? azArg[2] : "table"); 7960 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){ 7961 p->mode = MODE_Quote; 7962 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ 7963 p->mode = MODE_Ascii; 7964 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); 7965 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); 7966 }else if( nArg==1 ){ 7967 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); 7968 }else{ 7969 raw_printf(stderr, "Error: mode should be one of: " 7970 "ascii column csv html insert line list quote tabs tcl\n"); 7971 rc = 1; 7972 } 7973 p->cMode = p->mode; 7974 }else 7975 7976 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ 7977 if( nArg==2 ){ 7978 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, 7979 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); 7980 }else{ 7981 raw_printf(stderr, "Usage: .nullvalue STRING\n"); 7982 rc = 1; 7983 } 7984 }else 7985 7986 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ 7987 char *zNewFilename; /* Name of the database file to open */ 7988 int iName = 1; /* Index in azArg[] of the filename */ 7989 int newFlag = 0; /* True to delete file before opening */ 7990 /* Close the existing database */ 7991 session_close_all(p); 7992 close_db(p->db); 7993 p->db = 0; 7994 p->zDbFilename = 0; 7995 sqlite3_free(p->zFreeOnClose); 7996 p->zFreeOnClose = 0; 7997 p->openMode = SHELL_OPEN_UNSPEC; 7998 p->szMax = 0; 7999 /* Check for command-line arguments */ 8000 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){ 8001 const char *z = azArg[iName]; 8002 if( optionMatch(z,"new") ){ 8003 newFlag = 1; 8004#ifdef SQLITE_HAVE_ZLIB 8005 }else if( optionMatch(z, "zip") ){ 8006 p->openMode = SHELL_OPEN_ZIPFILE; 8007#endif 8008 }else if( optionMatch(z, "append") ){ 8009 p->openMode = SHELL_OPEN_APPENDVFS; 8010 }else if( optionMatch(z, "readonly") ){ 8011 p->openMode = SHELL_OPEN_READONLY; 8012#ifdef SQLITE_ENABLE_DESERIALIZE 8013 }else if( optionMatch(z, "deserialize") ){ 8014 p->openMode = SHELL_OPEN_DESERIALIZE; 8015 }else if( optionMatch(z, "hexdb") ){ 8016 p->openMode = SHELL_OPEN_HEXDB; 8017 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){ 8018 p->szMax = integerValue(azArg[++iName]); 8019#endif /* SQLITE_ENABLE_DESERIALIZE */ 8020 }else if( z[0]=='-' ){ 8021 utf8_printf(stderr, "unknown option: %s\n", z); 8022 rc = 1; 8023 goto meta_command_exit; 8024 } 8025 } 8026 /* If a filename is specified, try to open it first */ 8027 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0; 8028 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){ 8029 if( newFlag ) shellDeleteFile(zNewFilename); 8030 p->zDbFilename = zNewFilename; 8031 open_db(p, OPEN_DB_KEEPALIVE); 8032 if( p->db==0 ){ 8033 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); 8034 sqlite3_free(zNewFilename); 8035 }else{ 8036 p->zFreeOnClose = zNewFilename; 8037 } 8038 } 8039 if( p->db==0 ){ 8040 /* As a fall-back open a TEMP database */ 8041 p->zDbFilename = 0; 8042 open_db(p, 0); 8043 } 8044 }else 8045 8046 if( (c=='o' 8047 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0)) 8048 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0) 8049 ){ 8050 const char *zFile = nArg>=2 ? azArg[1] : "stdout"; 8051 int bTxtMode = 0; 8052 if( azArg[0][0]=='e' ){ 8053 /* Transform the ".excel" command into ".once -x" */ 8054 nArg = 2; 8055 azArg[0] = "once"; 8056 zFile = azArg[1] = "-x"; 8057 n = 4; 8058 } 8059 if( nArg>2 ){ 8060 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]); 8061 rc = 1; 8062 goto meta_command_exit; 8063 } 8064 if( n>1 && strncmp(azArg[0], "once", n)==0 ){ 8065 if( nArg<2 ){ 8066 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n"); 8067 rc = 1; 8068 goto meta_command_exit; 8069 } 8070 p->outCount = 2; 8071 }else{ 8072 p->outCount = 0; 8073 } 8074 output_reset(p); 8075 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++; 8076#ifndef SQLITE_NOHAVE_SYSTEM 8077 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){ 8078 p->doXdgOpen = 1; 8079 outputModePush(p); 8080 if( zFile[1]=='x' ){ 8081 newTempFile(p, "csv"); 8082 p->mode = MODE_Csv; 8083 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8084 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 8085 }else{ 8086 newTempFile(p, "txt"); 8087 bTxtMode = 1; 8088 } 8089 zFile = p->zTempFile; 8090 } 8091#endif /* SQLITE_NOHAVE_SYSTEM */ 8092 if( zFile[0]=='|' ){ 8093#ifdef SQLITE_OMIT_POPEN 8094 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 8095 rc = 1; 8096 p->out = stdout; 8097#else 8098 p->out = popen(zFile + 1, "w"); 8099 if( p->out==0 ){ 8100 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); 8101 p->out = stdout; 8102 rc = 1; 8103 }else{ 8104 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 8105 } 8106#endif 8107 }else{ 8108 p->out = output_file_open(zFile, bTxtMode); 8109 if( p->out==0 ){ 8110 if( strcmp(zFile,"off")!=0 ){ 8111 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); 8112 } 8113 p->out = stdout; 8114 rc = 1; 8115 } else { 8116 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 8117 } 8118 } 8119 }else 8120 8121 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){ 8122 open_db(p,0); 8123 if( nArg<=1 ) goto parameter_syntax_error; 8124 8125 /* .parameter clear 8126 ** Clear all bind parameters by dropping the TEMP table that holds them. 8127 */ 8128 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){ 8129 int wrSchema = 0; 8130 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); 8131 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 8132 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", 8133 0, 0, 0); 8134 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); 8135 }else 8136 8137 /* .parameter list 8138 ** List all bind parameters. 8139 */ 8140 if( nArg==2 && strcmp(azArg[1],"list")==0 ){ 8141 sqlite3_stmt *pStmt = 0; 8142 int rx; 8143 int len = 0; 8144 rx = sqlite3_prepare_v2(p->db, 8145 "SELECT max(length(key)) " 8146 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 8147 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 8148 len = sqlite3_column_int(pStmt, 0); 8149 if( len>40 ) len = 40; 8150 } 8151 sqlite3_finalize(pStmt); 8152 pStmt = 0; 8153 if( len ){ 8154 rx = sqlite3_prepare_v2(p->db, 8155 "SELECT key, quote(value) " 8156 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 8157 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 8158 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0), 8159 sqlite3_column_text(pStmt,1)); 8160 } 8161 sqlite3_finalize(pStmt); 8162 } 8163 }else 8164 8165 /* .parameter init 8166 ** Make sure the TEMP table used to hold bind parameters exists. 8167 ** Create it if necessary. 8168 */ 8169 if( nArg==2 && strcmp(azArg[1],"init")==0 ){ 8170 bind_table_init(p); 8171 }else 8172 8173 /* .parameter set NAME VALUE 8174 ** Set or reset a bind parameter. NAME should be the full parameter 8175 ** name exactly as it appears in the query. (ex: $abc, @def). The 8176 ** VALUE can be in either SQL literal notation, or if not it will be 8177 ** understood to be a text string. 8178 */ 8179 if( nArg==4 && strcmp(azArg[1],"set")==0 ){ 8180 int rx; 8181 char *zSql; 8182 sqlite3_stmt *pStmt; 8183 const char *zKey = azArg[2]; 8184 const char *zValue = azArg[3]; 8185 bind_table_init(p); 8186 zSql = sqlite3_mprintf( 8187 "REPLACE INTO temp.sqlite_parameters(key,value)" 8188 "VALUES(%Q,%s);", zKey, zValue); 8189 if( zSql==0 ) shell_out_of_memory(); 8190 pStmt = 0; 8191 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8192 sqlite3_free(zSql); 8193 if( rx!=SQLITE_OK ){ 8194 sqlite3_finalize(pStmt); 8195 pStmt = 0; 8196 zSql = sqlite3_mprintf( 8197 "REPLACE INTO temp.sqlite_parameters(key,value)" 8198 "VALUES(%Q,%Q);", zKey, zValue); 8199 if( zSql==0 ) shell_out_of_memory(); 8200 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8201 sqlite3_free(zSql); 8202 if( rx!=SQLITE_OK ){ 8203 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); 8204 sqlite3_finalize(pStmt); 8205 pStmt = 0; 8206 rc = 1; 8207 } 8208 } 8209 sqlite3_step(pStmt); 8210 sqlite3_finalize(pStmt); 8211 }else 8212 8213 /* .parameter unset NAME 8214 ** Remove the NAME binding from the parameter binding table, if it 8215 ** exists. 8216 */ 8217 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){ 8218 char *zSql = sqlite3_mprintf( 8219 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); 8220 if( zSql==0 ) shell_out_of_memory(); 8221 sqlite3_exec(p->db, zSql, 0, 0, 0); 8222 sqlite3_free(zSql); 8223 }else 8224 /* If no command name matches, show a syntax error */ 8225 parameter_syntax_error: 8226 showHelp(p->out, "parameter"); 8227 }else 8228 8229 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ 8230 int i; 8231 for(i=1; i<nArg; i++){ 8232 if( i>1 ) raw_printf(p->out, " "); 8233 utf8_printf(p->out, "%s", azArg[i]); 8234 } 8235 raw_printf(p->out, "\n"); 8236 }else 8237 8238#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 8239 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){ 8240 int i; 8241 int nn = 0; 8242 p->flgProgress = 0; 8243 p->mxProgress = 0; 8244 p->nProgress = 0; 8245 for(i=1; i<nArg; i++){ 8246 const char *z = azArg[i]; 8247 if( z[0]=='-' ){ 8248 z++; 8249 if( z[0]=='-' ) z++; 8250 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 8251 p->flgProgress |= SHELL_PROGRESS_QUIET; 8252 continue; 8253 } 8254 if( strcmp(z,"reset")==0 ){ 8255 p->flgProgress |= SHELL_PROGRESS_RESET; 8256 continue; 8257 } 8258 if( strcmp(z,"once")==0 ){ 8259 p->flgProgress |= SHELL_PROGRESS_ONCE; 8260 continue; 8261 } 8262 if( strcmp(z,"limit")==0 ){ 8263 if( i+1>=nArg ){ 8264 utf8_printf(stderr, "Error: missing argument on --limit\n"); 8265 rc = 1; 8266 goto meta_command_exit; 8267 }else{ 8268 p->mxProgress = (int)integerValue(azArg[++i]); 8269 } 8270 continue; 8271 } 8272 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]); 8273 rc = 1; 8274 goto meta_command_exit; 8275 }else{ 8276 nn = (int)integerValue(z); 8277 } 8278 } 8279 open_db(p, 0); 8280 sqlite3_progress_handler(p->db, nn, progress_handler, p); 8281 }else 8282#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 8283 8284 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ 8285 if( nArg >= 2) { 8286 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); 8287 } 8288 if( nArg >= 3) { 8289 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); 8290 } 8291 }else 8292 8293 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ 8294 rc = 2; 8295 }else 8296 8297 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ 8298 FILE *inSaved = p->in; 8299 int savedLineno = p->lineno; 8300 if( nArg!=2 ){ 8301 raw_printf(stderr, "Usage: .read FILE\n"); 8302 rc = 1; 8303 goto meta_command_exit; 8304 } 8305 p->in = fopen(azArg[1], "rb"); 8306 if( p->in==0 ){ 8307 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); 8308 rc = 1; 8309 }else{ 8310 rc = process_input(p); 8311 fclose(p->in); 8312 } 8313 p->in = inSaved; 8314 p->lineno = savedLineno; 8315 }else 8316 8317 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ 8318 const char *zSrcFile; 8319 const char *zDb; 8320 sqlite3 *pSrc; 8321 sqlite3_backup *pBackup; 8322 int nTimeout = 0; 8323 8324 if( nArg==2 ){ 8325 zSrcFile = azArg[1]; 8326 zDb = "main"; 8327 }else if( nArg==3 ){ 8328 zSrcFile = azArg[2]; 8329 zDb = azArg[1]; 8330 }else{ 8331 raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); 8332 rc = 1; 8333 goto meta_command_exit; 8334 } 8335 rc = sqlite3_open(zSrcFile, &pSrc); 8336 if( rc!=SQLITE_OK ){ 8337 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); 8338 close_db(pSrc); 8339 return 1; 8340 } 8341 open_db(p, 0); 8342 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); 8343 if( pBackup==0 ){ 8344 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8345 close_db(pSrc); 8346 return 1; 8347 } 8348 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK 8349 || rc==SQLITE_BUSY ){ 8350 if( rc==SQLITE_BUSY ){ 8351 if( nTimeout++ >= 3 ) break; 8352 sqlite3_sleep(100); 8353 } 8354 } 8355 sqlite3_backup_finish(pBackup); 8356 if( rc==SQLITE_DONE ){ 8357 rc = 0; 8358 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ 8359 raw_printf(stderr, "Error: source database is busy\n"); 8360 rc = 1; 8361 }else{ 8362 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8363 rc = 1; 8364 } 8365 close_db(pSrc); 8366 }else 8367 8368 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ 8369 if( nArg==2 ){ 8370 p->scanstatsOn = (u8)booleanValue(azArg[1]); 8371#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 8372 raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); 8373#endif 8374 }else{ 8375 raw_printf(stderr, "Usage: .scanstats on|off\n"); 8376 rc = 1; 8377 } 8378 }else 8379 8380 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ 8381 ShellText sSelect; 8382 ShellState data; 8383 char *zErrMsg = 0; 8384 const char *zDiv = "("; 8385 const char *zName = 0; 8386 int iSchema = 0; 8387 int bDebug = 0; 8388 int ii; 8389 8390 open_db(p, 0); 8391 memcpy(&data, p, sizeof(data)); 8392 data.showHeader = 0; 8393 data.cMode = data.mode = MODE_Semi; 8394 initText(&sSelect); 8395 for(ii=1; ii<nArg; ii++){ 8396 if( optionMatch(azArg[ii],"indent") ){ 8397 data.cMode = data.mode = MODE_Pretty; 8398 }else if( optionMatch(azArg[ii],"debug") ){ 8399 bDebug = 1; 8400 }else if( zName==0 ){ 8401 zName = azArg[ii]; 8402 }else{ 8403 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n"); 8404 rc = 1; 8405 goto meta_command_exit; 8406 } 8407 } 8408 if( zName!=0 ){ 8409 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0; 8410 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){ 8411 char *new_argv[2], *new_colv[2]; 8412 new_argv[0] = sqlite3_mprintf( 8413 "CREATE TABLE %s (\n" 8414 " type text,\n" 8415 " name text,\n" 8416 " tbl_name text,\n" 8417 " rootpage integer,\n" 8418 " sql text\n" 8419 ")", isMaster ? "sqlite_master" : "sqlite_temp_master"); 8420 new_argv[1] = 0; 8421 new_colv[0] = "sql"; 8422 new_colv[1] = 0; 8423 callback(&data, 1, new_argv, new_colv); 8424 sqlite3_free(new_argv[0]); 8425 } 8426 } 8427 if( zDiv ){ 8428 sqlite3_stmt *pStmt = 0; 8429 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", 8430 -1, &pStmt, 0); 8431 if( rc ){ 8432 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8433 sqlite3_finalize(pStmt); 8434 rc = 1; 8435 goto meta_command_exit; 8436 } 8437 appendText(&sSelect, "SELECT sql FROM", 0); 8438 iSchema = 0; 8439 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 8440 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); 8441 char zScNum[30]; 8442 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); 8443 appendText(&sSelect, zDiv, 0); 8444 zDiv = " UNION ALL "; 8445 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); 8446 if( sqlite3_stricmp(zDb, "main")!=0 ){ 8447 appendText(&sSelect, zDb, '\''); 8448 }else{ 8449 appendText(&sSelect, "NULL", 0); 8450 } 8451 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); 8452 appendText(&sSelect, zScNum, 0); 8453 appendText(&sSelect, " AS snum, ", 0); 8454 appendText(&sSelect, zDb, '\''); 8455 appendText(&sSelect, " AS sname FROM ", 0); 8456 appendText(&sSelect, zDb, quoteChar(zDb)); 8457 appendText(&sSelect, ".sqlite_master", 0); 8458 } 8459 sqlite3_finalize(pStmt); 8460#ifdef SQLITE_INTROSPECTION_PRAGMAS 8461 if( zName ){ 8462 appendText(&sSelect, 8463 " UNION ALL SELECT shell_module_schema(name)," 8464 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0); 8465 } 8466#endif 8467 appendText(&sSelect, ") WHERE ", 0); 8468 if( zName ){ 8469 char *zQarg = sqlite3_mprintf("%Q", zName); 8470 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || 8471 strchr(zName, '[') != 0; 8472 if( strchr(zName, '.') ){ 8473 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); 8474 }else{ 8475 appendText(&sSelect, "lower(tbl_name)", 0); 8476 } 8477 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); 8478 appendText(&sSelect, zQarg, 0); 8479 if( !bGlob ){ 8480 appendText(&sSelect, " ESCAPE '\\' ", 0); 8481 } 8482 appendText(&sSelect, " AND ", 0); 8483 sqlite3_free(zQarg); 8484 } 8485 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL" 8486 " ORDER BY snum, rowid", 0); 8487 if( bDebug ){ 8488 utf8_printf(p->out, "SQL: %s;\n", sSelect.z); 8489 }else{ 8490 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); 8491 } 8492 freeText(&sSelect); 8493 } 8494 if( zErrMsg ){ 8495 utf8_printf(stderr,"Error: %s\n", zErrMsg); 8496 sqlite3_free(zErrMsg); 8497 rc = 1; 8498 }else if( rc != SQLITE_OK ){ 8499 raw_printf(stderr,"Error: querying schema information\n"); 8500 rc = 1; 8501 }else{ 8502 rc = 0; 8503 } 8504 }else 8505 8506#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 8507 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ 8508 sqlite3SelectTrace = (int)integerValue(azArg[1]); 8509 }else 8510#endif 8511 8512#if defined(SQLITE_ENABLE_SESSION) 8513 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ 8514 OpenSession *pSession = &p->aSession[0]; 8515 char **azCmd = &azArg[1]; 8516 int iSes = 0; 8517 int nCmd = nArg - 1; 8518 int i; 8519 if( nArg<=1 ) goto session_syntax_error; 8520 open_db(p, 0); 8521 if( nArg>=3 ){ 8522 for(iSes=0; iSes<p->nSession; iSes++){ 8523 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break; 8524 } 8525 if( iSes<p->nSession ){ 8526 pSession = &p->aSession[iSes]; 8527 azCmd++; 8528 nCmd--; 8529 }else{ 8530 pSession = &p->aSession[0]; 8531 iSes = 0; 8532 } 8533 } 8534 8535 /* .session attach TABLE 8536 ** Invoke the sqlite3session_attach() interface to attach a particular 8537 ** table so that it is never filtered. 8538 */ 8539 if( strcmp(azCmd[0],"attach")==0 ){ 8540 if( nCmd!=2 ) goto session_syntax_error; 8541 if( pSession->p==0 ){ 8542 session_not_open: 8543 raw_printf(stderr, "ERROR: No sessions are open\n"); 8544 }else{ 8545 rc = sqlite3session_attach(pSession->p, azCmd[1]); 8546 if( rc ){ 8547 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); 8548 rc = 0; 8549 } 8550 } 8551 }else 8552 8553 /* .session changeset FILE 8554 ** .session patchset FILE 8555 ** Write a changeset or patchset into a file. The file is overwritten. 8556 */ 8557 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ 8558 FILE *out = 0; 8559 if( nCmd!=2 ) goto session_syntax_error; 8560 if( pSession->p==0 ) goto session_not_open; 8561 out = fopen(azCmd[1], "wb"); 8562 if( out==0 ){ 8563 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]); 8564 }else{ 8565 int szChng; 8566 void *pChng; 8567 if( azCmd[0][0]=='c' ){ 8568 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); 8569 }else{ 8570 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); 8571 } 8572 if( rc ){ 8573 printf("Error: error code %d\n", rc); 8574 rc = 0; 8575 } 8576 if( pChng 8577 && fwrite(pChng, szChng, 1, out)!=1 ){ 8578 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", 8579 szChng); 8580 } 8581 sqlite3_free(pChng); 8582 fclose(out); 8583 } 8584 }else 8585 8586 /* .session close 8587 ** Close the identified session 8588 */ 8589 if( strcmp(azCmd[0], "close")==0 ){ 8590 if( nCmd!=1 ) goto session_syntax_error; 8591 if( p->nSession ){ 8592 session_close(pSession); 8593 p->aSession[iSes] = p->aSession[--p->nSession]; 8594 } 8595 }else 8596 8597 /* .session enable ?BOOLEAN? 8598 ** Query or set the enable flag 8599 */ 8600 if( strcmp(azCmd[0], "enable")==0 ){ 8601 int ii; 8602 if( nCmd>2 ) goto session_syntax_error; 8603 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 8604 if( p->nSession ){ 8605 ii = sqlite3session_enable(pSession->p, ii); 8606 utf8_printf(p->out, "session %s enable flag = %d\n", 8607 pSession->zName, ii); 8608 } 8609 }else 8610 8611 /* .session filter GLOB .... 8612 ** Set a list of GLOB patterns of table names to be excluded. 8613 */ 8614 if( strcmp(azCmd[0], "filter")==0 ){ 8615 int ii, nByte; 8616 if( nCmd<2 ) goto session_syntax_error; 8617 if( p->nSession ){ 8618 for(ii=0; ii<pSession->nFilter; ii++){ 8619 sqlite3_free(pSession->azFilter[ii]); 8620 } 8621 sqlite3_free(pSession->azFilter); 8622 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); 8623 pSession->azFilter = sqlite3_malloc( nByte ); 8624 if( pSession->azFilter==0 ){ 8625 raw_printf(stderr, "Error: out or memory\n"); 8626 exit(1); 8627 } 8628 for(ii=1; ii<nCmd; ii++){ 8629 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); 8630 } 8631 pSession->nFilter = ii-1; 8632 } 8633 }else 8634 8635 /* .session indirect ?BOOLEAN? 8636 ** Query or set the indirect flag 8637 */ 8638 if( strcmp(azCmd[0], "indirect")==0 ){ 8639 int ii; 8640 if( nCmd>2 ) goto session_syntax_error; 8641 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 8642 if( p->nSession ){ 8643 ii = sqlite3session_indirect(pSession->p, ii); 8644 utf8_printf(p->out, "session %s indirect flag = %d\n", 8645 pSession->zName, ii); 8646 } 8647 }else 8648 8649 /* .session isempty 8650 ** Determine if the session is empty 8651 */ 8652 if( strcmp(azCmd[0], "isempty")==0 ){ 8653 int ii; 8654 if( nCmd!=1 ) goto session_syntax_error; 8655 if( p->nSession ){ 8656 ii = sqlite3session_isempty(pSession->p); 8657 utf8_printf(p->out, "session %s isempty flag = %d\n", 8658 pSession->zName, ii); 8659 } 8660 }else 8661 8662 /* .session list 8663 ** List all currently open sessions 8664 */ 8665 if( strcmp(azCmd[0],"list")==0 ){ 8666 for(i=0; i<p->nSession; i++){ 8667 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName); 8668 } 8669 }else 8670 8671 /* .session open DB NAME 8672 ** Open a new session called NAME on the attached database DB. 8673 ** DB is normally "main". 8674 */ 8675 if( strcmp(azCmd[0],"open")==0 ){ 8676 char *zName; 8677 if( nCmd!=3 ) goto session_syntax_error; 8678 zName = azCmd[2]; 8679 if( zName[0]==0 ) goto session_syntax_error; 8680 for(i=0; i<p->nSession; i++){ 8681 if( strcmp(p->aSession[i].zName,zName)==0 ){ 8682 utf8_printf(stderr, "Session \"%s\" already exists\n", zName); 8683 goto meta_command_exit; 8684 } 8685 } 8686 if( p->nSession>=ArraySize(p->aSession) ){ 8687 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession)); 8688 goto meta_command_exit; 8689 } 8690 pSession = &p->aSession[p->nSession]; 8691 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); 8692 if( rc ){ 8693 raw_printf(stderr, "Cannot open session: error code=%d\n", rc); 8694 rc = 0; 8695 goto meta_command_exit; 8696 } 8697 pSession->nFilter = 0; 8698 sqlite3session_table_filter(pSession->p, session_filter, pSession); 8699 p->nSession++; 8700 pSession->zName = sqlite3_mprintf("%s", zName); 8701 }else 8702 /* If no command name matches, show a syntax error */ 8703 session_syntax_error: 8704 showHelp(p->out, "session"); 8705 }else 8706#endif 8707 8708#ifdef SQLITE_DEBUG 8709 /* Undocumented commands for internal testing. Subject to change 8710 ** without notice. */ 8711 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ 8712 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ 8713 int i, v; 8714 for(i=1; i<nArg; i++){ 8715 v = booleanValue(azArg[i]); 8716 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); 8717 } 8718 } 8719 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ 8720 int i; sqlite3_int64 v; 8721 for(i=1; i<nArg; i++){ 8722 char zBuf[200]; 8723 v = integerValue(azArg[i]); 8724 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); 8725 utf8_printf(p->out, "%s", zBuf); 8726 } 8727 } 8728 }else 8729#endif 8730 8731 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){ 8732 int bIsInit = 0; /* True to initialize the SELFTEST table */ 8733 int bVerbose = 0; /* Verbose output */ 8734 int bSelftestExists; /* True if SELFTEST already exists */ 8735 int i, k; /* Loop counters */ 8736 int nTest = 0; /* Number of tests runs */ 8737 int nErr = 0; /* Number of errors seen */ 8738 ShellText str; /* Answer for a query */ 8739 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ 8740 8741 open_db(p,0); 8742 for(i=1; i<nArg; i++){ 8743 const char *z = azArg[i]; 8744 if( z[0]=='-' && z[1]=='-' ) z++; 8745 if( strcmp(z,"-init")==0 ){ 8746 bIsInit = 1; 8747 }else 8748 if( strcmp(z,"-v")==0 ){ 8749 bVerbose++; 8750 }else 8751 { 8752 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 8753 azArg[i], azArg[0]); 8754 raw_printf(stderr, "Should be one of: --init -v\n"); 8755 rc = 1; 8756 goto meta_command_exit; 8757 } 8758 } 8759 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) 8760 != SQLITE_OK ){ 8761 bSelftestExists = 0; 8762 }else{ 8763 bSelftestExists = 1; 8764 } 8765 if( bIsInit ){ 8766 createSelftestTable(p); 8767 bSelftestExists = 1; 8768 } 8769 initText(&str); 8770 appendText(&str, "x", 0); 8771 for(k=bSelftestExists; k>=0; k--){ 8772 if( k==1 ){ 8773 rc = sqlite3_prepare_v2(p->db, 8774 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", 8775 -1, &pStmt, 0); 8776 }else{ 8777 rc = sqlite3_prepare_v2(p->db, 8778 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," 8779 " (1,'run','PRAGMA integrity_check','ok')", 8780 -1, &pStmt, 0); 8781 } 8782 if( rc ){ 8783 raw_printf(stderr, "Error querying the selftest table\n"); 8784 rc = 1; 8785 sqlite3_finalize(pStmt); 8786 goto meta_command_exit; 8787 } 8788 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ 8789 int tno = sqlite3_column_int(pStmt, 0); 8790 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); 8791 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); 8792 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); 8793 8794 k = 0; 8795 if( bVerbose>0 ){ 8796 char *zQuote = sqlite3_mprintf("%q", zSql); 8797 printf("%d: %s %s\n", tno, zOp, zSql); 8798 sqlite3_free(zQuote); 8799 } 8800 if( strcmp(zOp,"memo")==0 ){ 8801 utf8_printf(p->out, "%s\n", zSql); 8802 }else 8803 if( strcmp(zOp,"run")==0 ){ 8804 char *zErrMsg = 0; 8805 str.n = 0; 8806 str.z[0] = 0; 8807 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); 8808 nTest++; 8809 if( bVerbose ){ 8810 utf8_printf(p->out, "Result: %s\n", str.z); 8811 } 8812 if( rc || zErrMsg ){ 8813 nErr++; 8814 rc = 1; 8815 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); 8816 sqlite3_free(zErrMsg); 8817 }else if( strcmp(zAns,str.z)!=0 ){ 8818 nErr++; 8819 rc = 1; 8820 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); 8821 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); 8822 } 8823 }else 8824 { 8825 utf8_printf(stderr, 8826 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); 8827 rc = 1; 8828 break; 8829 } 8830 } /* End loop over rows of content from SELFTEST */ 8831 sqlite3_finalize(pStmt); 8832 } /* End loop over k */ 8833 freeText(&str); 8834 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); 8835 }else 8836 8837 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ 8838 if( nArg<2 || nArg>3 ){ 8839 raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); 8840 rc = 1; 8841 } 8842 if( nArg>=2 ){ 8843 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, 8844 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); 8845 } 8846 if( nArg>=3 ){ 8847 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, 8848 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); 8849 } 8850 }else 8851 8852 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){ 8853 const char *zLike = 0; /* Which table to checksum. 0 means everything */ 8854 int i; /* Loop counter */ 8855 int bSchema = 0; /* Also hash the schema */ 8856 int bSeparate = 0; /* Hash each table separately */ 8857 int iSize = 224; /* Hash algorithm to use */ 8858 int bDebug = 0; /* Only show the query that would have run */ 8859 sqlite3_stmt *pStmt; /* For querying tables names */ 8860 char *zSql; /* SQL to be run */ 8861 char *zSep; /* Separator */ 8862 ShellText sSql; /* Complete SQL for the query to run the hash */ 8863 ShellText sQuery; /* Set of queries used to read all content */ 8864 open_db(p, 0); 8865 for(i=1; i<nArg; i++){ 8866 const char *z = azArg[i]; 8867 if( z[0]=='-' ){ 8868 z++; 8869 if( z[0]=='-' ) z++; 8870 if( strcmp(z,"schema")==0 ){ 8871 bSchema = 1; 8872 }else 8873 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 8874 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 8875 ){ 8876 iSize = atoi(&z[5]); 8877 }else 8878 if( strcmp(z,"debug")==0 ){ 8879 bDebug = 1; 8880 }else 8881 { 8882 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 8883 azArg[i], azArg[0]); 8884 raw_printf(stderr, "Should be one of: --schema" 8885 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n"); 8886 rc = 1; 8887 goto meta_command_exit; 8888 } 8889 }else if( zLike ){ 8890 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); 8891 rc = 1; 8892 goto meta_command_exit; 8893 }else{ 8894 zLike = z; 8895 bSeparate = 1; 8896 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; 8897 } 8898 } 8899 if( bSchema ){ 8900 zSql = "SELECT lower(name) FROM sqlite_master" 8901 " WHERE type='table' AND coalesce(rootpage,0)>1" 8902 " UNION ALL SELECT 'sqlite_master'" 8903 " ORDER BY 1 collate nocase"; 8904 }else{ 8905 zSql = "SELECT lower(name) FROM sqlite_master" 8906 " WHERE type='table' AND coalesce(rootpage,0)>1" 8907 " AND name NOT LIKE 'sqlite_%'" 8908 " ORDER BY 1 collate nocase"; 8909 } 8910 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8911 initText(&sQuery); 8912 initText(&sSql); 8913 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); 8914 zSep = "VALUES("; 8915 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 8916 const char *zTab = (const char*)sqlite3_column_text(pStmt,0); 8917 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; 8918 if( strncmp(zTab, "sqlite_",7)!=0 ){ 8919 appendText(&sQuery,"SELECT * FROM ", 0); 8920 appendText(&sQuery,zTab,'"'); 8921 appendText(&sQuery," NOT INDEXED;", 0); 8922 }else if( strcmp(zTab, "sqlite_master")==0 ){ 8923 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master" 8924 " ORDER BY name;", 0); 8925 }else if( strcmp(zTab, "sqlite_sequence")==0 ){ 8926 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" 8927 " ORDER BY name;", 0); 8928 }else if( strcmp(zTab, "sqlite_stat1")==0 ){ 8929 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" 8930 " ORDER BY tbl,idx;", 0); 8931 }else if( strcmp(zTab, "sqlite_stat4")==0 ){ 8932 appendText(&sQuery, "SELECT * FROM ", 0); 8933 appendText(&sQuery, zTab, 0); 8934 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); 8935 } 8936 appendText(&sSql, zSep, 0); 8937 appendText(&sSql, sQuery.z, '\''); 8938 sQuery.n = 0; 8939 appendText(&sSql, ",", 0); 8940 appendText(&sSql, zTab, '\''); 8941 zSep = "),("; 8942 } 8943 sqlite3_finalize(pStmt); 8944 if( bSeparate ){ 8945 zSql = sqlite3_mprintf( 8946 "%s))" 8947 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" 8948 " FROM [sha3sum$query]", 8949 sSql.z, iSize); 8950 }else{ 8951 zSql = sqlite3_mprintf( 8952 "%s))" 8953 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" 8954 " FROM [sha3sum$query]", 8955 sSql.z, iSize); 8956 } 8957 freeText(&sQuery); 8958 freeText(&sSql); 8959 if( bDebug ){ 8960 utf8_printf(p->out, "%s\n", zSql); 8961 }else{ 8962 shell_exec(p, zSql, 0); 8963 } 8964 sqlite3_free(zSql); 8965 }else 8966 8967#ifndef SQLITE_NOHAVE_SYSTEM 8968 if( c=='s' 8969 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) 8970 ){ 8971 char *zCmd; 8972 int i, x; 8973 if( nArg<2 ){ 8974 raw_printf(stderr, "Usage: .system COMMAND\n"); 8975 rc = 1; 8976 goto meta_command_exit; 8977 } 8978 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); 8979 for(i=2; i<nArg; i++){ 8980 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", 8981 zCmd, azArg[i]); 8982 } 8983 x = system(zCmd); 8984 sqlite3_free(zCmd); 8985 if( x ) raw_printf(stderr, "System command returns %d\n", x); 8986 }else 8987#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 8988 8989 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){ 8990 static const char *azBool[] = { "off", "on", "trigger", "full"}; 8991 int i; 8992 if( nArg!=1 ){ 8993 raw_printf(stderr, "Usage: .show\n"); 8994 rc = 1; 8995 goto meta_command_exit; 8996 } 8997 utf8_printf(p->out, "%12.12s: %s\n","echo", 8998 azBool[ShellHasFlag(p, SHFLG_Echo)]); 8999 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); 9000 utf8_printf(p->out, "%12.12s: %s\n","explain", 9001 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); 9002 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); 9003 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); 9004 utf8_printf(p->out, "%12.12s: ", "nullvalue"); 9005 output_c_string(p->out, p->nullValue); 9006 raw_printf(p->out, "\n"); 9007 utf8_printf(p->out,"%12.12s: %s\n","output", 9008 strlen30(p->outfile) ? p->outfile : "stdout"); 9009 utf8_printf(p->out,"%12.12s: ", "colseparator"); 9010 output_c_string(p->out, p->colSeparator); 9011 raw_printf(p->out, "\n"); 9012 utf8_printf(p->out,"%12.12s: ", "rowseparator"); 9013 output_c_string(p->out, p->rowSeparator); 9014 raw_printf(p->out, "\n"); 9015 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]); 9016 utf8_printf(p->out, "%12.12s: ", "width"); 9017 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { 9018 raw_printf(p->out, "%d ", p->colWidth[i]); 9019 } 9020 raw_printf(p->out, "\n"); 9021 utf8_printf(p->out, "%12.12s: %s\n", "filename", 9022 p->zDbFilename ? p->zDbFilename : ""); 9023 }else 9024 9025 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ 9026 if( nArg==2 ){ 9027 p->statsOn = (u8)booleanValue(azArg[1]); 9028 }else if( nArg==1 ){ 9029 display_stats(p->db, p, 0); 9030 }else{ 9031 raw_printf(stderr, "Usage: .stats ?on|off?\n"); 9032 rc = 1; 9033 } 9034 }else 9035 9036 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0) 9037 || (c=='i' && (strncmp(azArg[0], "indices", n)==0 9038 || strncmp(azArg[0], "indexes", n)==0) ) 9039 ){ 9040 sqlite3_stmt *pStmt; 9041 char **azResult; 9042 int nRow, nAlloc; 9043 int ii; 9044 ShellText s; 9045 initText(&s); 9046 open_db(p, 0); 9047 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 9048 if( rc ){ 9049 sqlite3_finalize(pStmt); 9050 return shellDatabaseError(p->db); 9051 } 9052 9053 if( nArg>2 && c=='i' ){ 9054 /* It is an historical accident that the .indexes command shows an error 9055 ** when called with the wrong number of arguments whereas the .tables 9056 ** command does not. */ 9057 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); 9058 rc = 1; 9059 sqlite3_finalize(pStmt); 9060 goto meta_command_exit; 9061 } 9062 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ 9063 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); 9064 if( zDbName==0 ) continue; 9065 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); 9066 if( sqlite3_stricmp(zDbName, "main")==0 ){ 9067 appendText(&s, "SELECT name FROM ", 0); 9068 }else{ 9069 appendText(&s, "SELECT ", 0); 9070 appendText(&s, zDbName, '\''); 9071 appendText(&s, "||'.'||name FROM ", 0); 9072 } 9073 appendText(&s, zDbName, '"'); 9074 appendText(&s, ".sqlite_master ", 0); 9075 if( c=='t' ){ 9076 appendText(&s," WHERE type IN ('table','view')" 9077 " AND name NOT LIKE 'sqlite_%'" 9078 " AND name LIKE ?1", 0); 9079 }else{ 9080 appendText(&s," WHERE type='index'" 9081 " AND tbl_name LIKE ?1", 0); 9082 } 9083 } 9084 rc = sqlite3_finalize(pStmt); 9085 appendText(&s, " ORDER BY 1", 0); 9086 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); 9087 freeText(&s); 9088 if( rc ) return shellDatabaseError(p->db); 9089 9090 /* Run the SQL statement prepared by the above block. Store the results 9091 ** as an array of nul-terminated strings in azResult[]. */ 9092 nRow = nAlloc = 0; 9093 azResult = 0; 9094 if( nArg>1 ){ 9095 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); 9096 }else{ 9097 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); 9098 } 9099 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 9100 if( nRow>=nAlloc ){ 9101 char **azNew; 9102 int n2 = nAlloc*2 + 10; 9103 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); 9104 if( azNew==0 ) shell_out_of_memory(); 9105 nAlloc = n2; 9106 azResult = azNew; 9107 } 9108 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 9109 if( 0==azResult[nRow] ) shell_out_of_memory(); 9110 nRow++; 9111 } 9112 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ 9113 rc = shellDatabaseError(p->db); 9114 } 9115 9116 /* Pretty-print the contents of array azResult[] to the output */ 9117 if( rc==0 && nRow>0 ){ 9118 int len, maxlen = 0; 9119 int i, j; 9120 int nPrintCol, nPrintRow; 9121 for(i=0; i<nRow; i++){ 9122 len = strlen30(azResult[i]); 9123 if( len>maxlen ) maxlen = len; 9124 } 9125 nPrintCol = 80/(maxlen+2); 9126 if( nPrintCol<1 ) nPrintCol = 1; 9127 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; 9128 for(i=0; i<nPrintRow; i++){ 9129 for(j=i; j<nRow; j+=nPrintRow){ 9130 char *zSp = j<nPrintRow ? "" : " "; 9131 utf8_printf(p->out, "%s%-*s", zSp, maxlen, 9132 azResult[j] ? azResult[j]:""); 9133 } 9134 raw_printf(p->out, "\n"); 9135 } 9136 } 9137 9138 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); 9139 sqlite3_free(azResult); 9140 }else 9141 9142 /* Begin redirecting output to the file "testcase-out.txt" */ 9143 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){ 9144 output_reset(p); 9145 p->out = output_file_open("testcase-out.txt", 0); 9146 if( p->out==0 ){ 9147 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); 9148 } 9149 if( nArg>=2 ){ 9150 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); 9151 }else{ 9152 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); 9153 } 9154 }else 9155 9156#ifndef SQLITE_UNTESTABLE 9157 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){ 9158 static const struct { 9159 const char *zCtrlName; /* Name of a test-control option */ 9160 int ctrlCode; /* Integer code for that option */ 9161 const char *zUsage; /* Usage notes */ 9162 } aCtrl[] = { 9163 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" }, 9164 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" }, 9165 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/ 9166 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/ 9167 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" }, 9168 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN" }, 9169 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */ 9170 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"}, 9171 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" }, 9172 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" }, 9173 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" }, 9174 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" }, 9175#ifdef YYCOVERAGE 9176 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" }, 9177#endif 9178 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " }, 9179 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" }, 9180 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" }, 9181 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, "SEED ?db?" }, 9182 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" }, 9183 }; 9184 int testctrl = -1; 9185 int iCtrl = -1; 9186 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ 9187 int isOk = 0; 9188 int i, n2; 9189 const char *zCmd = 0; 9190 9191 open_db(p, 0); 9192 zCmd = nArg>=2 ? azArg[1] : "help"; 9193 9194 /* The argument can optionally begin with "-" or "--" */ 9195 if( zCmd[0]=='-' && zCmd[1] ){ 9196 zCmd++; 9197 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 9198 } 9199 9200 /* --help lists all test-controls */ 9201 if( strcmp(zCmd,"help")==0 ){ 9202 utf8_printf(p->out, "Available test-controls:\n"); 9203 for(i=0; i<ArraySize(aCtrl); i++){ 9204 utf8_printf(p->out, " .testctrl %s %s\n", 9205 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 9206 } 9207 rc = 1; 9208 goto meta_command_exit; 9209 } 9210 9211 /* convert testctrl text option to value. allow any unique prefix 9212 ** of the option name, or a numerical value. */ 9213 n2 = strlen30(zCmd); 9214 for(i=0; i<ArraySize(aCtrl); i++){ 9215 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 9216 if( testctrl<0 ){ 9217 testctrl = aCtrl[i].ctrlCode; 9218 iCtrl = i; 9219 }else{ 9220 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n" 9221 "Use \".testctrl --help\" for help\n", zCmd); 9222 rc = 1; 9223 goto meta_command_exit; 9224 } 9225 } 9226 } 9227 if( testctrl<0 ){ 9228 utf8_printf(stderr,"Error: unknown test-control: %s\n" 9229 "Use \".testctrl --help\" for help\n", zCmd); 9230 }else{ 9231 switch(testctrl){ 9232 9233 /* sqlite3_test_control(int, db, int) */ 9234 case SQLITE_TESTCTRL_OPTIMIZATIONS: 9235 case SQLITE_TESTCTRL_RESERVE: 9236 if( nArg==3 ){ 9237 int opt = (int)strtol(azArg[2], 0, 0); 9238 rc2 = sqlite3_test_control(testctrl, p->db, opt); 9239 isOk = 3; 9240 } 9241 break; 9242 9243 /* sqlite3_test_control(int) */ 9244 case SQLITE_TESTCTRL_PRNG_SAVE: 9245 case SQLITE_TESTCTRL_PRNG_RESTORE: 9246 case SQLITE_TESTCTRL_PRNG_RESET: 9247 case SQLITE_TESTCTRL_BYTEORDER: 9248 if( nArg==2 ){ 9249 rc2 = sqlite3_test_control(testctrl); 9250 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; 9251 } 9252 break; 9253 9254 /* sqlite3_test_control(int, uint) */ 9255 case SQLITE_TESTCTRL_PENDING_BYTE: 9256 if( nArg==3 ){ 9257 unsigned int opt = (unsigned int)integerValue(azArg[2]); 9258 rc2 = sqlite3_test_control(testctrl, opt); 9259 isOk = 3; 9260 } 9261 break; 9262 9263 /* sqlite3_test_control(int, int, sqlite3*) */ 9264 case SQLITE_TESTCTRL_PRNG_SEED: 9265 if( nArg==3 || nArg==4 ){ 9266 int ii = (int)integerValue(azArg[2]); 9267 sqlite3 *db; 9268 if( ii==0 && strcmp(azArg[2],"random")==0 ){ 9269 sqlite3_randomness(sizeof(ii),&ii); 9270 printf("-- random seed: %d\n", ii); 9271 } 9272 if( nArg==3 ){ 9273 db = 0; 9274 }else{ 9275 db = p->db; 9276 /* Make sure the schema has been loaded */ 9277 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0); 9278 } 9279 rc2 = sqlite3_test_control(testctrl, ii, db); 9280 isOk = 3; 9281 } 9282 break; 9283 9284 /* sqlite3_test_control(int, int) */ 9285 case SQLITE_TESTCTRL_ASSERT: 9286 case SQLITE_TESTCTRL_ALWAYS: 9287 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: 9288 if( nArg==3 ){ 9289 int opt = booleanValue(azArg[2]); 9290 rc2 = sqlite3_test_control(testctrl, opt); 9291 isOk = 1; 9292 } 9293 break; 9294 9295 /* sqlite3_test_control(int, int) */ 9296 case SQLITE_TESTCTRL_LOCALTIME_FAULT: 9297 case SQLITE_TESTCTRL_NEVER_CORRUPT: 9298 if( nArg==3 ){ 9299 int opt = booleanValue(azArg[2]); 9300 rc2 = sqlite3_test_control(testctrl, opt); 9301 isOk = 3; 9302 } 9303 break; 9304 9305 case SQLITE_TESTCTRL_IMPOSTER: 9306 if( nArg==5 ){ 9307 rc2 = sqlite3_test_control(testctrl, p->db, 9308 azArg[2], 9309 integerValue(azArg[3]), 9310 integerValue(azArg[4])); 9311 isOk = 3; 9312 } 9313 break; 9314 9315#ifdef YYCOVERAGE 9316 case SQLITE_TESTCTRL_PARSER_COVERAGE: 9317 if( nArg==2 ){ 9318 sqlite3_test_control(testctrl, p->out); 9319 isOk = 3; 9320 } 9321#endif 9322 } 9323 } 9324 if( isOk==0 && iCtrl>=0 ){ 9325 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage); 9326 rc = 1; 9327 }else if( isOk==1 ){ 9328 raw_printf(p->out, "%d\n", rc2); 9329 }else if( isOk==2 ){ 9330 raw_printf(p->out, "0x%08x\n", rc2); 9331 } 9332 }else 9333#endif /* !defined(SQLITE_UNTESTABLE) */ 9334 9335 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ 9336 open_db(p, 0); 9337 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); 9338 }else 9339 9340 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ 9341 if( nArg==2 ){ 9342 enableTimer = booleanValue(azArg[1]); 9343 if( enableTimer && !HAS_TIMER ){ 9344 raw_printf(stderr, "Error: timer not available on this system.\n"); 9345 enableTimer = 0; 9346 } 9347 }else{ 9348 raw_printf(stderr, "Usage: .timer on|off\n"); 9349 rc = 1; 9350 } 9351 }else 9352 9353#ifndef SQLITE_OMIT_TRACE 9354 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ 9355 int mType = 0; 9356 int jj; 9357 open_db(p, 0); 9358 for(jj=1; jj<nArg; jj++){ 9359 const char *z = azArg[jj]; 9360 if( z[0]=='-' ){ 9361 if( optionMatch(z, "expanded") ){ 9362 p->eTraceType = SHELL_TRACE_EXPANDED; 9363 } 9364#ifdef SQLITE_ENABLE_NORMALIZE 9365 else if( optionMatch(z, "normalized") ){ 9366 p->eTraceType = SHELL_TRACE_NORMALIZED; 9367 } 9368#endif 9369 else if( optionMatch(z, "plain") ){ 9370 p->eTraceType = SHELL_TRACE_PLAIN; 9371 } 9372 else if( optionMatch(z, "profile") ){ 9373 mType |= SQLITE_TRACE_PROFILE; 9374 } 9375 else if( optionMatch(z, "row") ){ 9376 mType |= SQLITE_TRACE_ROW; 9377 } 9378 else if( optionMatch(z, "stmt") ){ 9379 mType |= SQLITE_TRACE_STMT; 9380 } 9381 else if( optionMatch(z, "close") ){ 9382 mType |= SQLITE_TRACE_CLOSE; 9383 } 9384 else { 9385 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z); 9386 rc = 1; 9387 goto meta_command_exit; 9388 } 9389 }else{ 9390 output_file_close(p->traceOut); 9391 p->traceOut = output_file_open(azArg[1], 0); 9392 } 9393 } 9394 if( p->traceOut==0 ){ 9395 sqlite3_trace_v2(p->db, 0, 0, 0); 9396 }else{ 9397 if( mType==0 ) mType = SQLITE_TRACE_STMT; 9398 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); 9399 } 9400 }else 9401#endif /* !defined(SQLITE_OMIT_TRACE) */ 9402 9403#if SQLITE_USER_AUTHENTICATION 9404 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ 9405 if( nArg<2 ){ 9406 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); 9407 rc = 1; 9408 goto meta_command_exit; 9409 } 9410 open_db(p, 0); 9411 if( strcmp(azArg[1],"login")==0 ){ 9412 if( nArg!=4 ){ 9413 raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); 9414 rc = 1; 9415 goto meta_command_exit; 9416 } 9417 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3])); 9418 if( rc ){ 9419 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); 9420 rc = 1; 9421 } 9422 }else if( strcmp(azArg[1],"add")==0 ){ 9423 if( nArg!=5 ){ 9424 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); 9425 rc = 1; 9426 goto meta_command_exit; 9427 } 9428 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 9429 booleanValue(azArg[4])); 9430 if( rc ){ 9431 raw_printf(stderr, "User-Add failed: %d\n", rc); 9432 rc = 1; 9433 } 9434 }else if( strcmp(azArg[1],"edit")==0 ){ 9435 if( nArg!=5 ){ 9436 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); 9437 rc = 1; 9438 goto meta_command_exit; 9439 } 9440 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 9441 booleanValue(azArg[4])); 9442 if( rc ){ 9443 raw_printf(stderr, "User-Edit failed: %d\n", rc); 9444 rc = 1; 9445 } 9446 }else if( strcmp(azArg[1],"delete")==0 ){ 9447 if( nArg!=3 ){ 9448 raw_printf(stderr, "Usage: .user delete USER\n"); 9449 rc = 1; 9450 goto meta_command_exit; 9451 } 9452 rc = sqlite3_user_delete(p->db, azArg[2]); 9453 if( rc ){ 9454 raw_printf(stderr, "User-Delete failed: %d\n", rc); 9455 rc = 1; 9456 } 9457 }else{ 9458 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); 9459 rc = 1; 9460 goto meta_command_exit; 9461 } 9462 }else 9463#endif /* SQLITE_USER_AUTHENTICATION */ 9464 9465 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ 9466 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, 9467 sqlite3_libversion(), sqlite3_sourceid()); 9468#if SQLITE_HAVE_ZLIB 9469 utf8_printf(p->out, "zlib version %s\n", zlibVersion()); 9470#endif 9471#define CTIMEOPT_VAL_(opt) #opt 9472#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) 9473#if defined(__clang__) && defined(__clang_major__) 9474 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." 9475 CTIMEOPT_VAL(__clang_minor__) "." 9476 CTIMEOPT_VAL(__clang_patchlevel__) "\n"); 9477#elif defined(_MSC_VER) 9478 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); 9479#elif defined(__GNUC__) && defined(__VERSION__) 9480 utf8_printf(p->out, "gcc-" __VERSION__ "\n"); 9481#endif 9482 }else 9483 9484 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ 9485 const char *zDbName = nArg==2 ? azArg[1] : "main"; 9486 sqlite3_vfs *pVfs = 0; 9487 if( p->db ){ 9488 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); 9489 if( pVfs ){ 9490 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); 9491 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 9492 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 9493 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 9494 } 9495 } 9496 }else 9497 9498 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ 9499 sqlite3_vfs *pVfs; 9500 sqlite3_vfs *pCurrent = 0; 9501 if( p->db ){ 9502 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); 9503 } 9504 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ 9505 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, 9506 pVfs==pCurrent ? " <--- CURRENT" : ""); 9507 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 9508 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 9509 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 9510 if( pVfs->pNext ){ 9511 raw_printf(p->out, "-----------------------------------\n"); 9512 } 9513 } 9514 }else 9515 9516 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ 9517 const char *zDbName = nArg==2 ? azArg[1] : "main"; 9518 char *zVfsName = 0; 9519 if( p->db ){ 9520 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); 9521 if( zVfsName ){ 9522 utf8_printf(p->out, "%s\n", zVfsName); 9523 sqlite3_free(zVfsName); 9524 } 9525 } 9526 }else 9527 9528#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 9529 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ 9530 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff; 9531 }else 9532#endif 9533 9534 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ 9535 int j; 9536 assert( nArg<=ArraySize(azArg) ); 9537 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){ 9538 p->colWidth[j-1] = (int)integerValue(azArg[j]); 9539 } 9540 }else 9541 9542 { 9543 utf8_printf(stderr, "Error: unknown command or invalid arguments: " 9544 " \"%s\". Enter \".help\" for help\n", azArg[0]); 9545 rc = 1; 9546 } 9547 9548meta_command_exit: 9549 if( p->outCount ){ 9550 p->outCount--; 9551 if( p->outCount==0 ) output_reset(p); 9552 } 9553 return rc; 9554} 9555 9556/* 9557** Return TRUE if a semicolon occurs anywhere in the first N characters 9558** of string z[]. 9559*/ 9560static int line_contains_semicolon(const char *z, int N){ 9561 int i; 9562 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; } 9563 return 0; 9564} 9565 9566/* 9567** Test to see if a line consists entirely of whitespace. 9568*/ 9569static int _all_whitespace(const char *z){ 9570 for(; *z; z++){ 9571 if( IsSpace(z[0]) ) continue; 9572 if( *z=='/' && z[1]=='*' ){ 9573 z += 2; 9574 while( *z && (*z!='*' || z[1]!='/') ){ z++; } 9575 if( *z==0 ) return 0; 9576 z++; 9577 continue; 9578 } 9579 if( *z=='-' && z[1]=='-' ){ 9580 z += 2; 9581 while( *z && *z!='\n' ){ z++; } 9582 if( *z==0 ) return 1; 9583 continue; 9584 } 9585 return 0; 9586 } 9587 return 1; 9588} 9589 9590/* 9591** Return TRUE if the line typed in is an SQL command terminator other 9592** than a semi-colon. The SQL Server style "go" command is understood 9593** as is the Oracle "/". 9594*/ 9595static int line_is_command_terminator(const char *zLine){ 9596 while( IsSpace(zLine[0]) ){ zLine++; }; 9597 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){ 9598 return 1; /* Oracle */ 9599 } 9600 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' 9601 && _all_whitespace(&zLine[2]) ){ 9602 return 1; /* SQL Server */ 9603 } 9604 return 0; 9605} 9606 9607/* 9608** We need a default sqlite3_complete() implementation to use in case 9609** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes 9610** any arbitrary text is a complete SQL statement. This is not very 9611** user-friendly, but it does seem to work. 9612*/ 9613#ifdef SQLITE_OMIT_COMPLETE 9614#define sqlite3_complete(x) 1 9615#endif 9616 9617/* 9618** Return true if zSql is a complete SQL statement. Return false if it 9619** ends in the middle of a string literal or C-style comment. 9620*/ 9621static int line_is_complete(char *zSql, int nSql){ 9622 int rc; 9623 if( zSql==0 ) return 1; 9624 zSql[nSql] = ';'; 9625 zSql[nSql+1] = 0; 9626 rc = sqlite3_complete(zSql); 9627 zSql[nSql] = 0; 9628 return rc; 9629} 9630 9631/* 9632** Run a single line of SQL. Return the number of errors. 9633*/ 9634static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ 9635 int rc; 9636 char *zErrMsg = 0; 9637 9638 open_db(p, 0); 9639 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); 9640 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 9641 BEGIN_TIMER; 9642 rc = shell_exec(p, zSql, &zErrMsg); 9643 END_TIMER; 9644 if( rc || zErrMsg ){ 9645 char zPrefix[100]; 9646 if( in!=0 || !stdin_is_interactive ){ 9647 sqlite3_snprintf(sizeof(zPrefix), zPrefix, 9648 "Error: near line %d:", startline); 9649 }else{ 9650 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); 9651 } 9652 if( zErrMsg!=0 ){ 9653 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); 9654 sqlite3_free(zErrMsg); 9655 zErrMsg = 0; 9656 }else{ 9657 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); 9658 } 9659 return 1; 9660 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ 9661 raw_printf(p->out, "changes: %3d total_changes: %d\n", 9662 sqlite3_changes(p->db), sqlite3_total_changes(p->db)); 9663 } 9664 return 0; 9665} 9666 9667 9668/* 9669** Read input from *in and process it. If *in==0 then input 9670** is interactive - the user is typing it it. Otherwise, input 9671** is coming from a file or device. A prompt is issued and history 9672** is saved only if input is interactive. An interrupt signal will 9673** cause this routine to exit immediately, unless input is interactive. 9674** 9675** Return the number of errors. 9676*/ 9677static int process_input(ShellState *p){ 9678 char *zLine = 0; /* A single input line */ 9679 char *zSql = 0; /* Accumulated SQL text */ 9680 int nLine; /* Length of current line */ 9681 int nSql = 0; /* Bytes of zSql[] used */ 9682 int nAlloc = 0; /* Allocated zSql[] space */ 9683 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */ 9684 int rc; /* Error code */ 9685 int errCnt = 0; /* Number of errors seen */ 9686 int startline = 0; /* Line number for start of current input */ 9687 9688 p->lineno = 0; 9689 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ 9690 fflush(p->out); 9691 zLine = one_input_line(p->in, zLine, nSql>0); 9692 if( zLine==0 ){ 9693 /* End of input */ 9694 if( p->in==0 && stdin_is_interactive ) printf("\n"); 9695 break; 9696 } 9697 if( seenInterrupt ){ 9698 if( p->in!=0 ) break; 9699 seenInterrupt = 0; 9700 } 9701 p->lineno++; 9702 if( nSql==0 && _all_whitespace(zLine) ){ 9703 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 9704 continue; 9705 } 9706 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ 9707 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 9708 if( zLine[0]=='.' ){ 9709 rc = do_meta_command(zLine, p); 9710 if( rc==2 ){ /* exit requested */ 9711 break; 9712 }else if( rc ){ 9713 errCnt++; 9714 } 9715 } 9716 continue; 9717 } 9718 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ 9719 memcpy(zLine,";",2); 9720 } 9721 nLine = strlen30(zLine); 9722 if( nSql+nLine+2>=nAlloc ){ 9723 nAlloc = nSql+nLine+100; 9724 zSql = realloc(zSql, nAlloc); 9725 if( zSql==0 ) shell_out_of_memory(); 9726 } 9727 nSqlPrior = nSql; 9728 if( nSql==0 ){ 9729 int i; 9730 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} 9731 assert( nAlloc>0 && zSql!=0 ); 9732 memcpy(zSql, zLine+i, nLine+1-i); 9733 startline = p->lineno; 9734 nSql = nLine-i; 9735 }else{ 9736 zSql[nSql++] = '\n'; 9737 memcpy(zSql+nSql, zLine, nLine+1); 9738 nSql += nLine; 9739 } 9740 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) 9741 && sqlite3_complete(zSql) ){ 9742 errCnt += runOneSqlLine(p, zSql, p->in, startline); 9743 nSql = 0; 9744 if( p->outCount ){ 9745 output_reset(p); 9746 p->outCount = 0; 9747 }else{ 9748 clearTempFile(p); 9749 } 9750 }else if( nSql && _all_whitespace(zSql) ){ 9751 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql); 9752 nSql = 0; 9753 } 9754 } 9755 if( nSql && !_all_whitespace(zSql) ){ 9756 errCnt += runOneSqlLine(p, zSql, p->in, startline); 9757 } 9758 free(zSql); 9759 free(zLine); 9760 return errCnt>0; 9761} 9762 9763/* 9764** Return a pathname which is the user's home directory. A 9765** 0 return indicates an error of some kind. 9766*/ 9767static char *find_home_dir(int clearFlag){ 9768 static char *home_dir = NULL; 9769 if( clearFlag ){ 9770 free(home_dir); 9771 home_dir = 0; 9772 return 0; 9773 } 9774 if( home_dir ) return home_dir; 9775 9776#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ 9777 && !defined(__RTP__) && !defined(_WRS_KERNEL) 9778 { 9779 struct passwd *pwent; 9780 uid_t uid = getuid(); 9781 if( (pwent=getpwuid(uid)) != NULL) { 9782 home_dir = pwent->pw_dir; 9783 } 9784 } 9785#endif 9786 9787#if defined(_WIN32_WCE) 9788 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() 9789 */ 9790 home_dir = "/"; 9791#else 9792 9793#if defined(_WIN32) || defined(WIN32) 9794 if (!home_dir) { 9795 home_dir = getenv("USERPROFILE"); 9796 } 9797#endif 9798 9799 if (!home_dir) { 9800 home_dir = getenv("HOME"); 9801 } 9802 9803#if defined(_WIN32) || defined(WIN32) 9804 if (!home_dir) { 9805 char *zDrive, *zPath; 9806 int n; 9807 zDrive = getenv("HOMEDRIVE"); 9808 zPath = getenv("HOMEPATH"); 9809 if( zDrive && zPath ){ 9810 n = strlen30(zDrive) + strlen30(zPath) + 1; 9811 home_dir = malloc( n ); 9812 if( home_dir==0 ) return 0; 9813 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); 9814 return home_dir; 9815 } 9816 home_dir = "c:\\"; 9817 } 9818#endif 9819 9820#endif /* !_WIN32_WCE */ 9821 9822 if( home_dir ){ 9823 int n = strlen30(home_dir) + 1; 9824 char *z = malloc( n ); 9825 if( z ) memcpy(z, home_dir, n); 9826 home_dir = z; 9827 } 9828 9829 return home_dir; 9830} 9831 9832/* 9833** Read input from the file given by sqliterc_override. Or if that 9834** parameter is NULL, take input from ~/.sqliterc 9835** 9836** Returns the number of errors. 9837*/ 9838static void process_sqliterc( 9839 ShellState *p, /* Configuration data */ 9840 const char *sqliterc_override /* Name of config file. NULL to use default */ 9841){ 9842 char *home_dir = NULL; 9843 const char *sqliterc = sqliterc_override; 9844 char *zBuf = 0; 9845 FILE *inSaved = p->in; 9846 int savedLineno = p->lineno; 9847 9848 if (sqliterc == NULL) { 9849 home_dir = find_home_dir(0); 9850 if( home_dir==0 ){ 9851 raw_printf(stderr, "-- warning: cannot find home directory;" 9852 " cannot read ~/.sqliterc\n"); 9853 return; 9854 } 9855 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); 9856 sqliterc = zBuf; 9857 } 9858 p->in = fopen(sqliterc,"rb"); 9859 if( p->in ){ 9860 if( stdin_is_interactive ){ 9861 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); 9862 } 9863 process_input(p); 9864 fclose(p->in); 9865 } 9866 p->in = inSaved; 9867 p->lineno = savedLineno; 9868 sqlite3_free(zBuf); 9869} 9870 9871/* 9872** Show available command line options 9873*/ 9874static const char zOptions[] = 9875#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 9876 " -A ARGS... run \".archive ARGS\" and exit\n" 9877#endif 9878 " -append append the database to the end of the file\n" 9879 " -ascii set output mode to 'ascii'\n" 9880 " -bail stop after hitting an error\n" 9881 " -batch force batch I/O\n" 9882 " -column set output mode to 'column'\n" 9883 " -cmd COMMAND run \"COMMAND\" before reading stdin\n" 9884 " -csv set output mode to 'csv'\n" 9885#if defined(SQLITE_ENABLE_DESERIALIZE) 9886 " -deserialize open the database using sqlite3_deserialize()\n" 9887#endif 9888 " -echo print commands before execution\n" 9889 " -init FILENAME read/process named file\n" 9890 " -[no]header turn headers on or off\n" 9891#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 9892 " -heap SIZE Size of heap for memsys3 or memsys5\n" 9893#endif 9894 " -help show this message\n" 9895 " -html set output mode to HTML\n" 9896 " -interactive force interactive I/O\n" 9897 " -line set output mode to 'line'\n" 9898 " -list set output mode to 'list'\n" 9899 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" 9900#if defined(SQLITE_ENABLE_DESERIALIZE) 9901 " -maxsize N maximum size for a --deserialize database\n" 9902#endif 9903 " -memtrace trace all memory allocations and deallocations\n" 9904 " -mmap N default mmap size set to N\n" 9905#ifdef SQLITE_ENABLE_MULTIPLEX 9906 " -multiplex enable the multiplexor VFS\n" 9907#endif 9908 " -newline SEP set output row separator. Default: '\\n'\n" 9909 " -nullvalue TEXT set text string for NULL values. Default ''\n" 9910 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" 9911 " -quote set output mode to 'quote'\n" 9912 " -readonly open the database read-only\n" 9913 " -separator SEP set output column separator. Default: '|'\n" 9914#ifdef SQLITE_ENABLE_SORTER_REFERENCES 9915 " -sorterref SIZE sorter references threshold size\n" 9916#endif 9917 " -stats print memory stats before each finalize\n" 9918 " -version show SQLite version\n" 9919 " -vfs NAME use NAME as the default VFS\n" 9920#ifdef SQLITE_ENABLE_VFSTRACE 9921 " -vfstrace enable tracing of all VFS calls\n" 9922#endif 9923#ifdef SQLITE_HAVE_ZLIB 9924 " -zip open the file as a ZIP Archive\n" 9925#endif 9926; 9927static void usage(int showDetail){ 9928 utf8_printf(stderr, 9929 "Usage: %s [OPTIONS] FILENAME [SQL]\n" 9930 "FILENAME is the name of an SQLite database. A new database is created\n" 9931 "if the file does not previously exist.\n", Argv0); 9932 if( showDetail ){ 9933 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); 9934 }else{ 9935 raw_printf(stderr, "Use the -help option for additional information\n"); 9936 } 9937 exit(1); 9938} 9939 9940/* 9941** Internal check: Verify that the SQLite is uninitialized. Print a 9942** error message if it is initialized. 9943*/ 9944static void verify_uninitialized(void){ 9945 if( sqlite3_config(-1)==SQLITE_MISUSE ){ 9946 utf8_printf(stdout, "WARNING: attempt to configure SQLite after" 9947 " initialization.\n"); 9948 } 9949} 9950 9951/* 9952** Initialize the state information in data 9953*/ 9954static void main_init(ShellState *data) { 9955 memset(data, 0, sizeof(*data)); 9956 data->normalMode = data->cMode = data->mode = MODE_List; 9957 data->autoExplain = 1; 9958 memcpy(data->colSeparator,SEP_Column, 2); 9959 memcpy(data->rowSeparator,SEP_Row, 2); 9960 data->showHeader = 0; 9961 data->shellFlgs = SHFLG_Lookaside; 9962 verify_uninitialized(); 9963 sqlite3_config(SQLITE_CONFIG_URI, 1); 9964 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); 9965 sqlite3_config(SQLITE_CONFIG_MULTITHREAD); 9966 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); 9967 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); 9968} 9969 9970/* 9971** Output text to the console in a font that attracts extra attention. 9972*/ 9973#ifdef _WIN32 9974static void printBold(const char *zText){ 9975 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 9976 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; 9977 GetConsoleScreenBufferInfo(out, &defaultScreenInfo); 9978 SetConsoleTextAttribute(out, 9979 FOREGROUND_RED|FOREGROUND_INTENSITY 9980 ); 9981 printf("%s", zText); 9982 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); 9983} 9984#else 9985static void printBold(const char *zText){ 9986 printf("\033[1m%s\033[0m", zText); 9987} 9988#endif 9989 9990/* 9991** Get the argument to an --option. Throw an error and die if no argument 9992** is available. 9993*/ 9994static char *cmdline_option_value(int argc, char **argv, int i){ 9995 if( i==argc ){ 9996 utf8_printf(stderr, "%s: Error: missing argument to %s\n", 9997 argv[0], argv[argc-1]); 9998 exit(1); 9999 } 10000 return argv[i]; 10001} 10002 10003#ifndef SQLITE_SHELL_IS_UTF8 10004# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) 10005# define SQLITE_SHELL_IS_UTF8 (0) 10006# else 10007# define SQLITE_SHELL_IS_UTF8 (1) 10008# endif 10009#endif 10010 10011#if SQLITE_SHELL_IS_UTF8 10012int SQLITE_CDECL main(int argc, char **argv){ 10013#else 10014int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ 10015 char **argv; 10016#endif 10017 char *zErrMsg = 0; 10018 ShellState data; 10019 const char *zInitFile = 0; 10020 int i; 10021 int rc = 0; 10022 int warnInmemoryDb = 0; 10023 int readStdin = 1; 10024 int nCmd = 0; 10025 char **azCmd = 0; 10026 const char *zVfs = 0; /* Value of -vfs command-line option */ 10027#if !SQLITE_SHELL_IS_UTF8 10028 char **argvToFree = 0; 10029 int argcToFree = 0; 10030#endif 10031 10032 setBinaryMode(stdin, 0); 10033 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ 10034 stdin_is_interactive = isatty(0); 10035 stdout_is_console = isatty(1); 10036 10037#if !defined(_WIN32_WCE) 10038 if( getenv("SQLITE_DEBUG_BREAK") ){ 10039 if( isatty(0) && isatty(2) ){ 10040 fprintf(stderr, 10041 "attach debugger to process %d and press any key to continue.\n", 10042 GETPID()); 10043 fgetc(stdin); 10044 }else{ 10045#if defined(_WIN32) || defined(WIN32) 10046 DebugBreak(); 10047#elif defined(SIGTRAP) 10048 raise(SIGTRAP); 10049#endif 10050 } 10051 } 10052#endif 10053 10054#if USE_SYSTEM_SQLITE+0!=1 10055 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ 10056 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", 10057 sqlite3_sourceid(), SQLITE_SOURCE_ID); 10058 exit(1); 10059 } 10060#endif 10061 main_init(&data); 10062 10063 /* On Windows, we must translate command-line arguments into UTF-8. 10064 ** The SQLite memory allocator subsystem has to be enabled in order to 10065 ** do this. But we want to run an sqlite3_shutdown() afterwards so that 10066 ** subsequent sqlite3_config() calls will work. So copy all results into 10067 ** memory that does not come from the SQLite memory allocator. 10068 */ 10069#if !SQLITE_SHELL_IS_UTF8 10070 sqlite3_initialize(); 10071 argvToFree = malloc(sizeof(argv[0])*argc*2); 10072 argcToFree = argc; 10073 argv = argvToFree + argc; 10074 if( argv==0 ) shell_out_of_memory(); 10075 for(i=0; i<argc; i++){ 10076 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); 10077 int n; 10078 if( z==0 ) shell_out_of_memory(); 10079 n = (int)strlen(z); 10080 argv[i] = malloc( n+1 ); 10081 if( argv[i]==0 ) shell_out_of_memory(); 10082 memcpy(argv[i], z, n+1); 10083 argvToFree[i] = argv[i]; 10084 sqlite3_free(z); 10085 } 10086 sqlite3_shutdown(); 10087#endif 10088 10089 assert( argc>=1 && argv && argv[0] ); 10090 Argv0 = argv[0]; 10091 10092 /* Make sure we have a valid signal handler early, before anything 10093 ** else is done. 10094 */ 10095#ifdef SIGINT 10096 signal(SIGINT, interrupt_handler); 10097#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 10098 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); 10099#endif 10100 10101#ifdef SQLITE_SHELL_DBNAME_PROC 10102 { 10103 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name 10104 ** of a C-function that will provide the name of the database file. Use 10105 ** this compile-time option to embed this shell program in larger 10106 ** applications. */ 10107 extern void SQLITE_SHELL_DBNAME_PROC(const char**); 10108 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename); 10109 warnInmemoryDb = 0; 10110 } 10111#endif 10112 10113 /* Do an initial pass through the command-line argument to locate 10114 ** the name of the database file, the name of the initialization file, 10115 ** the size of the alternative malloc heap, 10116 ** and the first command to execute. 10117 */ 10118 verify_uninitialized(); 10119 for(i=1; i<argc; i++){ 10120 char *z; 10121 z = argv[i]; 10122 if( z[0]!='-' ){ 10123 if( data.zDbFilename==0 ){ 10124 data.zDbFilename = z; 10125 }else{ 10126 /* Excesss arguments are interpreted as SQL (or dot-commands) and 10127 ** mean that nothing is read from stdin */ 10128 readStdin = 0; 10129 nCmd++; 10130 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); 10131 if( azCmd==0 ) shell_out_of_memory(); 10132 azCmd[nCmd-1] = z; 10133 } 10134 } 10135 if( z[1]=='-' ) z++; 10136 if( strcmp(z,"-separator")==0 10137 || strcmp(z,"-nullvalue")==0 10138 || strcmp(z,"-newline")==0 10139 || strcmp(z,"-cmd")==0 10140 ){ 10141 (void)cmdline_option_value(argc, argv, ++i); 10142 }else if( strcmp(z,"-init")==0 ){ 10143 zInitFile = cmdline_option_value(argc, argv, ++i); 10144 }else if( strcmp(z,"-batch")==0 ){ 10145 /* Need to check for batch mode here to so we can avoid printing 10146 ** informational messages (like from process_sqliterc) before 10147 ** we do the actual processing of arguments later in a second pass. 10148 */ 10149 stdin_is_interactive = 0; 10150 }else if( strcmp(z,"-heap")==0 ){ 10151#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 10152 const char *zSize; 10153 sqlite3_int64 szHeap; 10154 10155 zSize = cmdline_option_value(argc, argv, ++i); 10156 szHeap = integerValue(zSize); 10157 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; 10158 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); 10159#else 10160 (void)cmdline_option_value(argc, argv, ++i); 10161#endif 10162 }else if( strcmp(z,"-pagecache")==0 ){ 10163 int n, sz; 10164 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10165 if( sz>70000 ) sz = 70000; 10166 if( sz<0 ) sz = 0; 10167 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10168 sqlite3_config(SQLITE_CONFIG_PAGECACHE, 10169 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); 10170 data.shellFlgs |= SHFLG_Pagecache; 10171 }else if( strcmp(z,"-lookaside")==0 ){ 10172 int n, sz; 10173 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10174 if( sz<0 ) sz = 0; 10175 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10176 if( n<0 ) n = 0; 10177 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); 10178 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; 10179#ifdef SQLITE_ENABLE_VFSTRACE 10180 }else if( strcmp(z,"-vfstrace")==0 ){ 10181 extern int vfstrace_register( 10182 const char *zTraceName, 10183 const char *zOldVfsName, 10184 int (*xOut)(const char*,void*), 10185 void *pOutArg, 10186 int makeDefault 10187 ); 10188 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); 10189#endif 10190#ifdef SQLITE_ENABLE_MULTIPLEX 10191 }else if( strcmp(z,"-multiplex")==0 ){ 10192 extern int sqlite3_multiple_initialize(const char*,int); 10193 sqlite3_multiplex_initialize(0, 1); 10194#endif 10195 }else if( strcmp(z,"-mmap")==0 ){ 10196 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 10197 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); 10198#ifdef SQLITE_ENABLE_SORTER_REFERENCES 10199 }else if( strcmp(z,"-sorterref")==0 ){ 10200 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 10201 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); 10202#endif 10203 }else if( strcmp(z,"-vfs")==0 ){ 10204 zVfs = cmdline_option_value(argc, argv, ++i); 10205#ifdef SQLITE_HAVE_ZLIB 10206 }else if( strcmp(z,"-zip")==0 ){ 10207 data.openMode = SHELL_OPEN_ZIPFILE; 10208#endif 10209 }else if( strcmp(z,"-append")==0 ){ 10210 data.openMode = SHELL_OPEN_APPENDVFS; 10211#ifdef SQLITE_ENABLE_DESERIALIZE 10212 }else if( strcmp(z,"-deserialize")==0 ){ 10213 data.openMode = SHELL_OPEN_DESERIALIZE; 10214 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 10215 data.szMax = integerValue(argv[++i]); 10216#endif 10217 }else if( strcmp(z,"-readonly")==0 ){ 10218 data.openMode = SHELL_OPEN_READONLY; 10219#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 10220 }else if( strncmp(z, "-A",2)==0 ){ 10221 /* All remaining command-line arguments are passed to the ".archive" 10222 ** command, so ignore them */ 10223 break; 10224#endif 10225 }else if( strcmp(z, "-memtrace")==0 ){ 10226 sqlite3MemTraceActivate(stderr); 10227 } 10228 } 10229 verify_uninitialized(); 10230 10231 10232#ifdef SQLITE_SHELL_INIT_PROC 10233 { 10234 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name 10235 ** of a C-function that will perform initialization actions on SQLite that 10236 ** occur just before or after sqlite3_initialize(). Use this compile-time 10237 ** option to embed this shell program in larger applications. */ 10238 extern void SQLITE_SHELL_INIT_PROC(void); 10239 SQLITE_SHELL_INIT_PROC(); 10240 } 10241#else 10242 /* All the sqlite3_config() calls have now been made. So it is safe 10243 ** to call sqlite3_initialize() and process any command line -vfs option. */ 10244 sqlite3_initialize(); 10245#endif 10246 10247 if( zVfs ){ 10248 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); 10249 if( pVfs ){ 10250 sqlite3_vfs_register(pVfs, 1); 10251 }else{ 10252 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); 10253 exit(1); 10254 } 10255 } 10256 10257 if( data.zDbFilename==0 ){ 10258#ifndef SQLITE_OMIT_MEMORYDB 10259 data.zDbFilename = ":memory:"; 10260 warnInmemoryDb = argc==1; 10261#else 10262 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); 10263 return 1; 10264#endif 10265 } 10266 data.out = stdout; 10267 sqlite3_appendvfs_init(0,0,0); 10268 10269 /* Go ahead and open the database file if it already exists. If the 10270 ** file does not exist, delay opening it. This prevents empty database 10271 ** files from being created if a user mistypes the database name argument 10272 ** to the sqlite command-line tool. 10273 */ 10274 if( access(data.zDbFilename, 0)==0 ){ 10275 open_db(&data, 0); 10276 } 10277 10278 /* Process the initialization file if there is one. If no -init option 10279 ** is given on the command line, look for a file named ~/.sqliterc and 10280 ** try to process it. 10281 */ 10282 process_sqliterc(&data,zInitFile); 10283 10284 /* Make a second pass through the command-line argument and set 10285 ** options. This second pass is delayed until after the initialization 10286 ** file is processed so that the command-line arguments will override 10287 ** settings in the initialization file. 10288 */ 10289 for(i=1; i<argc; i++){ 10290 char *z = argv[i]; 10291 if( z[0]!='-' ) continue; 10292 if( z[1]=='-' ){ z++; } 10293 if( strcmp(z,"-init")==0 ){ 10294 i++; 10295 }else if( strcmp(z,"-html")==0 ){ 10296 data.mode = MODE_Html; 10297 }else if( strcmp(z,"-list")==0 ){ 10298 data.mode = MODE_List; 10299 }else if( strcmp(z,"-quote")==0 ){ 10300 data.mode = MODE_Quote; 10301 }else if( strcmp(z,"-line")==0 ){ 10302 data.mode = MODE_Line; 10303 }else if( strcmp(z,"-column")==0 ){ 10304 data.mode = MODE_Column; 10305 }else if( strcmp(z,"-csv")==0 ){ 10306 data.mode = MODE_Csv; 10307 memcpy(data.colSeparator,",",2); 10308#ifdef SQLITE_HAVE_ZLIB 10309 }else if( strcmp(z,"-zip")==0 ){ 10310 data.openMode = SHELL_OPEN_ZIPFILE; 10311#endif 10312 }else if( strcmp(z,"-append")==0 ){ 10313 data.openMode = SHELL_OPEN_APPENDVFS; 10314#ifdef SQLITE_ENABLE_DESERIALIZE 10315 }else if( strcmp(z,"-deserialize")==0 ){ 10316 data.openMode = SHELL_OPEN_DESERIALIZE; 10317 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 10318 data.szMax = integerValue(argv[++i]); 10319#endif 10320 }else if( strcmp(z,"-readonly")==0 ){ 10321 data.openMode = SHELL_OPEN_READONLY; 10322 }else if( strcmp(z,"-ascii")==0 ){ 10323 data.mode = MODE_Ascii; 10324 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 10325 SEP_Unit); 10326 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 10327 SEP_Record); 10328 }else if( strcmp(z,"-separator")==0 ){ 10329 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 10330 "%s",cmdline_option_value(argc,argv,++i)); 10331 }else if( strcmp(z,"-newline")==0 ){ 10332 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 10333 "%s",cmdline_option_value(argc,argv,++i)); 10334 }else if( strcmp(z,"-nullvalue")==0 ){ 10335 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, 10336 "%s",cmdline_option_value(argc,argv,++i)); 10337 }else if( strcmp(z,"-header")==0 ){ 10338 data.showHeader = 1; 10339 }else if( strcmp(z,"-noheader")==0 ){ 10340 data.showHeader = 0; 10341 }else if( strcmp(z,"-echo")==0 ){ 10342 ShellSetFlag(&data, SHFLG_Echo); 10343 }else if( strcmp(z,"-eqp")==0 ){ 10344 data.autoEQP = AUTOEQP_on; 10345 }else if( strcmp(z,"-eqpfull")==0 ){ 10346 data.autoEQP = AUTOEQP_full; 10347 }else if( strcmp(z,"-stats")==0 ){ 10348 data.statsOn = 1; 10349 }else if( strcmp(z,"-scanstats")==0 ){ 10350 data.scanstatsOn = 1; 10351 }else if( strcmp(z,"-backslash")==0 ){ 10352 /* Undocumented command-line option: -backslash 10353 ** Causes C-style backslash escapes to be evaluated in SQL statements 10354 ** prior to sending the SQL into SQLite. Useful for injecting 10355 ** crazy bytes in the middle of SQL statements for testing and debugging. 10356 */ 10357 ShellSetFlag(&data, SHFLG_Backslash); 10358 }else if( strcmp(z,"-bail")==0 ){ 10359 bail_on_error = 1; 10360 }else if( strcmp(z,"-version")==0 ){ 10361 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 10362 return 0; 10363 }else if( strcmp(z,"-interactive")==0 ){ 10364 stdin_is_interactive = 1; 10365 }else if( strcmp(z,"-batch")==0 ){ 10366 stdin_is_interactive = 0; 10367 }else if( strcmp(z,"-heap")==0 ){ 10368 i++; 10369 }else if( strcmp(z,"-pagecache")==0 ){ 10370 i+=2; 10371 }else if( strcmp(z,"-lookaside")==0 ){ 10372 i+=2; 10373 }else if( strcmp(z,"-mmap")==0 ){ 10374 i++; 10375 }else if( strcmp(z,"-memtrace")==0 ){ 10376 i++; 10377#ifdef SQLITE_ENABLE_SORTER_REFERENCES 10378 }else if( strcmp(z,"-sorterref")==0 ){ 10379 i++; 10380#endif 10381 }else if( strcmp(z,"-vfs")==0 ){ 10382 i++; 10383#ifdef SQLITE_ENABLE_VFSTRACE 10384 }else if( strcmp(z,"-vfstrace")==0 ){ 10385 i++; 10386#endif 10387#ifdef SQLITE_ENABLE_MULTIPLEX 10388 }else if( strcmp(z,"-multiplex")==0 ){ 10389 i++; 10390#endif 10391 }else if( strcmp(z,"-help")==0 ){ 10392 usage(1); 10393 }else if( strcmp(z,"-cmd")==0 ){ 10394 /* Run commands that follow -cmd first and separately from commands 10395 ** that simply appear on the command-line. This seems goofy. It would 10396 ** be better if all commands ran in the order that they appear. But 10397 ** we retain the goofy behavior for historical compatibility. */ 10398 if( i==argc-1 ) break; 10399 z = cmdline_option_value(argc,argv,++i); 10400 if( z[0]=='.' ){ 10401 rc = do_meta_command(z, &data); 10402 if( rc && bail_on_error ) return rc==2 ? 0 : rc; 10403 }else{ 10404 open_db(&data, 0); 10405 rc = shell_exec(&data, z, &zErrMsg); 10406 if( zErrMsg!=0 ){ 10407 utf8_printf(stderr,"Error: %s\n", zErrMsg); 10408 if( bail_on_error ) return rc!=0 ? rc : 1; 10409 }else if( rc!=0 ){ 10410 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); 10411 if( bail_on_error ) return rc; 10412 } 10413 } 10414#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 10415 }else if( strncmp(z, "-A", 2)==0 ){ 10416 if( nCmd>0 ){ 10417 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" 10418 " with \"%s\"\n", z); 10419 return 1; 10420 } 10421 open_db(&data, OPEN_DB_ZIPFILE); 10422 if( z[2] ){ 10423 argv[i] = &z[2]; 10424 arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); 10425 }else{ 10426 arDotCommand(&data, 1, argv+i, argc-i); 10427 } 10428 readStdin = 0; 10429 break; 10430#endif 10431 }else{ 10432 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); 10433 raw_printf(stderr,"Use -help for a list of options.\n"); 10434 return 1; 10435 } 10436 data.cMode = data.mode; 10437 } 10438 10439 if( !readStdin ){ 10440 /* Run all arguments that do not begin with '-' as if they were separate 10441 ** command-line inputs, except for the argToSkip argument which contains 10442 ** the database filename. 10443 */ 10444 for(i=0; i<nCmd; i++){ 10445 if( azCmd[i][0]=='.' ){ 10446 rc = do_meta_command(azCmd[i], &data); 10447 if( rc ) return rc==2 ? 0 : rc; 10448 }else{ 10449 open_db(&data, 0); 10450 rc = shell_exec(&data, azCmd[i], &zErrMsg); 10451 if( zErrMsg!=0 ){ 10452 utf8_printf(stderr,"Error: %s\n", zErrMsg); 10453 return rc!=0 ? rc : 1; 10454 }else if( rc!=0 ){ 10455 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); 10456 return rc; 10457 } 10458 } 10459 } 10460 free(azCmd); 10461 }else{ 10462 /* Run commands received from standard input 10463 */ 10464 if( stdin_is_interactive ){ 10465 char *zHome; 10466 char *zHistory; 10467 int nHistory; 10468 printf( 10469 "SQLite version %s %.19s\n" /*extra-version-info*/ 10470 "Enter \".help\" for usage hints.\n", 10471 sqlite3_libversion(), sqlite3_sourceid() 10472 ); 10473 if( warnInmemoryDb ){ 10474 printf("Connected to a "); 10475 printBold("transient in-memory database"); 10476 printf(".\nUse \".open FILENAME\" to reopen on a " 10477 "persistent database.\n"); 10478 } 10479 zHistory = getenv("SQLITE_HISTORY"); 10480 if( zHistory ){ 10481 zHistory = strdup(zHistory); 10482 }else if( (zHome = find_home_dir(0))!=0 ){ 10483 nHistory = strlen30(zHome) + 20; 10484 if( (zHistory = malloc(nHistory))!=0 ){ 10485 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); 10486 } 10487 } 10488 if( zHistory ){ shell_read_history(zHistory); } 10489#if HAVE_READLINE || HAVE_EDITLINE 10490 rl_attempted_completion_function = readline_completion; 10491#elif HAVE_LINENOISE 10492 linenoiseSetCompletionCallback(linenoise_completion); 10493#endif 10494 data.in = 0; 10495 rc = process_input(&data); 10496 if( zHistory ){ 10497 shell_stifle_history(2000); 10498 shell_write_history(zHistory); 10499 free(zHistory); 10500 } 10501 }else{ 10502 data.in = stdin; 10503 rc = process_input(&data); 10504 } 10505 } 10506 set_table_name(&data, 0); 10507 if( data.db ){ 10508 session_close_all(&data); 10509 close_db(data.db); 10510 } 10511 sqlite3_free(data.zFreeOnClose); 10512 find_home_dir(1); 10513 output_reset(&data); 10514 data.doXdgOpen = 0; 10515 clearTempFile(&data); 10516#if !SQLITE_SHELL_IS_UTF8 10517 for(i=0; i<argcToFree; i++) free(argvToFree[i]); 10518 free(argvToFree); 10519#endif 10520 /* Clear the global data structure so that valgrind will detect memory 10521 ** leaks */ 10522 memset(&data, 0, sizeof(data)); 10523 return rc; 10524} 10525