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